1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/url_request/url_request_http_job.h"
6
7 #include <stdint.h>
8
9 #include <cstddef>
10 #include <memory>
11 #include <utility>
12 #include <vector>
13
14 #include "base/compiler_specific.h"
15 #include "base/memory/ptr_util.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/run_loop.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_split.h"
20 #include "base/test/bind.h"
21 #include "base/test/gmock_callback_support.h"
22 #include "base/test/metrics/histogram_tester.h"
23 #include "base/test/scoped_feature_list.h"
24 #include "base/test/task_environment.h"
25 #include "build/build_config.h"
26 #include "net/base/auth.h"
27 #include "net/base/features.h"
28 #include "net/base/isolation_info.h"
29 #include "net/base/load_flags.h"
30 #include "net/base/proxy_chain.h"
31 #include "net/base/proxy_server.h"
32 #include "net/base/proxy_string_util.h"
33 #include "net/base/request_priority.h"
34 #include "net/base/test_proxy_delegate.h"
35 #include "net/cert/ct_policy_status.h"
36 #include "net/cookies/canonical_cookie_test_helpers.h"
37 #include "net/cookies/cookie_monster.h"
38 #include "net/cookies/cookie_store_test_callbacks.h"
39 #include "net/cookies/cookie_store_test_helpers.h"
40 #include "net/cookies/test_cookie_access_delegate.h"
41 #include "net/http/http_transaction_factory.h"
42 #include "net/http/http_transaction_test_util.h"
43 #include "net/http/transport_security_state.h"
44 #include "net/log/net_log_event_type.h"
45 #include "net/log/test_net_log.h"
46 #include "net/log/test_net_log_util.h"
47 #include "net/net_buildflags.h"
48 #include "net/proxy_resolution/configured_proxy_resolution_service.h"
49 #include "net/socket/next_proto.h"
50 #include "net/socket/socket_test_util.h"
51 #include "net/test/cert_test_util.h"
52 #include "net/test/embedded_test_server/default_handlers.h"
53 #include "net/test/gtest_util.h"
54 #include "net/test/test_data_directory.h"
55 #include "net/test/test_with_task_environment.h"
56 #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
57 #include "net/url_request/url_request.h"
58 #include "net/url_request/url_request_context.h"
59 #include "net/url_request/url_request_context_builder.h"
60 #include "net/url_request/url_request_test_util.h"
61 #include "net/url_request/websocket_handshake_userdata_key.h"
62 #include "net/websockets/websocket_test_util.h"
63 #include "testing/gmock/include/gmock/gmock.h"
64 #include "testing/gtest/include/gtest/gtest.h"
65 #include "url/gurl.h"
66 #include "url/url_constants.h"
67
68 #if BUILDFLAG(IS_ANDROID)
69 #include "base/android/jni_android.h"
70 #include "net/android/net_test_support_jni/AndroidNetworkLibraryTestUtil_jni.h"
71 #endif
72
73 #if BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS)
74 #include "net/device_bound_sessions/mock_session_service.h"
75 #include "net/device_bound_sessions/session_service.h"
76 #endif
77
78 using net::test::IsError;
79 using net::test::IsOk;
80
81 namespace net {
82
83 namespace {
84
85 using ::testing::_;
86 using ::testing::InSequence;
87 using ::testing::Invoke;
88 using ::testing::Return;
89 using ::testing::UnorderedElementsAre;
90 using ::testing::Unused;
91
92 const char kSimpleGetMockWrite[] =
93 "GET / HTTP/1.1\r\n"
94 "Host: www.example.com\r\n"
95 "Connection: keep-alive\r\n"
96 "User-Agent: \r\n"
97 "Accept-Encoding: gzip, deflate\r\n"
98 "Accept-Language: en-us,fr\r\n\r\n";
99
100 const char kSimpleHeadMockWrite[] =
101 "HEAD / HTTP/1.1\r\n"
102 "Host: www.example.com\r\n"
103 "Connection: keep-alive\r\n"
104 "User-Agent: \r\n"
105 "Accept-Encoding: gzip, deflate\r\n"
106 "Accept-Language: en-us,fr\r\n\r\n";
107
108 const char kTrustAnchorRequestHistogram[] =
109 "Net.Certificate.TrustAnchor.Request";
110
111 // Inherit from URLRequestHttpJob to expose the priority and some
112 // other hidden functions.
113 class TestURLRequestHttpJob : public URLRequestHttpJob {
114 public:
TestURLRequestHttpJob(URLRequest * request)115 explicit TestURLRequestHttpJob(URLRequest* request)
116 : URLRequestHttpJob(request,
117 request->context()->http_user_agent_settings()) {}
118
119 TestURLRequestHttpJob(const TestURLRequestHttpJob&) = delete;
120 TestURLRequestHttpJob& operator=(const TestURLRequestHttpJob&) = delete;
121
122 ~TestURLRequestHttpJob() override = default;
123
124 // URLRequestJob implementation:
SetUpSourceStream()125 std::unique_ptr<SourceStream> SetUpSourceStream() override {
126 if (use_null_source_stream_)
127 return nullptr;
128 return URLRequestHttpJob::SetUpSourceStream();
129 }
130
set_use_null_source_stream(bool use_null_source_stream)131 void set_use_null_source_stream(bool use_null_source_stream) {
132 use_null_source_stream_ = use_null_source_stream;
133 }
134
135 using URLRequestHttpJob::SetPriority;
136 using URLRequestHttpJob::Start;
137 using URLRequestHttpJob::Kill;
138 using URLRequestHttpJob::priority;
139
140 private:
141 bool use_null_source_stream_ = false;
142 };
143
144 class URLRequestHttpJobSetUpSourceTest : public TestWithTaskEnvironment {
145 public:
URLRequestHttpJobSetUpSourceTest()146 URLRequestHttpJobSetUpSourceTest() {
147 auto context_builder = CreateTestURLRequestContextBuilder();
148 context_builder->set_client_socket_factory_for_testing(&socket_factory_);
149 context_ = context_builder->Build();
150 }
151
152 protected:
153 MockClientSocketFactory socket_factory_;
154
155 std::unique_ptr<URLRequestContext> context_;
156 TestDelegate delegate_;
157 };
158
159 // Tests that if SetUpSourceStream() returns nullptr, the request fails.
TEST_F(URLRequestHttpJobSetUpSourceTest,SetUpSourceFails)160 TEST_F(URLRequestHttpJobSetUpSourceTest, SetUpSourceFails) {
161 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
162 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
163 "Content-Length: 12\r\n\r\n"),
164 MockRead("Test Content")};
165
166 StaticSocketDataProvider socket_data(reads, writes);
167 socket_factory_.AddSocketDataProvider(&socket_data);
168
169 std::unique_ptr<URLRequest> request =
170 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
171 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
172 auto job = std::make_unique<TestURLRequestHttpJob>(request.get());
173 job->set_use_null_source_stream(true);
174 TestScopedURLInterceptor interceptor(request->url(), std::move(job));
175 request->Start();
176
177 delegate_.RunUntilComplete();
178 EXPECT_EQ(ERR_CONTENT_DECODING_INIT_FAILED, delegate_.request_status());
179 }
180
181 // Tests that if there is an unknown content-encoding type, the raw response
182 // body is passed through.
TEST_F(URLRequestHttpJobSetUpSourceTest,UnknownEncoding)183 TEST_F(URLRequestHttpJobSetUpSourceTest, UnknownEncoding) {
184 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
185 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
186 "Content-Encoding: foo, gzip\r\n"
187 "Content-Length: 12\r\n\r\n"),
188 MockRead("Test Content")};
189
190 StaticSocketDataProvider socket_data(reads, writes);
191 socket_factory_.AddSocketDataProvider(&socket_data);
192
193 std::unique_ptr<URLRequest> request =
194 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
195 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
196 auto job = std::make_unique<TestURLRequestHttpJob>(request.get());
197 TestScopedURLInterceptor interceptor(request->url(), std::move(job));
198 request->Start();
199
200 delegate_.RunUntilComplete();
201 EXPECT_EQ(OK, delegate_.request_status());
202 EXPECT_EQ("Test Content", delegate_.data_received());
203 }
204
205 // TaskEnvironment is required to instantiate a
206 // net::ConfiguredProxyResolutionService, which registers itself as an IP
207 // Address Observer with the NetworkChangeNotifier.
208 using URLRequestHttpJobWithProxyTest = TestWithTaskEnvironment;
209
210 class URLRequestHttpJobWithProxy {
211 public:
URLRequestHttpJobWithProxy(std::unique_ptr<ProxyResolutionService> proxy_resolution_service)212 explicit URLRequestHttpJobWithProxy(
213 std::unique_ptr<ProxyResolutionService> proxy_resolution_service) {
214 auto context_builder = CreateTestURLRequestContextBuilder();
215 context_builder->set_client_socket_factory_for_testing(&socket_factory_);
216 if (proxy_resolution_service) {
217 context_builder->set_proxy_resolution_service(
218 std::move(proxy_resolution_service));
219 }
220 context_ = context_builder->Build();
221 }
222
223 URLRequestHttpJobWithProxy(const URLRequestHttpJobWithProxy&) = delete;
224 URLRequestHttpJobWithProxy& operator=(const URLRequestHttpJobWithProxy&) =
225 delete;
226
227 MockClientSocketFactory socket_factory_;
228 std::unique_ptr<URLRequestContext> context_;
229 };
230
231 // Tests that when a proxy is not used, the proxy chain is set correctly on the
232 // URLRequest.
TEST_F(URLRequestHttpJobWithProxyTest,TestFailureWithoutProxy)233 TEST_F(URLRequestHttpJobWithProxyTest, TestFailureWithoutProxy) {
234 URLRequestHttpJobWithProxy http_job_with_proxy(nullptr);
235
236 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
237 MockRead reads[] = {MockRead(SYNCHRONOUS, ERR_CONNECTION_RESET)};
238
239 StaticSocketDataProvider socket_data(reads, writes);
240 http_job_with_proxy.socket_factory_.AddSocketDataProvider(&socket_data);
241
242 TestDelegate delegate;
243 std::unique_ptr<URLRequest> request =
244 http_job_with_proxy.context_->CreateRequest(
245 GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
246 TRAFFIC_ANNOTATION_FOR_TESTS);
247
248 request->Start();
249 ASSERT_TRUE(request->is_pending());
250 delegate.RunUntilComplete();
251
252 EXPECT_THAT(delegate.request_status(), IsError(ERR_CONNECTION_RESET));
253 EXPECT_EQ(ProxyChain::Direct(), request->proxy_chain());
254 EXPECT_EQ(0, request->received_response_content_length());
255 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
256 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
257 }
258
259 // Tests that when one proxy chain is in use and the connection to a proxy
260 // server in the proxy chain fails, the proxy chain is still set correctly on
261 // the URLRequest.
TEST_F(URLRequestHttpJobWithProxyTest,TestSuccessfulWithOneProxy)262 TEST_F(URLRequestHttpJobWithProxyTest, TestSuccessfulWithOneProxy) {
263 const char kSimpleProxyGetMockWrite[] =
264 "GET http://www.example.com/ HTTP/1.1\r\n"
265 "Host: www.example.com\r\n"
266 "Proxy-Connection: keep-alive\r\n"
267 "User-Agent: \r\n"
268 "Accept-Encoding: gzip, deflate\r\n"
269 "Accept-Language: en-us,fr\r\n\r\n";
270
271 const ProxyChain proxy_chain =
272 ProxyUriToProxyChain("http://origin.net:80", ProxyServer::SCHEME_HTTP);
273
274 std::unique_ptr<ProxyResolutionService> proxy_resolution_service =
275 ConfiguredProxyResolutionService::CreateFixedFromPacResultForTest(
276 ProxyServerToPacResultElement(proxy_chain.First()),
277 TRAFFIC_ANNOTATION_FOR_TESTS);
278
279 MockWrite writes[] = {MockWrite(kSimpleProxyGetMockWrite)};
280 MockRead reads[] = {MockRead(SYNCHRONOUS, ERR_CONNECTION_RESET)};
281
282 StaticSocketDataProvider socket_data(reads, writes);
283
284 URLRequestHttpJobWithProxy http_job_with_proxy(
285 std::move(proxy_resolution_service));
286 http_job_with_proxy.socket_factory_.AddSocketDataProvider(&socket_data);
287
288 TestDelegate delegate;
289 std::unique_ptr<URLRequest> request =
290 http_job_with_proxy.context_->CreateRequest(
291 GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
292 TRAFFIC_ANNOTATION_FOR_TESTS);
293
294 request->Start();
295 ASSERT_TRUE(request->is_pending());
296 delegate.RunUntilComplete();
297
298 EXPECT_THAT(delegate.request_status(), IsError(ERR_CONNECTION_RESET));
299 // When request fails due to proxy connection errors, the proxy chain should
300 // still be set on the `request`.
301 EXPECT_EQ(proxy_chain, request->proxy_chain());
302 EXPECT_EQ(0, request->received_response_content_length());
303 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
304 EXPECT_EQ(0, request->GetTotalReceivedBytes());
305 }
306
307 // Tests that when two proxy chains are in use and the connection to a proxy
308 // server in the first proxy chain fails, the proxy chain is set correctly on
309 // the URLRequest.
TEST_F(URLRequestHttpJobWithProxyTest,TestContentLengthSuccessfulRequestWithTwoProxies)310 TEST_F(URLRequestHttpJobWithProxyTest,
311 TestContentLengthSuccessfulRequestWithTwoProxies) {
312 const ProxyChain proxy_chain =
313 ProxyUriToProxyChain("http://origin.net:80", ProxyServer::SCHEME_HTTP);
314
315 // Connection to `proxy_chain` would fail. Request should be fetched over
316 // DIRECT.
317 std::unique_ptr<ProxyResolutionService> proxy_resolution_service =
318 ConfiguredProxyResolutionService::CreateFixedFromPacResultForTest(
319 ProxyServerToPacResultElement(proxy_chain.First()) + "; DIRECT",
320 TRAFFIC_ANNOTATION_FOR_TESTS);
321
322 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
323 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
324 "Content-Length: 12\r\n\r\n"),
325 MockRead("Test Content"), MockRead(ASYNC, OK)};
326
327 MockConnect mock_connect_1(SYNCHRONOUS, ERR_CONNECTION_RESET);
328 StaticSocketDataProvider connect_data_1;
329 connect_data_1.set_connect_data(mock_connect_1);
330
331 StaticSocketDataProvider socket_data(reads, writes);
332
333 URLRequestHttpJobWithProxy http_job_with_proxy(
334 std::move(proxy_resolution_service));
335 http_job_with_proxy.socket_factory_.AddSocketDataProvider(&connect_data_1);
336 http_job_with_proxy.socket_factory_.AddSocketDataProvider(&socket_data);
337
338 TestDelegate delegate;
339 std::unique_ptr<URLRequest> request =
340 http_job_with_proxy.context_->CreateRequest(
341 GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
342 TRAFFIC_ANNOTATION_FOR_TESTS);
343
344 request->Start();
345 ASSERT_TRUE(request->is_pending());
346 delegate.RunUntilComplete();
347
348 EXPECT_THAT(delegate.request_status(), IsOk());
349 EXPECT_EQ(ProxyChain::Direct(), request->proxy_chain());
350 EXPECT_EQ(12, request->received_response_content_length());
351 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
352 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
353 }
354
355 // Test that the IP Protection-specific metrics get recorded as expected when
356 // the direct-only param is enabled.
TEST_F(URLRequestHttpJobWithProxyTest,IpProtectionDirectOnlyProxyMetricsRecorded)357 TEST_F(URLRequestHttpJobWithProxyTest,
358 IpProtectionDirectOnlyProxyMetricsRecorded) {
359 base::test::ScopedFeatureList scoped_feature_list;
360 scoped_feature_list.InitAndEnableFeatureWithParameters(
361 net::features::kEnableIpProtectionProxy,
362 {{net::features::kIpPrivacyDirectOnly.name, "true"}});
363 const auto kIpProtectionDirectChain =
364 ProxyChain::ForIpProtection(std::vector<ProxyServer>());
365
366 std::unique_ptr<ProxyResolutionService> proxy_resolution_service =
367 ConfiguredProxyResolutionService::CreateFixedForTest(
368 "https://not-used:70", TRAFFIC_ANNOTATION_FOR_TESTS);
369 auto proxy_delegate = std::make_unique<TestProxyDelegate>();
370 proxy_delegate->set_proxy_chain(kIpProtectionDirectChain);
371 proxy_resolution_service->SetProxyDelegate(proxy_delegate.get());
372
373 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
374
375 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
376 "Content-Length: 12\r\n\r\n"),
377 MockRead("Test Content")};
378
379 StaticSocketDataProvider socket_data(reads, writes);
380
381 URLRequestHttpJobWithProxy http_job_with_proxy(
382 std::move(proxy_resolution_service));
383 http_job_with_proxy.socket_factory_.AddSocketDataProvider(&socket_data);
384
385 TestDelegate delegate;
386 base::HistogramTester histogram_tester;
387 std::unique_ptr<URLRequest> request =
388 http_job_with_proxy.context_->CreateRequest(
389 GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
390 TRAFFIC_ANNOTATION_FOR_TESTS);
391
392 request->Start();
393 ASSERT_TRUE(request->is_pending());
394 delegate.RunUntilComplete();
395
396 EXPECT_THAT(delegate.request_status(), IsOk());
397 EXPECT_EQ(kIpProtectionDirectChain, request->proxy_chain());
398 EXPECT_EQ(12, request->received_response_content_length());
399 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
400 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
401
402 histogram_tester.ExpectUniqueSample("Net.HttpJob.IpProtection.BytesSent",
403 std::size(kSimpleGetMockWrite),
404 /*expected_bucket_count=*/1);
405
406 histogram_tester.ExpectUniqueSample(
407 "Net.HttpJob.IpProtection.PrefilterBytesRead.Net",
408 /*sample=*/12, /*expected_bucket_count=*/1);
409
410 histogram_tester.ExpectUniqueSample(
411 "Net.HttpJob.IpProtection.JobResult",
412 /*sample=*/URLRequestHttpJob::IpProtectionJobResult::kProtectionSuccess,
413 /*expected_bucket_count=*/1);
414 }
415
416 // Test that IP Protection-specific metrics are NOT recorded for direct requests
417 // when the direct-only param is disabled.
TEST_F(URLRequestHttpJobWithProxyTest,IpProtectionDirectProxyMetricsRecorded)418 TEST_F(URLRequestHttpJobWithProxyTest, IpProtectionDirectProxyMetricsRecorded) {
419 base::test::ScopedFeatureList scoped_feature_list;
420 scoped_feature_list.InitAndEnableFeatureWithParameters(
421 net::features::kEnableIpProtectionProxy,
422 {{net::features::kIpPrivacyDirectOnly.name, "false"}});
423 const auto kIpProtectionDirectChain =
424 ProxyChain::ForIpProtection(std::vector<ProxyServer>());
425
426 std::unique_ptr<ProxyResolutionService> proxy_resolution_service =
427 ConfiguredProxyResolutionService::CreateFixedForTest(
428 "https://not-used:70", TRAFFIC_ANNOTATION_FOR_TESTS);
429 auto proxy_delegate = std::make_unique<TestProxyDelegate>();
430 proxy_delegate->set_proxy_chain(kIpProtectionDirectChain);
431 proxy_resolution_service->SetProxyDelegate(proxy_delegate.get());
432
433 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
434
435 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
436 "Content-Length: 12\r\n\r\n"),
437 MockRead("Test Content")};
438
439 StaticSocketDataProvider socket_data(reads, writes);
440
441 URLRequestHttpJobWithProxy http_job_with_proxy(
442 std::move(proxy_resolution_service));
443 http_job_with_proxy.socket_factory_.AddSocketDataProvider(&socket_data);
444
445 TestDelegate delegate;
446 base::HistogramTester histogram_tester;
447 std::unique_ptr<URLRequest> request =
448 http_job_with_proxy.context_->CreateRequest(
449 GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
450 TRAFFIC_ANNOTATION_FOR_TESTS);
451
452 request->Start();
453 ASSERT_TRUE(request->is_pending());
454 delegate.RunUntilComplete();
455
456 EXPECT_THAT(delegate.request_status(), IsOk());
457 EXPECT_EQ(kIpProtectionDirectChain, request->proxy_chain());
458 EXPECT_EQ(12, request->received_response_content_length());
459 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
460 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
461
462 histogram_tester.ExpectTotalCount("Net.HttpJob.IpProtection.BytesSent", 0);
463 histogram_tester.ExpectTotalCount(
464 "Net.HttpJob.IpProtection.PrefilterBytesRead.Net", 0);
465 }
466
467 class URLRequestHttpJobTest : public TestWithTaskEnvironment {
468 protected:
URLRequestHttpJobTest()469 URLRequestHttpJobTest() {
470 auto context_builder = CreateTestURLRequestContextBuilder();
471 context_builder->SetHttpTransactionFactoryForTesting(
472 std::make_unique<MockNetworkLayer>());
473 context_builder->DisableHttpCache();
474 context_builder->set_net_log(NetLog::Get());
475 context_ = context_builder->Build();
476
477 req_ = context_->CreateRequest(GURL("http://www.example.com"),
478 DEFAULT_PRIORITY, &delegate_,
479 TRAFFIC_ANNOTATION_FOR_TESTS);
480 }
481
network_layer()482 MockNetworkLayer& network_layer() {
483 // This cast is safe because we set a MockNetworkLayer in the constructor.
484 return *static_cast<MockNetworkLayer*>(
485 context_->http_transaction_factory());
486 }
487
CreateFirstPartyRequest(const URLRequestContext & context,const GURL & url,URLRequest::Delegate * delegate)488 std::unique_ptr<URLRequest> CreateFirstPartyRequest(
489 const URLRequestContext& context,
490 const GURL& url,
491 URLRequest::Delegate* delegate) {
492 auto req = context.CreateRequest(url, DEFAULT_PRIORITY, delegate,
493 TRAFFIC_ANNOTATION_FOR_TESTS);
494 req->set_initiator(url::Origin::Create(url));
495 req->set_site_for_cookies(SiteForCookies::FromUrl(url));
496 return req;
497 }
498
499 std::unique_ptr<URLRequestContext> context_;
500 TestDelegate delegate_;
501 RecordingNetLogObserver net_log_observer_;
502 std::unique_ptr<URLRequest> req_;
503 };
504
505 class URLRequestHttpJobWithMockSocketsTest : public TestWithTaskEnvironment {
506 protected:
URLRequestHttpJobWithMockSocketsTest()507 URLRequestHttpJobWithMockSocketsTest() {
508 auto context_builder = CreateTestURLRequestContextBuilder();
509 context_builder->set_client_socket_factory_for_testing(&socket_factory_);
510 context_ = context_builder->Build();
511 }
512
513 MockClientSocketFactory socket_factory_;
514 std::unique_ptr<URLRequestContext> context_;
515 };
516
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestContentLengthSuccessfulRequest)517 TEST_F(URLRequestHttpJobWithMockSocketsTest,
518 TestContentLengthSuccessfulRequest) {
519 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
520 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
521 "Content-Length: 12\r\n\r\n"),
522 MockRead("Test Content")};
523
524 StaticSocketDataProvider socket_data(reads, writes);
525 socket_factory_.AddSocketDataProvider(&socket_data);
526
527 TestDelegate delegate;
528 std::unique_ptr<URLRequest> request =
529 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
530 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
531
532 request->Start();
533 ASSERT_TRUE(request->is_pending());
534 delegate.RunUntilComplete();
535
536 EXPECT_THAT(delegate.request_status(), IsOk());
537 EXPECT_EQ(12, request->received_response_content_length());
538 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
539 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
540 }
541
542 // Tests a successful HEAD request.
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestSuccessfulHead)543 TEST_F(URLRequestHttpJobWithMockSocketsTest, TestSuccessfulHead) {
544 MockWrite writes[] = {MockWrite(kSimpleHeadMockWrite)};
545 MockRead reads[] = {
546 MockRead("HTTP/1.1 200 OK\r\n"
547 "Content-Length: 0\r\n\r\n")};
548
549 StaticSocketDataProvider socket_data(reads, writes);
550 socket_factory_.AddSocketDataProvider(&socket_data);
551
552 TestDelegate delegate;
553 std::unique_ptr<URLRequest> request =
554 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
555 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
556
557 request->set_method("HEAD");
558 request->Start();
559 ASSERT_TRUE(request->is_pending());
560 delegate.RunUntilComplete();
561
562 EXPECT_THAT(delegate.request_status(), IsOk());
563 EXPECT_EQ(0, request->received_response_content_length());
564 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
565 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
566 }
567
568 // Similar to above test but tests that even if response body is there in the
569 // HEAD response stream, it should not be read due to HttpStreamParser's logic.
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestSuccessfulHeadWithContent)570 TEST_F(URLRequestHttpJobWithMockSocketsTest, TestSuccessfulHeadWithContent) {
571 MockWrite writes[] = {MockWrite(kSimpleHeadMockWrite)};
572 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
573 "Content-Length: 12\r\n\r\n"),
574 MockRead("Test Content")};
575
576 StaticSocketDataProvider socket_data(reads, writes);
577 socket_factory_.AddSocketDataProvider(&socket_data);
578
579 TestDelegate delegate;
580 std::unique_ptr<URLRequest> request =
581 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
582 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
583
584 request->set_method("HEAD");
585 request->Start();
586 ASSERT_TRUE(request->is_pending());
587 delegate.RunUntilComplete();
588
589 EXPECT_THAT(delegate.request_status(), IsOk());
590 EXPECT_EQ(0, request->received_response_content_length());
591 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
592 EXPECT_EQ(CountReadBytes(reads) - 12, request->GetTotalReceivedBytes());
593 }
594
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestSuccessfulCachedHeadRequest)595 TEST_F(URLRequestHttpJobWithMockSocketsTest, TestSuccessfulCachedHeadRequest) {
596 const url::Origin kOrigin1 =
597 url::Origin::Create(GURL("http://www.example.com"));
598 const IsolationInfo kTestIsolationInfo =
599 IsolationInfo::CreateForInternalRequest(kOrigin1);
600
601 // Cache the response.
602 {
603 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
604 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
605 "Content-Length: 12\r\n\r\n"),
606 MockRead("Test Content")};
607
608 StaticSocketDataProvider socket_data(reads, writes);
609 socket_factory_.AddSocketDataProvider(&socket_data);
610
611 TestDelegate delegate;
612 std::unique_ptr<URLRequest> request = context_->CreateRequest(
613 GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
614 TRAFFIC_ANNOTATION_FOR_TESTS);
615
616 request->set_isolation_info(kTestIsolationInfo);
617 request->Start();
618 ASSERT_TRUE(request->is_pending());
619 delegate.RunUntilComplete();
620
621 EXPECT_THAT(delegate.request_status(), IsOk());
622 EXPECT_EQ(12, request->received_response_content_length());
623 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
624 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
625 }
626
627 // Send a HEAD request for the cached response.
628 {
629 MockWrite writes[] = {MockWrite(kSimpleHeadMockWrite)};
630 MockRead reads[] = {
631 MockRead("HTTP/1.1 200 OK\r\n"
632 "Content-Length: 0\r\n\r\n")};
633
634 StaticSocketDataProvider socket_data(reads, writes);
635 socket_factory_.AddSocketDataProvider(&socket_data);
636
637 TestDelegate delegate;
638 std::unique_ptr<URLRequest> request = context_->CreateRequest(
639 GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
640 TRAFFIC_ANNOTATION_FOR_TESTS);
641
642 // Use the cached version.
643 request->SetLoadFlags(LOAD_SKIP_CACHE_VALIDATION);
644 request->set_method("HEAD");
645 request->set_isolation_info(kTestIsolationInfo);
646 request->Start();
647 ASSERT_TRUE(request->is_pending());
648 delegate.RunUntilComplete();
649
650 EXPECT_THAT(delegate.request_status(), IsOk());
651 EXPECT_EQ(0, request->received_response_content_length());
652 EXPECT_EQ(0, request->GetTotalSentBytes());
653 EXPECT_EQ(0, request->GetTotalReceivedBytes());
654 }
655 }
656
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestContentLengthSuccessfulHttp09Request)657 TEST_F(URLRequestHttpJobWithMockSocketsTest,
658 TestContentLengthSuccessfulHttp09Request) {
659 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
660 MockRead reads[] = {MockRead("Test Content"),
661 MockRead(net::SYNCHRONOUS, net::OK)};
662
663 StaticSocketDataProvider socket_data(reads, base::span<MockWrite>());
664 socket_factory_.AddSocketDataProvider(&socket_data);
665
666 TestDelegate delegate;
667 std::unique_ptr<URLRequest> request =
668 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
669 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
670
671 request->Start();
672 ASSERT_TRUE(request->is_pending());
673 delegate.RunUntilComplete();
674
675 EXPECT_THAT(delegate.request_status(), IsOk());
676 EXPECT_EQ(12, request->received_response_content_length());
677 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
678 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
679 }
680
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestContentLengthFailedRequest)681 TEST_F(URLRequestHttpJobWithMockSocketsTest, TestContentLengthFailedRequest) {
682 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
683 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
684 "Content-Length: 20\r\n\r\n"),
685 MockRead("Test Content"),
686 MockRead(net::SYNCHRONOUS, net::ERR_FAILED)};
687
688 StaticSocketDataProvider socket_data(reads, writes);
689 socket_factory_.AddSocketDataProvider(&socket_data);
690
691 TestDelegate delegate;
692 std::unique_ptr<URLRequest> request =
693 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
694 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
695
696 request->Start();
697 ASSERT_TRUE(request->is_pending());
698 delegate.RunUntilComplete();
699
700 EXPECT_THAT(delegate.request_status(), IsError(ERR_FAILED));
701 EXPECT_EQ(12, request->received_response_content_length());
702 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
703 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
704 }
705
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestContentLengthCancelledRequest)706 TEST_F(URLRequestHttpJobWithMockSocketsTest,
707 TestContentLengthCancelledRequest) {
708 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
709 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
710 "Content-Length: 20\r\n\r\n"),
711 MockRead("Test Content"),
712 MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)};
713
714 StaticSocketDataProvider socket_data(reads, writes);
715 socket_factory_.AddSocketDataProvider(&socket_data);
716
717 TestDelegate delegate;
718 std::unique_ptr<URLRequest> request =
719 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
720 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
721
722 delegate.set_cancel_in_received_data(true);
723 request->Start();
724 delegate.RunUntilComplete();
725
726 EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
727 EXPECT_EQ(12, request->received_response_content_length());
728 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
729 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
730 }
731
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestNetworkBytesRedirectedRequest)732 TEST_F(URLRequestHttpJobWithMockSocketsTest,
733 TestNetworkBytesRedirectedRequest) {
734 MockWrite redirect_writes[] = {
735 MockWrite("GET / HTTP/1.1\r\n"
736 "Host: www.redirect.com\r\n"
737 "Connection: keep-alive\r\n"
738 "User-Agent: \r\n"
739 "Accept-Encoding: gzip, deflate\r\n"
740 "Accept-Language: en-us,fr\r\n\r\n")};
741
742 MockRead redirect_reads[] = {
743 MockRead("HTTP/1.1 302 Found\r\n"
744 "Location: http://www.example.com\r\n\r\n"),
745 };
746 StaticSocketDataProvider redirect_socket_data(redirect_reads,
747 redirect_writes);
748 socket_factory_.AddSocketDataProvider(&redirect_socket_data);
749
750 MockWrite final_writes[] = {MockWrite(kSimpleGetMockWrite)};
751 MockRead final_reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
752 "Content-Length: 12\r\n\r\n"),
753 MockRead("Test Content")};
754 StaticSocketDataProvider final_socket_data(final_reads, final_writes);
755 socket_factory_.AddSocketDataProvider(&final_socket_data);
756
757 TestDelegate delegate;
758 std::unique_ptr<URLRequest> request =
759 context_->CreateRequest(GURL("http://www.redirect.com"), DEFAULT_PRIORITY,
760 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
761
762 request->Start();
763 ASSERT_TRUE(request->is_pending());
764 delegate.RunUntilComplete();
765
766 EXPECT_THAT(delegate.request_status(), IsOk());
767 EXPECT_EQ(12, request->received_response_content_length());
768 // Should not include the redirect.
769 EXPECT_EQ(CountWriteBytes(final_writes), request->GetTotalSentBytes());
770 EXPECT_EQ(CountReadBytes(final_reads), request->GetTotalReceivedBytes());
771 }
772
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestNetworkBytesCancelledAfterHeaders)773 TEST_F(URLRequestHttpJobWithMockSocketsTest,
774 TestNetworkBytesCancelledAfterHeaders) {
775 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
776 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n\r\n")};
777 StaticSocketDataProvider socket_data(reads, writes);
778 socket_factory_.AddSocketDataProvider(&socket_data);
779
780 TestDelegate delegate;
781 std::unique_ptr<URLRequest> request =
782 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
783 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
784
785 delegate.set_cancel_in_response_started(true);
786 request->Start();
787 delegate.RunUntilComplete();
788
789 EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
790 EXPECT_EQ(0, request->received_response_content_length());
791 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
792 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
793 }
794
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestNetworkBytesCancelledImmediately)795 TEST_F(URLRequestHttpJobWithMockSocketsTest,
796 TestNetworkBytesCancelledImmediately) {
797 StaticSocketDataProvider socket_data;
798 socket_factory_.AddSocketDataProvider(&socket_data);
799
800 TestDelegate delegate;
801 std::unique_ptr<URLRequest> request =
802 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
803 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
804
805 request->Start();
806 request->Cancel();
807 delegate.RunUntilComplete();
808
809 EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
810 EXPECT_EQ(0, request->received_response_content_length());
811 EXPECT_EQ(0, request->GetTotalSentBytes());
812 EXPECT_EQ(0, request->GetTotalReceivedBytes());
813 }
814
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestHttpTimeToFirstByte)815 TEST_F(URLRequestHttpJobWithMockSocketsTest, TestHttpTimeToFirstByte) {
816 base::HistogramTester histograms;
817 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
818 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
819 "Content-Length: 12\r\n\r\n"),
820 MockRead("Test Content")};
821
822 StaticSocketDataProvider socket_data(reads, writes);
823 socket_factory_.AddSocketDataProvider(&socket_data);
824
825 TestDelegate delegate;
826 std::unique_ptr<URLRequest> request =
827 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
828 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
829 histograms.ExpectTotalCount("Net.HttpTimeToFirstByte", 0);
830
831 request->Start();
832 delegate.RunUntilComplete();
833
834 EXPECT_THAT(delegate.request_status(), IsOk());
835 histograms.ExpectTotalCount("Net.HttpTimeToFirstByte", 1);
836 }
837
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestHttpTimeToFirstByteForCancelledTask)838 TEST_F(URLRequestHttpJobWithMockSocketsTest,
839 TestHttpTimeToFirstByteForCancelledTask) {
840 base::HistogramTester histograms;
841 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
842 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
843 "Content-Length: 12\r\n\r\n"),
844 MockRead("Test Content")};
845
846 StaticSocketDataProvider socket_data(reads, writes);
847 socket_factory_.AddSocketDataProvider(&socket_data);
848
849 TestDelegate delegate;
850 std::unique_ptr<URLRequest> request =
851 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
852 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
853
854 request->Start();
855 request->Cancel();
856 delegate.RunUntilComplete();
857
858 EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
859 histograms.ExpectTotalCount("Net.HttpTimeToFirstByte", 0);
860 }
861
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestHttpJobSuccessPriorityKeyedTotalTime)862 TEST_F(URLRequestHttpJobWithMockSocketsTest,
863 TestHttpJobSuccessPriorityKeyedTotalTime) {
864 base::HistogramTester histograms;
865
866 for (int priority = 0; priority < net::NUM_PRIORITIES; ++priority) {
867 for (int request_index = 0; request_index <= priority; ++request_index) {
868 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
869 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
870 "Content-Length: 12\r\n\r\n"),
871 MockRead("Test Content")};
872
873 StaticSocketDataProvider socket_data(reads, writes);
874 socket_factory_.AddSocketDataProvider(&socket_data);
875
876 TestDelegate delegate;
877 std::unique_ptr<URLRequest> request =
878 context_->CreateRequest(GURL("http://www.example.com/"),
879 static_cast<net::RequestPriority>(priority),
880 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
881
882 request->Start();
883 delegate.RunUntilComplete();
884 EXPECT_THAT(delegate.request_status(), IsOk());
885 }
886 }
887
888 for (int priority = 0; priority < net::NUM_PRIORITIES; ++priority) {
889 histograms.ExpectTotalCount("Net.HttpJob.TotalTimeSuccess.Priority" +
890 base::NumberToString(priority),
891 priority + 1);
892 }
893 }
894
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestHttpJobRecordsTrustAnchorHistograms)895 TEST_F(URLRequestHttpJobWithMockSocketsTest,
896 TestHttpJobRecordsTrustAnchorHistograms) {
897 SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
898 ssl_socket_data.ssl_info.cert =
899 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
900 // Simulate a certificate chain issued by "C=US, O=Google Trust Services LLC,
901 // CN=GTS Root R4". This publicly-trusted root was chosen as it was included
902 // in 2017 and is not anticipated to be removed from all supported platforms
903 // for a few decades.
904 // Note: The actual cert in |cert| does not matter for this testing.
905 SHA256HashValue leaf_hash = {{0}};
906 SHA256HashValue intermediate_hash = {{1}};
907 SHA256HashValue root_hash = {
908 {0x98, 0x47, 0xe5, 0x65, 0x3e, 0x5e, 0x9e, 0x84, 0x75, 0x16, 0xe5,
909 0xcb, 0x81, 0x86, 0x06, 0xaa, 0x75, 0x44, 0xa1, 0x9b, 0xe6, 0x7f,
910 0xd7, 0x36, 0x6d, 0x50, 0x69, 0x88, 0xe8, 0xd8, 0x43, 0x47}};
911 ssl_socket_data.ssl_info.public_key_hashes.push_back(HashValue(leaf_hash));
912 ssl_socket_data.ssl_info.public_key_hashes.push_back(
913 HashValue(intermediate_hash));
914 ssl_socket_data.ssl_info.public_key_hashes.push_back(HashValue(root_hash));
915
916 const base::HistogramBase::Sample kGTSRootR4HistogramID = 486;
917
918 socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
919
920 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
921 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
922 "Content-Length: 12\r\n\r\n"),
923 MockRead("Test Content")};
924 StaticSocketDataProvider socket_data(reads, writes);
925 socket_factory_.AddSocketDataProvider(&socket_data);
926
927 base::HistogramTester histograms;
928 histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 0);
929
930 TestDelegate delegate;
931 std::unique_ptr<URLRequest> request = context_->CreateRequest(
932 GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
933 TRAFFIC_ANNOTATION_FOR_TESTS);
934 request->Start();
935 delegate.RunUntilComplete();
936 EXPECT_THAT(delegate.request_status(), IsOk());
937
938 histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 1);
939 histograms.ExpectUniqueSample(kTrustAnchorRequestHistogram,
940 kGTSRootR4HistogramID, 1);
941 }
942
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestHttpJobDoesNotRecordTrustAnchorHistogramsWhenNoNetworkLoad)943 TEST_F(URLRequestHttpJobWithMockSocketsTest,
944 TestHttpJobDoesNotRecordTrustAnchorHistogramsWhenNoNetworkLoad) {
945 SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
946 ssl_socket_data.ssl_info.cert =
947 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
948 // Simulate a request loaded from a non-network source, such as a disk
949 // cache.
950 ssl_socket_data.ssl_info.public_key_hashes.clear();
951
952 socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
953
954 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
955 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
956 "Content-Length: 12\r\n\r\n"),
957 MockRead("Test Content")};
958 StaticSocketDataProvider socket_data(reads, writes);
959 socket_factory_.AddSocketDataProvider(&socket_data);
960
961 base::HistogramTester histograms;
962 histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 0);
963
964 TestDelegate delegate;
965 std::unique_ptr<URLRequest> request = context_->CreateRequest(
966 GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
967 TRAFFIC_ANNOTATION_FOR_TESTS);
968 request->Start();
969 delegate.RunUntilComplete();
970 EXPECT_THAT(delegate.request_status(), IsOk());
971
972 histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 0);
973 }
974
TEST_F(URLRequestHttpJobWithMockSocketsTest,TestHttpJobRecordsMostSpecificTrustAnchorHistograms)975 TEST_F(URLRequestHttpJobWithMockSocketsTest,
976 TestHttpJobRecordsMostSpecificTrustAnchorHistograms) {
977 SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
978 ssl_socket_data.ssl_info.cert =
979 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
980 // Simulate a certificate chain issued by "C=US, O=Google Trust Services LLC,
981 // CN=GTS Root R4". This publicly-trusted root was chosen as it was included
982 // in 2017 and is not anticipated to be removed from all supported platforms
983 // for a few decades.
984 // Note: The actual cert in |cert| does not matter for this testing.
985 SHA256HashValue leaf_hash = {{0}};
986 SHA256HashValue intermediate_hash = {{1}};
987 SHA256HashValue gts_root_r3_hash = {
988 {0x41, 0x79, 0xed, 0xd9, 0x81, 0xef, 0x74, 0x74, 0x77, 0xb4, 0x96,
989 0x26, 0x40, 0x8a, 0xf4, 0x3d, 0xaa, 0x2c, 0xa7, 0xab, 0x7f, 0x9e,
990 0x08, 0x2c, 0x10, 0x60, 0xf8, 0x40, 0x96, 0x77, 0x43, 0x48}};
991 SHA256HashValue gts_root_r4_hash = {
992 {0x98, 0x47, 0xe5, 0x65, 0x3e, 0x5e, 0x9e, 0x84, 0x75, 0x16, 0xe5,
993 0xcb, 0x81, 0x86, 0x06, 0xaa, 0x75, 0x44, 0xa1, 0x9b, 0xe6, 0x7f,
994 0xd7, 0x36, 0x6d, 0x50, 0x69, 0x88, 0xe8, 0xd8, 0x43, 0x47}};
995 ssl_socket_data.ssl_info.public_key_hashes.push_back(HashValue(leaf_hash));
996 ssl_socket_data.ssl_info.public_key_hashes.push_back(
997 HashValue(intermediate_hash));
998 ssl_socket_data.ssl_info.public_key_hashes.push_back(
999 HashValue(gts_root_r3_hash));
1000 ssl_socket_data.ssl_info.public_key_hashes.push_back(
1001 HashValue(gts_root_r4_hash));
1002
1003 const base::HistogramBase::Sample kGTSRootR3HistogramID = 485;
1004
1005 socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
1006
1007 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
1008 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1009 "Content-Length: 12\r\n\r\n"),
1010 MockRead("Test Content")};
1011 StaticSocketDataProvider socket_data(reads, writes);
1012 socket_factory_.AddSocketDataProvider(&socket_data);
1013
1014 base::HistogramTester histograms;
1015 histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 0);
1016
1017 TestDelegate delegate;
1018 std::unique_ptr<URLRequest> request = context_->CreateRequest(
1019 GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
1020 TRAFFIC_ANNOTATION_FOR_TESTS);
1021 request->Start();
1022 delegate.RunUntilComplete();
1023 EXPECT_THAT(delegate.request_status(), IsOk());
1024
1025 histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 1);
1026 histograms.ExpectUniqueSample(kTrustAnchorRequestHistogram,
1027 kGTSRootR3HistogramID, 1);
1028 }
1029
TEST_F(URLRequestHttpJobWithMockSocketsTest,EncodingAdvertisementOnRange)1030 TEST_F(URLRequestHttpJobWithMockSocketsTest, EncodingAdvertisementOnRange) {
1031 MockWrite writes[] = {
1032 MockWrite("GET / HTTP/1.1\r\n"
1033 "Host: www.example.com\r\n"
1034 "Connection: keep-alive\r\n"
1035 "User-Agent: \r\n"
1036 "Accept-Encoding: identity\r\n"
1037 "Accept-Language: en-us,fr\r\n"
1038 "Range: bytes=0-1023\r\n\r\n")};
1039
1040 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1041 "Accept-Ranges: bytes\r\n"
1042 "Content-Length: 12\r\n\r\n"),
1043 MockRead("Test Content")};
1044
1045 StaticSocketDataProvider socket_data(reads, writes);
1046 socket_factory_.AddSocketDataProvider(&socket_data);
1047
1048 TestDelegate delegate;
1049 std::unique_ptr<URLRequest> request =
1050 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
1051 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
1052
1053 // Make the extra header to trigger the change in "Accepted-Encoding"
1054 HttpRequestHeaders headers;
1055 headers.SetHeader("Range", "bytes=0-1023");
1056 request->SetExtraRequestHeaders(headers);
1057
1058 request->Start();
1059 delegate.RunUntilComplete();
1060
1061 EXPECT_THAT(delegate.request_status(), IsOk());
1062 EXPECT_EQ(12, request->received_response_content_length());
1063 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
1064 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
1065 }
1066
TEST_F(URLRequestHttpJobWithMockSocketsTest,RangeRequestOverrideEncoding)1067 TEST_F(URLRequestHttpJobWithMockSocketsTest, RangeRequestOverrideEncoding) {
1068 MockWrite writes[] = {
1069 MockWrite("GET / HTTP/1.1\r\n"
1070 "Host: www.example.com\r\n"
1071 "Connection: keep-alive\r\n"
1072 "Accept-Encoding: gzip, deflate\r\n"
1073 "User-Agent: \r\n"
1074 "Accept-Language: en-us,fr\r\n"
1075 "Range: bytes=0-1023\r\n\r\n")};
1076
1077 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1078 "Accept-Ranges: bytes\r\n"
1079 "Content-Length: 12\r\n\r\n"),
1080 MockRead("Test Content")};
1081
1082 StaticSocketDataProvider socket_data(reads, writes);
1083 socket_factory_.AddSocketDataProvider(&socket_data);
1084
1085 TestDelegate delegate;
1086 std::unique_ptr<URLRequest> request =
1087 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
1088 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
1089
1090 // Explicitly set "Accept-Encoding" to make sure it's not overridden by
1091 // AddExtraHeaders
1092 HttpRequestHeaders headers;
1093 headers.SetHeader("Accept-Encoding", "gzip, deflate");
1094 headers.SetHeader("Range", "bytes=0-1023");
1095 request->SetExtraRequestHeaders(headers);
1096
1097 request->Start();
1098 delegate.RunUntilComplete();
1099
1100 EXPECT_THAT(delegate.request_status(), IsOk());
1101 EXPECT_EQ(12, request->received_response_content_length());
1102 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
1103 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
1104 }
1105
TEST_F(URLRequestHttpJobTest,TestCancelWhileReadingCookies)1106 TEST_F(URLRequestHttpJobTest, TestCancelWhileReadingCookies) {
1107 auto context_builder = CreateTestURLRequestContextBuilder();
1108 context_builder->SetCookieStore(std::make_unique<DelayedCookieMonster>());
1109 auto context = context_builder->Build();
1110
1111 TestDelegate delegate;
1112 std::unique_ptr<URLRequest> request =
1113 context->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
1114 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
1115
1116 request->Start();
1117 request->Cancel();
1118 delegate.RunUntilComplete();
1119
1120 EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
1121 }
1122
1123 // Make sure that SetPriority actually sets the URLRequestHttpJob's
1124 // priority, before start. Other tests handle the after start case.
TEST_F(URLRequestHttpJobTest,SetPriorityBasic)1125 TEST_F(URLRequestHttpJobTest, SetPriorityBasic) {
1126 auto job = std::make_unique<TestURLRequestHttpJob>(req_.get());
1127 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1128
1129 job->SetPriority(LOWEST);
1130 EXPECT_EQ(LOWEST, job->priority());
1131
1132 job->SetPriority(LOW);
1133 EXPECT_EQ(LOW, job->priority());
1134 }
1135
1136 // Make sure that URLRequestHttpJob passes on its priority to its
1137 // transaction on start.
TEST_F(URLRequestHttpJobTest,SetTransactionPriorityOnStart)1138 TEST_F(URLRequestHttpJobTest, SetTransactionPriorityOnStart) {
1139 TestScopedURLInterceptor interceptor(
1140 req_->url(), std::make_unique<TestURLRequestHttpJob>(req_.get()));
1141 req_->SetPriority(LOW);
1142
1143 EXPECT_FALSE(network_layer().last_transaction());
1144
1145 req_->Start();
1146
1147 ASSERT_TRUE(network_layer().last_transaction());
1148 EXPECT_EQ(LOW, network_layer().last_transaction()->priority());
1149 }
1150
1151 // Make sure that URLRequestHttpJob passes on its priority updates to
1152 // its transaction.
TEST_F(URLRequestHttpJobTest,SetTransactionPriority)1153 TEST_F(URLRequestHttpJobTest, SetTransactionPriority) {
1154 TestScopedURLInterceptor interceptor(
1155 req_->url(), std::make_unique<TestURLRequestHttpJob>(req_.get()));
1156 req_->SetPriority(LOW);
1157 req_->Start();
1158 ASSERT_TRUE(network_layer().last_transaction());
1159 EXPECT_EQ(LOW, network_layer().last_transaction()->priority());
1160
1161 req_->SetPriority(HIGHEST);
1162 EXPECT_EQ(HIGHEST, network_layer().last_transaction()->priority());
1163 }
1164
TEST_F(URLRequestHttpJobTest,HSTSInternalRedirectTest)1165 TEST_F(URLRequestHttpJobTest, HSTSInternalRedirectTest) {
1166 // Setup HSTS state.
1167 context_->transport_security_state()->AddHSTS(
1168 "upgrade.test", base::Time::Now() + base::Seconds(10), true);
1169 ASSERT_TRUE(
1170 context_->transport_security_state()->ShouldUpgradeToSSL("upgrade.test"));
1171 ASSERT_FALSE(context_->transport_security_state()->ShouldUpgradeToSSL(
1172 "no-upgrade.test"));
1173
1174 struct TestCase {
1175 const char* url;
1176 bool upgrade_expected;
1177 const char* url_expected;
1178 } cases[] = {
1179 {"http://upgrade.test/", true, "https://upgrade.test/"},
1180 {"http://upgrade.test:123/", true, "https://upgrade.test:123/"},
1181 {"http://no-upgrade.test/", false, "http://no-upgrade.test/"},
1182 {"http://no-upgrade.test:123/", false, "http://no-upgrade.test:123/"},
1183 #if BUILDFLAG(ENABLE_WEBSOCKETS)
1184 {"ws://upgrade.test/", true, "wss://upgrade.test/"},
1185 {"ws://upgrade.test:123/", true, "wss://upgrade.test:123/"},
1186 {"ws://no-upgrade.test/", false, "ws://no-upgrade.test/"},
1187 {"ws://no-upgrade.test:123/", false, "ws://no-upgrade.test:123/"},
1188 #endif // BUILDFLAG(ENABLE_WEBSOCKETS)
1189 };
1190
1191 for (const auto& test : cases) {
1192 SCOPED_TRACE(test.url);
1193
1194 GURL url = GURL(test.url);
1195 // This is needed to bypass logic that rejects using URLRequests directly
1196 // for WebSocket requests.
1197 bool is_for_websockets = url.SchemeIsWSOrWSS();
1198
1199 TestDelegate d;
1200 TestNetworkDelegate network_delegate;
1201 std::unique_ptr<URLRequest> r(context_->CreateRequest(
1202 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS,
1203 is_for_websockets));
1204
1205 net_log_observer_.Clear();
1206 r->Start();
1207 d.RunUntilComplete();
1208
1209 if (test.upgrade_expected) {
1210 auto entries = net_log_observer_.GetEntriesWithType(
1211 net::NetLogEventType::URL_REQUEST_REDIRECT_JOB);
1212 int redirects = entries.size();
1213 for (const auto& entry : entries) {
1214 EXPECT_EQ("HSTS", GetStringValueFromParams(entry, "reason"));
1215 }
1216 EXPECT_EQ(1, redirects);
1217 EXPECT_EQ(1, d.received_redirect_count());
1218 EXPECT_EQ(2u, r->url_chain().size());
1219 } else {
1220 EXPECT_EQ(0, d.received_redirect_count());
1221 EXPECT_EQ(1u, r->url_chain().size());
1222 }
1223 EXPECT_EQ(GURL(test.url_expected), r->url());
1224 }
1225 }
1226
TEST_F(URLRequestHttpJobTest,ShouldBypassHSTS)1227 TEST_F(URLRequestHttpJobTest, ShouldBypassHSTS) {
1228 // Setup HSTS state.
1229 context_->transport_security_state()->AddHSTS(
1230 "upgrade.test", base::Time::Now() + base::Seconds(30), true);
1231 ASSERT_TRUE(
1232 context_->transport_security_state()->ShouldUpgradeToSSL("upgrade.test"));
1233
1234 struct TestCase {
1235 const char* url;
1236 bool bypass_hsts;
1237 const char* url_expected;
1238 } cases[] = {
1239 {"http://upgrade.test/example.crl", true,
1240 "http://upgrade.test/example.crl"},
1241 // This test ensures that the HSTS check and upgrade happens prior to cache
1242 // and socket pool checks
1243 {"http://upgrade.test/example.crl", false,
1244 "https://upgrade.test/example.crl"},
1245 {"http://upgrade.test", false, "https://upgrade.test"},
1246 {"http://upgrade.test:1080", false, "https://upgrade.test:1080"},
1247 #if BUILDFLAG(ENABLE_WEBSOCKETS)
1248 {"ws://upgrade.test/example.crl", true, "ws://upgrade.test/example.crl"},
1249 {"ws://upgrade.test/example.crl", false, "wss://upgrade.test/example.crl"},
1250 {"ws://upgrade.test", false, "wss://upgrade.test"},
1251 {"ws://upgrade.test:1080", false, "wss://upgrade.test:1080"},
1252 #endif // BUILDFLAG(ENABLE_WEBSOCKETS)
1253 };
1254
1255 for (const auto& test : cases) {
1256 SCOPED_TRACE(test.url);
1257
1258 GURL url = GURL(test.url);
1259 // This is needed to bypass logic that rejects using URLRequests directly
1260 // for WebSocket requests.
1261 bool is_for_websockets = url.SchemeIsWSOrWSS();
1262
1263 TestDelegate d;
1264 TestNetworkDelegate network_delegate;
1265 std::unique_ptr<URLRequest> r(context_->CreateRequest(
1266 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS,
1267 is_for_websockets));
1268 if (test.bypass_hsts) {
1269 r->SetLoadFlags(net::LOAD_SHOULD_BYPASS_HSTS);
1270 r->set_allow_credentials(false);
1271 }
1272
1273 net_log_observer_.Clear();
1274 r->Start();
1275 d.RunUntilComplete();
1276
1277 if (test.bypass_hsts) {
1278 EXPECT_EQ(0, d.received_redirect_count());
1279 EXPECT_EQ(1u, r->url_chain().size());
1280 } else {
1281 auto entries = net_log_observer_.GetEntriesWithType(
1282 net::NetLogEventType::URL_REQUEST_REDIRECT_JOB);
1283 int redirects = entries.size();
1284 for (const auto& entry : entries) {
1285 EXPECT_EQ("HSTS", GetStringValueFromParams(entry, "reason"));
1286 }
1287 EXPECT_EQ(1, redirects);
1288 EXPECT_EQ(1, d.received_redirect_count());
1289 EXPECT_EQ(2u, r->url_chain().size());
1290 }
1291 EXPECT_EQ(GURL(test.url_expected), r->url());
1292 }
1293 }
1294
1295 #if BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS)
1296
1297 class URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest
1298 : public TestWithTaskEnvironment {
1299 protected:
URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest()1300 URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest() {
1301 auto context_builder = CreateTestURLRequestContextBuilder();
1302 context_builder->set_client_socket_factory_for_testing(&socket_factory_);
1303 context_builder->set_device_bound_session_service(
1304 std::make_unique<
1305 testing::StrictMock<device_bound_sessions::SessionServiceMock>>());
1306 context_ = context_builder->Build();
1307 request_ = context_->CreateRequest(GURL("http://www.example.com"),
1308 DEFAULT_PRIORITY, &delegate_,
1309 TRAFFIC_ANNOTATION_FOR_TESTS);
1310 }
1311
GetMockService()1312 device_bound_sessions::SessionServiceMock& GetMockService() {
1313 return *static_cast<device_bound_sessions::SessionServiceMock*>(
1314 context_->device_bound_session_service());
1315 }
1316
1317 MockClientSocketFactory socket_factory_;
1318 std::unique_ptr<URLRequestContext> context_;
1319 TestDelegate delegate_;
1320 std::unique_ptr<URLRequest> request_;
1321 };
1322
TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,ShouldRespondToDeviceBoundSessionHeader)1323 TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,
1324 ShouldRespondToDeviceBoundSessionHeader) {
1325 const MockWrite writes[] = {
1326 MockWrite("GET / HTTP/1.1\r\n"
1327 "Host: www.example.com\r\n"
1328 "Connection: keep-alive\r\n"
1329 "User-Agent: \r\n"
1330 "Accept-Encoding: gzip, deflate\r\n"
1331 "Accept-Language: en-us,fr\r\n\r\n")};
1332
1333 const MockRead reads[] = {
1334 MockRead("HTTP/1.1 200 OK\r\n"
1335 "Accept-Ranges: bytes\r\n"
1336 "Sec-Session-Registration: (ES256);path=\"new\";"
1337 "challenge=\"test\"\r\n"
1338 "Content-Length: 12\r\n\r\n"),
1339 MockRead("Test Content")};
1340
1341 StaticSocketDataProvider socket_data(reads, writes);
1342 socket_factory_.AddSocketDataProvider(&socket_data);
1343
1344 EXPECT_CALL(GetMockService(), GetAnySessionRequiringDeferral)
1345 .WillOnce(Return(std::nullopt));
1346 request_->Start();
1347 EXPECT_CALL(GetMockService(), RegisterBoundSession).Times(1);
1348 delegate_.RunUntilComplete();
1349 EXPECT_THAT(delegate_.request_status(), IsOk());
1350 }
1351
TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,DeferRequestIfNeeded)1352 TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,
1353 DeferRequestIfNeeded) {
1354 const MockWrite writes[] = {
1355 MockWrite("GET / HTTP/1.1\r\n"
1356 "Host: www.example.com\r\n"
1357 "Connection: keep-alive\r\n"
1358 "User-Agent: \r\n"
1359 "Accept-Encoding: gzip, deflate\r\n"
1360 "Accept-Language: en-us,fr\r\n\r\n")};
1361
1362 const MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1363 "Accept-Ranges: bytes\r\n"
1364 "Content-Length: 12\r\n\r\n"),
1365 MockRead("Test Content")};
1366
1367 StaticSocketDataProvider socket_data(reads, writes);
1368 socket_factory_.AddSocketDataProvider(&socket_data);
1369
1370 {
1371 InSequence s;
1372 EXPECT_CALL(GetMockService(), GetAnySessionRequiringDeferral)
1373 .WillOnce(Invoke([](Unused) {
1374 std::optional<device_bound_sessions::Session::Id> tag("test");
1375 return tag;
1376 }));
1377 EXPECT_CALL(GetMockService(), DeferRequestForRefresh)
1378 .WillOnce(base::test::RunOnceClosure<3>());
1379 }
1380
1381 request_->Start();
1382 delegate_.RunUntilComplete();
1383 EXPECT_THAT(delegate_.request_status(), IsOk());
1384 }
1385
TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,DontDeferRequestIfNotNeeded)1386 TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,
1387 DontDeferRequestIfNotNeeded) {
1388 const MockWrite writes[] = {
1389 MockWrite("GET / HTTP/1.1\r\n"
1390 "Host: www.example.com\r\n"
1391 "Connection: keep-alive\r\n"
1392 "User-Agent: \r\n"
1393 "Accept-Encoding: gzip, deflate\r\n"
1394 "Accept-Language: en-us,fr\r\n\r\n")};
1395
1396 const MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1397 "Accept-Ranges: bytes\r\n"
1398 "Content-Length: 12\r\n\r\n"),
1399 MockRead("Test Content")};
1400
1401 StaticSocketDataProvider socket_data(reads, writes);
1402 socket_factory_.AddSocketDataProvider(&socket_data);
1403
1404 EXPECT_CALL(GetMockService(), GetAnySessionRequiringDeferral)
1405 .WillOnce(Invoke([](Unused) { return std::nullopt; }));
1406 request_->Start();
1407 delegate_.RunUntilComplete();
1408 EXPECT_THAT(delegate_.request_status(), IsOk());
1409 }
1410
TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,ShouldNotRespondWithoutDeviceBoundSessionHeader)1411 TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,
1412 ShouldNotRespondWithoutDeviceBoundSessionHeader) {
1413 const MockWrite writes[] = {
1414 MockWrite("GET / HTTP/1.1\r\n"
1415 "Host: www.example.com\r\n"
1416 "Connection: keep-alive\r\n"
1417 "User-Agent: \r\n"
1418 "Accept-Encoding: gzip, deflate\r\n"
1419 "Accept-Language: en-us,fr\r\n\r\n")};
1420
1421 const MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1422 "Accept-Ranges: bytes\r\n"
1423 "Content-Length: 12\r\n\r\n"),
1424 MockRead("Test Content")};
1425
1426 StaticSocketDataProvider socket_data(reads, writes);
1427 socket_factory_.AddSocketDataProvider(&socket_data);
1428
1429 {
1430 InSequence s;
1431 EXPECT_CALL(GetMockService(), GetAnySessionRequiringDeferral)
1432 .WillOnce(Return(std::nullopt));
1433 EXPECT_CALL(GetMockService(), RegisterBoundSession).Times(0);
1434 }
1435 request_->Start();
1436 delegate_.RunUntilComplete();
1437 EXPECT_THAT(delegate_.request_status(), IsOk());
1438 }
1439
TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,ShouldProcessDeviceBoundSessionChallengeHeader)1440 TEST_F(URLRequestHttpJobWithMockSocketsDeviceBoundSessionServiceTest,
1441 ShouldProcessDeviceBoundSessionChallengeHeader) {
1442 const MockWrite writes[] = {
1443 MockWrite("GET / HTTP/1.1\r\n"
1444 "Host: www.example.com\r\n"
1445 "Connection: keep-alive\r\n"
1446 "User-Agent: \r\n"
1447 "Accept-Encoding: gzip, deflate\r\n"
1448 "Accept-Language: en-us,fr\r\n\r\n")};
1449
1450 const MockRead reads[] = {
1451 MockRead(
1452 "HTTP/1.1 200 OK\r\n"
1453 "Accept-Ranges: bytes\r\n"
1454 "Sec-Session-Challenge: \"session_identifier\";challenge=\"test\"\r\n"
1455 "Content-Length: 12\r\n\r\n"),
1456 MockRead("Test Content")};
1457
1458 StaticSocketDataProvider socket_data(reads, writes);
1459 socket_factory_.AddSocketDataProvider(&socket_data);
1460
1461 {
1462 InSequence s;
1463 EXPECT_CALL(GetMockService(), GetAnySessionRequiringDeferral)
1464 .WillOnce(Return(std::nullopt));
1465 EXPECT_CALL(GetMockService(), SetChallengeForBoundSession).Times(1);
1466 }
1467 request_->Start();
1468 delegate_.RunUntilComplete();
1469 EXPECT_THAT(delegate_.request_status(), IsOk());
1470 }
1471
1472 #endif // BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS)
1473
1474 namespace {
HandleRequest(const std::string_view & content,const test_server::HttpRequest & request)1475 std::unique_ptr<test_server::HttpResponse> HandleRequest(
1476 const std::string_view& content,
1477 const test_server::HttpRequest& request) {
1478 auto response = std::make_unique<test_server::BasicHttpResponse>();
1479 response->set_content(content);
1480 return std::move(response);
1481 }
1482 } // namespace
1483
1484 // This test checks that if an HTTP connection was made for a request that has
1485 // the should_bypass_hsts flag set to true, subsequent calls to the exact same
1486 // URL WITHOUT should_bypass_hsts=true will be upgraded to HTTPS early
1487 // enough in the process such that the HTTP socket connection is not re-used,
1488 // and the request does not have a hit in the cache.
TEST_F(URLRequestHttpJobTest,ShouldBypassHSTSResponseAndConnectionNotReused)1489 TEST_F(URLRequestHttpJobTest, ShouldBypassHSTSResponseAndConnectionNotReused) {
1490 constexpr std::string_view kSecureContent = "Secure: Okay Content";
1491 constexpr std::string_view kInsecureContent = "Insecure: Bad Content";
1492
1493 auto context_builder = CreateTestURLRequestContextBuilder();
1494 auto context = context_builder->Build();
1495
1496 // The host of all EmbeddedTestServer URLs is 127.0.0.1.
1497 context->transport_security_state()->AddHSTS(
1498 "127.0.0.1", base::Time::Now() + base::Seconds(30), true);
1499 ASSERT_TRUE(
1500 context->transport_security_state()->ShouldUpgradeToSSL("127.0.0.1"));
1501
1502 GURL::Replacements replace_scheme;
1503 replace_scheme.SetSchemeStr("https");
1504 GURL insecure_url;
1505 GURL secure_url;
1506
1507 int common_port = 0;
1508
1509 // Create an HTTP request that is not upgraded to the should_bypass_hsts flag,
1510 // and ensure that the response is stored in the cache.
1511 {
1512 EmbeddedTestServer http_server(EmbeddedTestServer::TYPE_HTTP);
1513 http_server.AddDefaultHandlers(base::FilePath());
1514 http_server.RegisterRequestHandler(
1515 base::BindRepeating(&HandleRequest, kInsecureContent));
1516 ASSERT_TRUE(http_server.Start());
1517 common_port = http_server.port();
1518
1519 insecure_url = http_server.base_url();
1520 ASSERT_TRUE(insecure_url.SchemeIs("http"));
1521 secure_url = insecure_url.ReplaceComponents(replace_scheme);
1522 ASSERT_TRUE(secure_url.SchemeIs("https"));
1523
1524 net_log_observer_.Clear();
1525 TestDelegate delegate;
1526 std::unique_ptr<URLRequest> req(
1527 context->CreateRequest(insecure_url, DEFAULT_PRIORITY, &delegate,
1528 TRAFFIC_ANNOTATION_FOR_TESTS));
1529 req->SetLoadFlags(net::LOAD_SHOULD_BYPASS_HSTS);
1530 req->set_allow_credentials(false);
1531 req->Start();
1532 delegate.RunUntilComplete();
1533 EXPECT_EQ(kInsecureContent, delegate.data_received());
1534 // There should be 2 cache event entries, one for beginning the read and one
1535 // for finishing the read.
1536 EXPECT_EQ(2u, net_log_observer_
1537 .GetEntriesWithType(
1538 net::NetLogEventType::HTTP_CACHE_ADD_TO_ENTRY)
1539 .size());
1540 ASSERT_TRUE(http_server.ShutdownAndWaitUntilComplete());
1541 }
1542 // Test that a request with the same URL will be upgraded as long as
1543 // should_bypass_hsts flag is not set, and doesn't have an cache hit or
1544 // re-use an existing socket connection.
1545 {
1546 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
1547 https_server.AddDefaultHandlers(base::FilePath());
1548 https_server.RegisterRequestHandler(
1549 base::BindRepeating(&HandleRequest, kSecureContent));
1550 ASSERT_TRUE(https_server.Start(common_port));
1551
1552 TestDelegate delegate;
1553 std::unique_ptr<URLRequest> req(
1554 context->CreateRequest(insecure_url, DEFAULT_PRIORITY, &delegate,
1555 TRAFFIC_ANNOTATION_FOR_TESTS));
1556 req->set_allow_credentials(false);
1557 req->Start();
1558 delegate.RunUntilRedirect();
1559 // Ensure that the new URL has an upgraded protocol. This ensures that when
1560 // the redirect request continues, the HTTP socket connection from before
1561 // will not be re-used, given that "protocol" is one of the fields used to
1562 // create a socket connection. Documentation here:
1563 // https://chromium.googlesource.com/chromium/src/+/HEAD/net/docs/life-of-a-url-request.md
1564 // under "Socket Pools" section.
1565 EXPECT_EQ(delegate.redirect_info().new_url, secure_url);
1566 EXPECT_TRUE(delegate.redirect_info().new_url.SchemeIs("https"));
1567 EXPECT_THAT(delegate.request_status(), net::ERR_IO_PENDING);
1568
1569 req->FollowDeferredRedirect(std::nullopt /* removed_headers */,
1570 std::nullopt /* modified_headers */);
1571 delegate.RunUntilComplete();
1572 EXPECT_EQ(kSecureContent, delegate.data_received());
1573 EXPECT_FALSE(req->was_cached());
1574 ASSERT_TRUE(https_server.ShutdownAndWaitUntilComplete());
1575 }
1576 }
1577
TEST_F(URLRequestHttpJobTest,HSTSInternalRedirectCallback)1578 TEST_F(URLRequestHttpJobTest, HSTSInternalRedirectCallback) {
1579 EmbeddedTestServer https_test(EmbeddedTestServer::TYPE_HTTPS);
1580 https_test.AddDefaultHandlers(base::FilePath());
1581 ASSERT_TRUE(https_test.Start());
1582
1583 auto context = CreateTestURLRequestContextBuilder()->Build();
1584 context->transport_security_state()->AddHSTS(
1585 "127.0.0.1", base::Time::Now() + base::Seconds(10), true);
1586 ASSERT_TRUE(
1587 context->transport_security_state()->ShouldUpgradeToSSL("127.0.0.1"));
1588
1589 GURL::Replacements replace_scheme;
1590 replace_scheme.SetSchemeStr("http");
1591
1592 {
1593 GURL url(
1594 https_test.GetURL("/echoheader").ReplaceComponents(replace_scheme));
1595 TestDelegate delegate;
1596 HttpRequestHeaders extra_headers;
1597 extra_headers.SetHeader("X-HSTS-Test", "1");
1598
1599 HttpRawRequestHeaders raw_req_headers;
1600
1601 std::unique_ptr<URLRequest> r(context->CreateRequest(
1602 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
1603 r->SetExtraRequestHeaders(extra_headers);
1604 r->SetRequestHeadersCallback(base::BindRepeating(
1605 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
1606
1607 r->Start();
1608 delegate.RunUntilRedirect();
1609
1610 EXPECT_FALSE(raw_req_headers.headers().empty());
1611 std::string value;
1612 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-HSTS-Test", &value));
1613 EXPECT_EQ("1", value);
1614 EXPECT_EQ("GET /echoheader HTTP/1.1\r\n", raw_req_headers.request_line());
1615
1616 raw_req_headers = HttpRawRequestHeaders();
1617
1618 r->FollowDeferredRedirect(std::nullopt /* removed_headers */,
1619 std::nullopt /* modified_headers */);
1620 delegate.RunUntilComplete();
1621
1622 EXPECT_FALSE(raw_req_headers.headers().empty());
1623 }
1624
1625 {
1626 GURL url(https_test.GetURL("/echoheader?foo=bar")
1627 .ReplaceComponents(replace_scheme));
1628 TestDelegate delegate;
1629
1630 HttpRawRequestHeaders raw_req_headers;
1631
1632 std::unique_ptr<URLRequest> r(context->CreateRequest(
1633 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
1634 r->SetRequestHeadersCallback(base::BindRepeating(
1635 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
1636
1637 r->Start();
1638 delegate.RunUntilRedirect();
1639
1640 EXPECT_EQ("GET /echoheader?foo=bar HTTP/1.1\r\n",
1641 raw_req_headers.request_line());
1642 }
1643
1644 {
1645 GURL url(
1646 https_test.GetURL("/echoheader#foo").ReplaceComponents(replace_scheme));
1647 TestDelegate delegate;
1648
1649 HttpRawRequestHeaders raw_req_headers;
1650
1651 std::unique_ptr<URLRequest> r(context->CreateRequest(
1652 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
1653 r->SetRequestHeadersCallback(base::BindRepeating(
1654 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
1655
1656 r->Start();
1657 delegate.RunUntilRedirect();
1658
1659 EXPECT_EQ("GET /echoheader HTTP/1.1\r\n", raw_req_headers.request_line());
1660 }
1661 }
1662
1663 class URLRequestHttpJobWithBrotliSupportTest : public TestWithTaskEnvironment {
1664 protected:
URLRequestHttpJobWithBrotliSupportTest()1665 URLRequestHttpJobWithBrotliSupportTest() {
1666 HttpNetworkSessionParams params;
1667 auto context_builder = CreateTestURLRequestContextBuilder();
1668 context_builder->set_enable_brotli(true);
1669 context_builder->set_http_network_session_params(params);
1670 context_builder->set_client_socket_factory_for_testing(&socket_factory_);
1671 context_ = context_builder->Build();
1672 }
1673
1674 MockClientSocketFactory socket_factory_;
1675 std::unique_ptr<URLRequestContext> context_;
1676 };
1677
TEST_F(URLRequestHttpJobWithBrotliSupportTest,NoBrotliAdvertisementOverHttp)1678 TEST_F(URLRequestHttpJobWithBrotliSupportTest, NoBrotliAdvertisementOverHttp) {
1679 MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
1680 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1681 "Content-Length: 12\r\n\r\n"),
1682 MockRead("Test Content")};
1683 StaticSocketDataProvider socket_data(reads, writes);
1684 socket_factory_.AddSocketDataProvider(&socket_data);
1685
1686 TestDelegate delegate;
1687 std::unique_ptr<URLRequest> request =
1688 context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
1689 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
1690 request->Start();
1691 delegate.RunUntilComplete();
1692
1693 EXPECT_THAT(delegate.request_status(), IsOk());
1694 EXPECT_EQ(12, request->received_response_content_length());
1695 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
1696 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
1697 }
1698
TEST_F(URLRequestHttpJobWithBrotliSupportTest,BrotliAdvertisement)1699 TEST_F(URLRequestHttpJobWithBrotliSupportTest, BrotliAdvertisement) {
1700 net::SSLSocketDataProvider ssl_socket_data_provider(net::ASYNC, net::OK);
1701 ssl_socket_data_provider.next_proto = kProtoHTTP11;
1702 ssl_socket_data_provider.ssl_info.cert =
1703 ImportCertFromFile(GetTestCertsDirectory(), "unittest.selfsigned.der");
1704 ASSERT_TRUE(ssl_socket_data_provider.ssl_info.cert);
1705 socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data_provider);
1706
1707 MockWrite writes[] = {
1708 MockWrite("GET / HTTP/1.1\r\n"
1709 "Host: www.example.com\r\n"
1710 "Connection: keep-alive\r\n"
1711 "User-Agent: \r\n"
1712 "Accept-Encoding: gzip, deflate, br\r\n"
1713 "Accept-Language: en-us,fr\r\n\r\n")};
1714 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1715 "Content-Length: 12\r\n\r\n"),
1716 MockRead("Test Content")};
1717 StaticSocketDataProvider socket_data(reads, writes);
1718 socket_factory_.AddSocketDataProvider(&socket_data);
1719
1720 TestDelegate delegate;
1721 std::unique_ptr<URLRequest> request =
1722 context_->CreateRequest(GURL("https://www.example.com"), DEFAULT_PRIORITY,
1723 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
1724 request->Start();
1725 delegate.RunUntilComplete();
1726
1727 EXPECT_THAT(delegate.request_status(), IsOk());
1728 EXPECT_EQ(12, request->received_response_content_length());
1729 EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
1730 EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
1731 }
1732
TEST_F(URLRequestHttpJobWithBrotliSupportTest,DefaultAcceptEncodingOverriden)1733 TEST_F(URLRequestHttpJobWithBrotliSupportTest, DefaultAcceptEncodingOverriden) {
1734 struct {
1735 base::flat_set<net::SourceStream::SourceType> accepted_types;
1736 const char* expected_request_headers;
1737 } kTestCases[] = {{{net::SourceStream::SourceType::TYPE_DEFLATE},
1738 "GET / HTTP/1.1\r\n"
1739 "Host: www.example.com\r\n"
1740 "Connection: keep-alive\r\n"
1741 "User-Agent: \r\n"
1742 "Accept-Encoding: deflate\r\n"
1743 "Accept-Language: en-us,fr\r\n\r\n"},
1744 {{},
1745 "GET / HTTP/1.1\r\n"
1746 "Host: www.example.com\r\n"
1747 "Connection: keep-alive\r\n"
1748 "User-Agent: \r\n"
1749 "Accept-Language: en-us,fr\r\n\r\n"},
1750 {{net::SourceStream::SourceType::TYPE_GZIP},
1751 "GET / HTTP/1.1\r\n"
1752 "Host: www.example.com\r\n"
1753 "Connection: keep-alive\r\n"
1754 "User-Agent: \r\n"
1755 "Accept-Encoding: gzip\r\n"
1756 "Accept-Language: en-us,fr\r\n\r\n"},
1757 {{net::SourceStream::SourceType::TYPE_GZIP,
1758 net::SourceStream::SourceType::TYPE_DEFLATE},
1759 "GET / HTTP/1.1\r\n"
1760 "Host: www.example.com\r\n"
1761 "Connection: keep-alive\r\n"
1762 "User-Agent: \r\n"
1763 "Accept-Encoding: gzip, deflate\r\n"
1764 "Accept-Language: en-us,fr\r\n\r\n"},
1765 {{net::SourceStream::SourceType::TYPE_BROTLI},
1766 "GET / HTTP/1.1\r\n"
1767 "Host: www.example.com\r\n"
1768 "Connection: keep-alive\r\n"
1769 "User-Agent: \r\n"
1770 "Accept-Encoding: br\r\n"
1771 "Accept-Language: en-us,fr\r\n\r\n"},
1772 {{net::SourceStream::SourceType::TYPE_BROTLI,
1773 net::SourceStream::SourceType::TYPE_GZIP,
1774 net::SourceStream::SourceType::TYPE_DEFLATE},
1775 "GET / HTTP/1.1\r\n"
1776 "Host: www.example.com\r\n"
1777 "Connection: keep-alive\r\n"
1778 "User-Agent: \r\n"
1779 "Accept-Encoding: gzip, deflate, br\r\n"
1780 "Accept-Language: en-us,fr\r\n\r\n"}};
1781
1782 for (auto test : kTestCases) {
1783 net::SSLSocketDataProvider ssl_socket_data_provider(net::ASYNC, net::OK);
1784 ssl_socket_data_provider.next_proto = kProtoHTTP11;
1785 ssl_socket_data_provider.ssl_info.cert =
1786 ImportCertFromFile(GetTestCertsDirectory(), "unittest.selfsigned.der");
1787 ASSERT_TRUE(ssl_socket_data_provider.ssl_info.cert);
1788 socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data_provider);
1789
1790 MockWrite writes[] = {MockWrite(test.expected_request_headers)};
1791 MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
1792 "Content-Length: 12\r\n\r\n"),
1793 MockRead("Test Content")};
1794 StaticSocketDataProvider socket_data(reads, writes);
1795 socket_factory_.AddSocketDataProvider(&socket_data);
1796
1797 TestDelegate delegate;
1798 std::unique_ptr<URLRequest> request = context_->CreateRequest(
1799 GURL("https://www.example.com"), DEFAULT_PRIORITY, &delegate,
1800 TRAFFIC_ANNOTATION_FOR_TESTS);
1801 request->set_accepted_stream_types(test.accepted_types);
1802 request->Start();
1803 delegate.RunUntilComplete();
1804 EXPECT_THAT(delegate.request_status(), IsOk());
1805 socket_factory_.ResetNextMockIndexes();
1806 }
1807 }
1808
1809 #if BUILDFLAG(IS_ANDROID)
1810 class URLRequestHttpJobWithCheckClearTextPermittedTest
1811 : public TestWithTaskEnvironment {
1812 protected:
URLRequestHttpJobWithCheckClearTextPermittedTest()1813 URLRequestHttpJobWithCheckClearTextPermittedTest() {
1814 auto context_builder = CreateTestURLRequestContextBuilder();
1815 context_builder->SetHttpTransactionFactoryForTesting(
1816 std::make_unique<MockNetworkLayer>());
1817 context_builder->set_check_cleartext_permitted(true);
1818 context_builder->set_client_socket_factory_for_testing(&socket_factory_);
1819 context_ = context_builder->Build();
1820 }
1821
1822 MockClientSocketFactory socket_factory_;
1823 std::unique_ptr<URLRequestContext> context_;
1824 };
1825
TEST_F(URLRequestHttpJobWithCheckClearTextPermittedTest,AndroidCleartextPermittedTest)1826 TEST_F(URLRequestHttpJobWithCheckClearTextPermittedTest,
1827 AndroidCleartextPermittedTest) {
1828 static constexpr struct TestCase {
1829 const char* url;
1830 bool cleartext_permitted;
1831 bool should_block;
1832 int expected_per_host_call_count;
1833 int expected_default_call_count;
1834 } kTestCases[] = {
1835 {"http://unblocked.test/", true, false, 1, 0},
1836 {"https://unblocked.test/", true, false, 0, 0},
1837 {"http://blocked.test/", false, true, 1, 0},
1838 {"https://blocked.test/", false, false, 0, 0},
1839 // If determining the per-host cleartext policy causes an
1840 // IllegalArgumentException (because the hostname is invalid),
1841 // the default configuration should be applied, and the
1842 // exception should not cause a JNI error.
1843 {"http://./", false, true, 1, 1},
1844 {"http://./", true, false, 1, 1},
1845 // Even if the host name would be considered invalid, https
1846 // schemes should not trigger cleartext policy checks.
1847 {"https://./", false, false, 0, 0},
1848 };
1849
1850 JNIEnv* env = base::android::AttachCurrentThread();
1851 for (const TestCase& test : kTestCases) {
1852 Java_AndroidNetworkLibraryTestUtil_setUpSecurityPolicyForTesting(
1853 env, test.cleartext_permitted);
1854
1855 TestDelegate delegate;
1856 std::unique_ptr<URLRequest> request =
1857 context_->CreateRequest(GURL(test.url), DEFAULT_PRIORITY, &delegate,
1858 TRAFFIC_ANNOTATION_FOR_TESTS);
1859 request->Start();
1860 delegate.RunUntilComplete();
1861
1862 if (test.should_block) {
1863 EXPECT_THAT(delegate.request_status(),
1864 IsError(ERR_CLEARTEXT_NOT_PERMITTED));
1865 } else {
1866 // Should fail since there's no test server running
1867 EXPECT_THAT(delegate.request_status(), IsError(ERR_FAILED));
1868 }
1869 EXPECT_EQ(
1870 Java_AndroidNetworkLibraryTestUtil_getPerHostCleartextCheckCount(env),
1871 test.expected_per_host_call_count);
1872 EXPECT_EQ(
1873 Java_AndroidNetworkLibraryTestUtil_getDefaultCleartextCheckCount(env),
1874 test.expected_default_call_count);
1875 }
1876 }
1877 #endif
1878
1879 #if BUILDFLAG(ENABLE_WEBSOCKETS)
1880
1881 class URLRequestHttpJobWebSocketTest : public TestWithTaskEnvironment {
1882 protected:
URLRequestHttpJobWebSocketTest()1883 URLRequestHttpJobWebSocketTest() {
1884 auto context_builder = CreateTestURLRequestContextBuilder();
1885 context_builder->set_client_socket_factory_for_testing(&socket_factory_);
1886 context_ = context_builder->Build();
1887 req_ =
1888 context_->CreateRequest(GURL("ws://www.example.org"), DEFAULT_PRIORITY,
1889 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS,
1890 /*is_for_websockets=*/true);
1891 }
1892
1893 std::unique_ptr<URLRequestContext> context_;
1894 MockClientSocketFactory socket_factory_;
1895 TestDelegate delegate_;
1896 std::unique_ptr<URLRequest> req_;
1897 };
1898
TEST_F(URLRequestHttpJobWebSocketTest,RejectedWithoutCreateHelper)1899 TEST_F(URLRequestHttpJobWebSocketTest, RejectedWithoutCreateHelper) {
1900 req_->Start();
1901 delegate_.RunUntilComplete();
1902 EXPECT_THAT(delegate_.request_status(), IsError(ERR_DISALLOWED_URL_SCHEME));
1903 }
1904
TEST_F(URLRequestHttpJobWebSocketTest,CreateHelperPassedThrough)1905 TEST_F(URLRequestHttpJobWebSocketTest, CreateHelperPassedThrough) {
1906 HttpRequestHeaders headers;
1907 headers.SetHeader("Connection", "Upgrade");
1908 headers.SetHeader("Upgrade", "websocket");
1909 headers.SetHeader("Origin", "http://www.example.org");
1910 headers.SetHeader("Sec-WebSocket-Version", "13");
1911 req_->SetExtraRequestHeaders(headers);
1912
1913 MockWrite writes[] = {
1914 MockWrite("GET / HTTP/1.1\r\n"
1915 "Host: www.example.org\r\n"
1916 "Connection: Upgrade\r\n"
1917 "Upgrade: websocket\r\n"
1918 "Origin: http://www.example.org\r\n"
1919 "Sec-WebSocket-Version: 13\r\n"
1920 "User-Agent: \r\n"
1921 "Accept-Encoding: gzip, deflate\r\n"
1922 "Accept-Language: en-us,fr\r\n"
1923 "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
1924 "Sec-WebSocket-Extensions: permessage-deflate; "
1925 "client_max_window_bits\r\n\r\n")};
1926
1927 MockRead reads[] = {
1928 MockRead("HTTP/1.1 101 Switching Protocols\r\n"
1929 "Upgrade: websocket\r\n"
1930 "Connection: Upgrade\r\n"
1931 "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"),
1932 MockRead(ASYNC, 0)};
1933
1934 StaticSocketDataProvider data(reads, writes);
1935 socket_factory_.AddSocketDataProvider(&data);
1936
1937 auto websocket_stream_create_helper =
1938 std::make_unique<TestWebSocketHandshakeStreamCreateHelper>();
1939
1940 req_->SetUserData(kWebSocketHandshakeUserDataKey,
1941 std::move(websocket_stream_create_helper));
1942 req_->SetLoadFlags(LOAD_DISABLE_CACHE);
1943 req_->Start();
1944 delegate_.RunUntilComplete();
1945 EXPECT_THAT(delegate_.request_status(), IsOk());
1946 EXPECT_TRUE(delegate_.response_completed());
1947
1948 EXPECT_TRUE(data.AllWriteDataConsumed());
1949 EXPECT_TRUE(data.AllReadDataConsumed());
1950 }
1951
1952 #endif // BUILDFLAG(ENABLE_WEBSOCKETS)
1953
SetAllCookies(CookieMonster * cm,const CookieList & list)1954 bool SetAllCookies(CookieMonster* cm, const CookieList& list) {
1955 DCHECK(cm);
1956 ResultSavingCookieCallback<CookieAccessResult> callback;
1957 cm->SetAllCookiesAsync(list, callback.MakeCallback());
1958 callback.WaitUntilDone();
1959 return callback.result().status.IsInclude();
1960 }
1961
CreateAndSetCookie(CookieStore * cs,const GURL & url,const std::string & cookie_line)1962 bool CreateAndSetCookie(CookieStore* cs,
1963 const GURL& url,
1964 const std::string& cookie_line) {
1965 auto cookie =
1966 CanonicalCookie::CreateForTesting(url, cookie_line, base::Time::Now());
1967 if (!cookie)
1968 return false;
1969 DCHECK(cs);
1970 ResultSavingCookieCallback<CookieAccessResult> callback;
1971 cs->SetCanonicalCookieAsync(std::move(cookie), url,
1972 CookieOptions::MakeAllInclusive(),
1973 callback.MakeCallback());
1974 callback.WaitUntilDone();
1975 return callback.result().status.IsInclude();
1976 }
1977
RunRequest(URLRequestContext * context,const GURL & url)1978 void RunRequest(URLRequestContext* context, const GURL& url) {
1979 TestDelegate delegate;
1980 std::unique_ptr<URLRequest> request = context->CreateRequest(
1981 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
1982
1983 // Make this a laxly same-site context to allow setting
1984 // SameSite=Lax-by-default cookies.
1985 request->set_site_for_cookies(SiteForCookies::FromUrl(url));
1986 request->Start();
1987 delegate.RunUntilComplete();
1988 }
1989
1990 } // namespace
1991
TEST_F(URLRequestHttpJobTest,CookieSchemeRequestSchemeHistogram)1992 TEST_F(URLRequestHttpJobTest, CookieSchemeRequestSchemeHistogram) {
1993 base::HistogramTester histograms;
1994 const std::string test_histogram = "Cookie.CookieSchemeRequestScheme";
1995
1996 auto context_builder = CreateTestURLRequestContextBuilder();
1997 context_builder->SetCookieStore(std::make_unique<CookieMonster>(
1998 /*store=*/nullptr, /*net_log=*/nullptr));
1999 auto context = context_builder->Build();
2000
2001 auto* cookie_store = static_cast<CookieMonster*>(context->cookie_store());
2002
2003 // Secure set cookie marked as Unset source scheme.
2004 // Using port 7 because it fails the transaction without sending a request and
2005 // prevents a timeout due to the fake addresses. Because we only need the
2006 // headers to be generated (and thus the histogram filled) and not actually
2007 // sent this is acceptable.
2008 GURL nonsecure_url_for_unset1("http://unset1.example:7");
2009 GURL secure_url_for_unset1("https://unset1.example:7");
2010
2011 // Normally the source scheme would be set by
2012 // CookieMonster::SetCanonicalCookie(), however we're using SetAllCookies() to
2013 // bypass the source scheme check in order to test the kUnset state which
2014 // would normally only happen during an existing cookie DB version upgrade.
2015 std::unique_ptr<CanonicalCookie> unset_cookie1 =
2016 CanonicalCookie::CreateForTesting(
2017 secure_url_for_unset1, "NoSourceSchemeHttps=val", base::Time::Now());
2018 unset_cookie1->SetSourceScheme(net::CookieSourceScheme::kUnset);
2019
2020 CookieList list1 = {*unset_cookie1};
2021 EXPECT_TRUE(SetAllCookies(cookie_store, list1));
2022 RunRequest(context.get(), nonsecure_url_for_unset1);
2023 histograms.ExpectBucketCount(
2024 test_histogram,
2025 URLRequestHttpJob::CookieRequestScheme::kUnsetCookieScheme, 1);
2026 RunRequest(context.get(), secure_url_for_unset1);
2027 histograms.ExpectBucketCount(
2028 test_histogram,
2029 URLRequestHttpJob::CookieRequestScheme::kUnsetCookieScheme, 2);
2030
2031 // Nonsecure set cookie marked as unset source scheme.
2032 GURL nonsecure_url_for_unset2("http://unset2.example:7");
2033 GURL secure_url_for_unset2("https://unset2.example:7");
2034
2035 std::unique_ptr<CanonicalCookie> unset_cookie2 =
2036 CanonicalCookie::CreateForTesting(nonsecure_url_for_unset2,
2037 "NoSourceSchemeHttp=val",
2038 base::Time::Now());
2039 unset_cookie2->SetSourceScheme(net::CookieSourceScheme::kUnset);
2040
2041 CookieList list2 = {*unset_cookie2};
2042 EXPECT_TRUE(SetAllCookies(cookie_store, list2));
2043 RunRequest(context.get(), nonsecure_url_for_unset2);
2044 histograms.ExpectBucketCount(
2045 test_histogram,
2046 URLRequestHttpJob::CookieRequestScheme::kUnsetCookieScheme, 3);
2047 RunRequest(context.get(), secure_url_for_unset2);
2048 histograms.ExpectBucketCount(
2049 test_histogram,
2050 URLRequestHttpJob::CookieRequestScheme::kUnsetCookieScheme, 4);
2051
2052 // Secure set cookie with source scheme marked appropriately.
2053 GURL nonsecure_url_for_secure_set("http://secureset.example:7");
2054 GURL secure_url_for_secure_set("https://secureset.example:7");
2055
2056 EXPECT_TRUE(CreateAndSetCookie(cookie_store, secure_url_for_secure_set,
2057 "SecureScheme=val"));
2058 RunRequest(context.get(), nonsecure_url_for_secure_set);
2059 histograms.ExpectBucketCount(
2060 test_histogram,
2061 URLRequestHttpJob::CookieRequestScheme::kSecureSetNonsecureRequest, 1);
2062 RunRequest(context.get(), secure_url_for_secure_set);
2063 histograms.ExpectBucketCount(
2064 test_histogram,
2065 URLRequestHttpJob::CookieRequestScheme::kSecureSetSecureRequest, 1);
2066
2067 // Nonsecure set cookie with source scheme marked appropriately.
2068 GURL nonsecure_url_for_nonsecure_set("http://nonsecureset.example:7");
2069 GURL secure_url_for_nonsecure_set("https://nonsecureset.example:7");
2070
2071 EXPECT_TRUE(CreateAndSetCookie(cookie_store, nonsecure_url_for_nonsecure_set,
2072 "NonSecureScheme=val"));
2073 RunRequest(context.get(), nonsecure_url_for_nonsecure_set);
2074 histograms.ExpectBucketCount(
2075 test_histogram,
2076 URLRequestHttpJob::CookieRequestScheme::kNonsecureSetNonsecureRequest, 1);
2077 RunRequest(context.get(), secure_url_for_nonsecure_set);
2078 histograms.ExpectBucketCount(
2079 test_histogram,
2080 URLRequestHttpJob::CookieRequestScheme::kNonsecureSetSecureRequest, 1);
2081 }
2082
2083 // Test that cookies are annotated with the appropriate exclusion reason when
2084 // privacy mode is enabled.
TEST_F(URLRequestHttpJobTest,PrivacyMode_ExclusionReason)2085 TEST_F(URLRequestHttpJobTest, PrivacyMode_ExclusionReason) {
2086 HttpTestServer test_server;
2087 ASSERT_TRUE(test_server.Start());
2088
2089 auto context_builder = CreateTestURLRequestContextBuilder();
2090 context_builder->SetCookieStore(std::make_unique<CookieMonster>(
2091 /*store=*/nullptr, /*net_log=*/nullptr));
2092 auto& network_delegate = *context_builder->set_network_delegate(
2093 std::make_unique<FilteringTestNetworkDelegate>());
2094 auto context = context_builder->Build();
2095
2096 // Set cookies.
2097 {
2098 TestDelegate d;
2099 GURL test_url = test_server.GetURL(
2100 "/set-cookie?one=1&"
2101 "two=2&"
2102 "three=3");
2103 std::unique_ptr<URLRequest> req =
2104 CreateFirstPartyRequest(*context, test_url, &d);
2105 req->Start();
2106 d.RunUntilComplete();
2107 }
2108
2109 // Get cookies.
2110 network_delegate.ResetAnnotateCookiesCalledCount();
2111 ASSERT_EQ(0, network_delegate.annotate_cookies_called_count());
2112 // We want to fetch cookies from the cookie store, so we use the
2113 // NetworkDelegate to override the privacy mode (rather than setting it via
2114 // `allow_credentials`, since that skips querying the cookie store).
2115 network_delegate.set_force_privacy_mode(true);
2116 TestDelegate d;
2117 std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
2118 *context, test_server.GetURL("/echoheader?Cookie"), &d);
2119 req->Start();
2120 d.RunUntilComplete();
2121
2122 EXPECT_EQ("None", d.data_received());
2123 EXPECT_THAT(
2124 req->maybe_sent_cookies(),
2125 UnorderedElementsAre(
2126 MatchesCookieWithAccessResult(
2127 MatchesCookieWithNameSourceType("one", CookieSourceType::kHTTP),
2128 MatchesCookieAccessResult(
2129 HasExactlyExclusionReasonsForTesting(
2130 std::vector<CookieInclusionStatus::ExclusionReason>{
2131 CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}),
2132 _, _, _)),
2133 MatchesCookieWithAccessResult(
2134 MatchesCookieWithNameSourceType("two", CookieSourceType::kHTTP),
2135 MatchesCookieAccessResult(
2136 HasExactlyExclusionReasonsForTesting(
2137 std::vector<CookieInclusionStatus::ExclusionReason>{
2138 CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}),
2139 _, _, _)),
2140 MatchesCookieWithAccessResult(
2141 MatchesCookieWithNameSourceType("three", CookieSourceType::kHTTP),
2142 MatchesCookieAccessResult(
2143 HasExactlyExclusionReasonsForTesting(
2144 std::vector<CookieInclusionStatus::ExclusionReason>{
2145 CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}),
2146 _, _, _))));
2147
2148 EXPECT_EQ(0, network_delegate.annotate_cookies_called_count());
2149 }
2150
2151 // Test that cookies are allowed to be selectively blocked by the network
2152 // delegate.
TEST_F(URLRequestHttpJobTest,IndividuallyBlockedCookies)2153 TEST_F(URLRequestHttpJobTest, IndividuallyBlockedCookies) {
2154 HttpTestServer test_server;
2155 ASSERT_TRUE(test_server.Start());
2156
2157 auto network_delegate = std::make_unique<FilteringTestNetworkDelegate>();
2158 network_delegate->set_block_get_cookies_by_name(true);
2159 network_delegate->SetCookieFilter("blocked_");
2160 auto context_builder = CreateTestURLRequestContextBuilder();
2161 context_builder->SetCookieStore(std::make_unique<CookieMonster>(
2162 /*store=*/nullptr, /*net_log=*/nullptr));
2163 context_builder->set_network_delegate(std::move(network_delegate));
2164 auto context = context_builder->Build();
2165
2166 // Set cookies.
2167 {
2168 TestDelegate d;
2169 GURL test_url = test_server.GetURL(
2170 "/set-cookie?blocked_one=1;SameSite=Lax;Secure&"
2171 "blocked_two=1;SameSite=Lax;Secure&"
2172 "allowed=1;SameSite=Lax;Secure");
2173 std::unique_ptr<URLRequest> req =
2174 CreateFirstPartyRequest(*context, test_url, &d);
2175 req->Start();
2176 d.RunUntilComplete();
2177 }
2178
2179 // Get cookies.
2180 TestDelegate d;
2181 std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
2182 *context, test_server.GetURL("/echoheader?Cookie"), &d);
2183 req->Start();
2184 d.RunUntilComplete();
2185
2186 EXPECT_EQ("allowed=1", d.data_received());
2187 EXPECT_THAT(
2188 req->maybe_sent_cookies(),
2189 UnorderedElementsAre(
2190 MatchesCookieWithAccessResult(
2191 MatchesCookieWithNameSourceType("blocked_one",
2192 CookieSourceType::kHTTP),
2193 MatchesCookieAccessResult(
2194 HasExactlyExclusionReasonsForTesting(
2195 std::vector<CookieInclusionStatus::ExclusionReason>{
2196 CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}),
2197 _, _, _)),
2198 MatchesCookieWithAccessResult(
2199 MatchesCookieWithNameSourceType("blocked_two",
2200 CookieSourceType::kHTTP),
2201 MatchesCookieAccessResult(
2202 HasExactlyExclusionReasonsForTesting(
2203 std::vector<CookieInclusionStatus::ExclusionReason>{
2204 CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}),
2205 _, _, _)),
2206 MatchesCookieWithAccessResult(
2207 MatchesCookieWithNameSourceType("allowed",
2208 CookieSourceType::kHTTP),
2209 MatchesCookieAccessResult(IsInclude(), _, _, _))));
2210 }
2211
2212 namespace {
2213
2214 int content_count = 0;
IncreaseOnRequest(const test_server::HttpRequest & request)2215 std::unique_ptr<test_server::HttpResponse> IncreaseOnRequest(
2216 const test_server::HttpRequest& request) {
2217 auto http_response = std::make_unique<test_server::BasicHttpResponse>();
2218 http_response->set_content(base::NumberToString(content_count));
2219 content_count++;
2220 return std::move(http_response);
2221 }
2222
ResetContentCount()2223 void ResetContentCount() {
2224 content_count = 0;
2225 }
2226
2227 } // namespace
2228
TEST_F(URLRequestHttpJobTest,GetFirstPartySetsCacheFilterMatchInfo)2229 TEST_F(URLRequestHttpJobTest, GetFirstPartySetsCacheFilterMatchInfo) {
2230 EmbeddedTestServer https_test(EmbeddedTestServer::TYPE_HTTPS);
2231 https_test.AddDefaultHandlers(base::FilePath());
2232 https_test.RegisterRequestHandler(base::BindRepeating(&IncreaseOnRequest));
2233 ASSERT_TRUE(https_test.Start());
2234
2235 auto context_builder = CreateTestURLRequestContextBuilder();
2236 auto cookie_access_delegate = std::make_unique<TestCookieAccessDelegate>();
2237 TestCookieAccessDelegate* raw_cookie_access_delegate =
2238 cookie_access_delegate.get();
2239 auto cm = std::make_unique<CookieMonster>(nullptr, nullptr);
2240 cm->SetCookieAccessDelegate(std::move(cookie_access_delegate));
2241 context_builder->SetCookieStore(std::move(cm));
2242 auto context = context_builder->Build();
2243
2244 const GURL kTestUrl = https_test.GetURL("/");
2245 const IsolationInfo kTestIsolationInfo =
2246 IsolationInfo::CreateForInternalRequest(url::Origin::Create(kTestUrl));
2247 {
2248 TestDelegate delegate;
2249 std::unique_ptr<URLRequest> req(context->CreateRequest(
2250 kTestUrl, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
2251 req->set_isolation_info(kTestIsolationInfo);
2252 req->set_allow_credentials(false);
2253 req->Start();
2254 delegate.RunUntilComplete();
2255 EXPECT_EQ("0", delegate.data_received());
2256 }
2257 { // Test using the cached response.
2258 TestDelegate delegate;
2259 std::unique_ptr<URLRequest> req(context->CreateRequest(
2260 kTestUrl, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
2261 req->SetLoadFlags(LOAD_SKIP_CACHE_VALIDATION);
2262 req->set_allow_credentials(false);
2263 req->set_isolation_info(kTestIsolationInfo);
2264 req->Start();
2265 delegate.RunUntilComplete();
2266 EXPECT_EQ("0", delegate.data_received());
2267 }
2268
2269 // Set cache filter and test cache is bypassed because the request site has a
2270 // matched entry in the filter and its response cache was stored before being
2271 // marked to clear.
2272 const int64_t kClearAtRunId = 3;
2273 const int64_t kBrowserRunId = 3;
2274 FirstPartySetsCacheFilter cache_filter(
2275 {{SchemefulSite(kTestUrl), kClearAtRunId}}, kBrowserRunId);
2276 raw_cookie_access_delegate->set_first_party_sets_cache_filter(
2277 std::move(cache_filter));
2278 {
2279 TestDelegate delegate;
2280 std::unique_ptr<URLRequest> req(context->CreateRequest(
2281 kTestUrl, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
2282 req->SetLoadFlags(LOAD_SKIP_CACHE_VALIDATION);
2283 req->set_allow_credentials(false);
2284 req->set_isolation_info(kTestIsolationInfo);
2285 req->Start();
2286 delegate.RunUntilComplete();
2287 EXPECT_EQ("1", delegate.data_received());
2288 }
2289
2290 ResetContentCount();
2291 }
2292
TEST_F(URLRequestHttpJobTest,SetPartitionedCookie)2293 TEST_F(URLRequestHttpJobTest, SetPartitionedCookie) {
2294 EmbeddedTestServer https_test(EmbeddedTestServer::TYPE_HTTPS);
2295 https_test.AddDefaultHandlers(base::FilePath());
2296 ASSERT_TRUE(https_test.Start());
2297
2298 auto context_builder = CreateTestURLRequestContextBuilder();
2299 context_builder->SetCookieStore(std::make_unique<CookieMonster>(
2300 /*store=*/nullptr, /*net_log=*/nullptr));
2301 auto context = context_builder->Build();
2302
2303 const url::Origin kTopFrameOrigin =
2304 url::Origin::Create(GURL("https://www.toplevelsite.com"));
2305 const IsolationInfo kTestIsolationInfo =
2306 IsolationInfo::CreateForInternalRequest(kTopFrameOrigin);
2307
2308 {
2309 TestDelegate delegate;
2310 std::unique_ptr<URLRequest> req(context->CreateRequest(
2311 https_test.GetURL(
2312 "/set-cookie?__Host-foo=bar;SameSite=None;Secure;Path=/"
2313 ";Partitioned;"),
2314 DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
2315
2316 req->set_isolation_info(kTestIsolationInfo);
2317 req->Start();
2318 ASSERT_TRUE(req->is_pending());
2319 delegate.RunUntilComplete();
2320 }
2321
2322 { // Test request from the same top-level site.
2323 TestDelegate delegate;
2324 std::unique_ptr<URLRequest> req(context->CreateRequest(
2325 https_test.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &delegate,
2326 TRAFFIC_ANNOTATION_FOR_TESTS));
2327 req->set_isolation_info(kTestIsolationInfo);
2328 req->Start();
2329 delegate.RunUntilComplete();
2330 EXPECT_EQ("__Host-foo=bar", delegate.data_received());
2331 }
2332
2333 { // Test request from a different top-level site.
2334 const url::Origin kOtherTopFrameOrigin =
2335 url::Origin::Create(GURL("https://www.anothertoplevelsite.com"));
2336 const IsolationInfo kOtherTestIsolationInfo =
2337 IsolationInfo::CreateForInternalRequest(kOtherTopFrameOrigin);
2338
2339 TestDelegate delegate;
2340 std::unique_ptr<URLRequest> req(context->CreateRequest(
2341 https_test.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &delegate,
2342 TRAFFIC_ANNOTATION_FOR_TESTS));
2343 req->set_isolation_info(kOtherTestIsolationInfo);
2344 req->Start();
2345 delegate.RunUntilComplete();
2346 EXPECT_EQ("None", delegate.data_received());
2347 }
2348
2349 { // Test request from same top-level eTLD+1 but different scheme. Note that
2350 // although the top-level site is insecure, the endpoint setting/receiving
2351 // the cookie is always secure.
2352 const url::Origin kHttpTopFrameOrigin =
2353 url::Origin::Create(GURL("http://www.toplevelsite.com"));
2354 const IsolationInfo kHttpTestIsolationInfo =
2355 IsolationInfo::CreateForInternalRequest(kHttpTopFrameOrigin);
2356
2357 TestDelegate delegate;
2358 std::unique_ptr<URLRequest> req(context->CreateRequest(
2359 https_test.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &delegate,
2360 TRAFFIC_ANNOTATION_FOR_TESTS));
2361 req->set_isolation_info(kHttpTestIsolationInfo);
2362 req->Start();
2363 delegate.RunUntilComplete();
2364 EXPECT_EQ("None", delegate.data_received());
2365 }
2366 }
2367
TEST_F(URLRequestHttpJobTest,PartitionedCookiePrivacyMode)2368 TEST_F(URLRequestHttpJobTest, PartitionedCookiePrivacyMode) {
2369 EmbeddedTestServer https_test(EmbeddedTestServer::TYPE_HTTPS);
2370 https_test.AddDefaultHandlers(base::FilePath());
2371 ASSERT_TRUE(https_test.Start());
2372
2373 auto context_builder = CreateTestURLRequestContextBuilder();
2374 context_builder->SetCookieStore(
2375 std::make_unique<CookieMonster>(/*store=*/nullptr, /*net_log=*/nullptr));
2376 auto& network_delegate = *context_builder->set_network_delegate(
2377 std::make_unique<FilteringTestNetworkDelegate>());
2378 auto context = context_builder->Build();
2379
2380 const url::Origin kTopFrameOrigin =
2381 url::Origin::Create(GURL("https://www.toplevelsite.com"));
2382 const IsolationInfo kTestIsolationInfo =
2383 IsolationInfo::CreateForInternalRequest(kTopFrameOrigin);
2384
2385 {
2386 // Set an unpartitioned and partitioned cookie.
2387 TestDelegate delegate;
2388 std::unique_ptr<URLRequest> req(context->CreateRequest(
2389 https_test.GetURL(
2390 "/set-cookie?__Host-partitioned=0;SameSite=None;Secure;Path=/"
2391 ";Partitioned;&__Host-unpartitioned=1;SameSite=None;Secure;Path=/"),
2392 DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
2393 req->set_isolation_info(kTestIsolationInfo);
2394 req->Start();
2395 ASSERT_TRUE(req->is_pending());
2396 delegate.RunUntilComplete();
2397 }
2398
2399 { // Get both cookies when privacy mode is disabled.
2400 TestDelegate delegate;
2401 std::unique_ptr<URLRequest> req(context->CreateRequest(
2402 https_test.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &delegate,
2403 TRAFFIC_ANNOTATION_FOR_TESTS));
2404 req->set_isolation_info(kTestIsolationInfo);
2405 req->Start();
2406 delegate.RunUntilComplete();
2407 EXPECT_EQ("__Host-partitioned=0; __Host-unpartitioned=1",
2408 delegate.data_received());
2409 }
2410
2411 { // Get cookies with privacy mode enabled and partitioned state allowed.
2412 network_delegate.set_force_privacy_mode(true);
2413 network_delegate.set_partitioned_state_allowed(true);
2414 network_delegate.SetCookieFilter("unpartitioned");
2415 network_delegate.set_block_get_cookies_by_name(true);
2416 TestDelegate delegate;
2417 std::unique_ptr<URLRequest> req(context->CreateRequest(
2418 https_test.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &delegate,
2419 TRAFFIC_ANNOTATION_FOR_TESTS));
2420 req->set_isolation_info(kTestIsolationInfo);
2421 req->Start();
2422 delegate.RunUntilComplete();
2423 EXPECT_EQ("__Host-partitioned=0", delegate.data_received());
2424 auto want_exclusion_reasons =
2425 std::vector<CookieInclusionStatus::ExclusionReason>{};
2426
2427 EXPECT_THAT(
2428 req->maybe_sent_cookies(),
2429 UnorderedElementsAre(
2430 MatchesCookieWithAccessResult(
2431 MatchesCookieWithNameSourceType("__Host-partitioned",
2432 CookieSourceType::kHTTP),
2433 MatchesCookieAccessResult(HasExactlyExclusionReasonsForTesting(
2434 want_exclusion_reasons),
2435 _, _, _)),
2436 MatchesCookieWithAccessResult(
2437 MatchesCookieWithNameSourceType("__Host-unpartitioned",
2438 CookieSourceType::kHTTP),
2439 MatchesCookieAccessResult(
2440 HasExactlyExclusionReasonsForTesting(
2441 std::vector<CookieInclusionStatus::ExclusionReason>{
2442 CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}),
2443 _, _, _))));
2444 }
2445
2446 { // Get cookies with privacy mode enabled and partitioned state is not
2447 // allowed.
2448 network_delegate.set_force_privacy_mode(true);
2449 network_delegate.set_partitioned_state_allowed(false);
2450 TestDelegate delegate;
2451 std::unique_ptr<URLRequest> req(context->CreateRequest(
2452 https_test.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &delegate,
2453 TRAFFIC_ANNOTATION_FOR_TESTS));
2454 req->set_isolation_info(kTestIsolationInfo);
2455 req->Start();
2456 delegate.RunUntilComplete();
2457 EXPECT_EQ("None", delegate.data_received());
2458 EXPECT_THAT(
2459 req->maybe_sent_cookies(),
2460 UnorderedElementsAre(
2461 MatchesCookieWithAccessResult(
2462 MatchesCookieWithNameSourceType("__Host-partitioned",
2463 CookieSourceType::kHTTP),
2464 MatchesCookieAccessResult(
2465 HasExactlyExclusionReasonsForTesting(
2466 std::vector<CookieInclusionStatus::ExclusionReason>{
2467 CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}),
2468 _, _, _)),
2469 MatchesCookieWithAccessResult(
2470 MatchesCookieWithNameSourceType("__Host-unpartitioned",
2471 CookieSourceType::kHTTP),
2472 MatchesCookieAccessResult(
2473 HasExactlyExclusionReasonsForTesting(
2474 std::vector<CookieInclusionStatus::ExclusionReason>{
2475 CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}),
2476 _, _, _))));
2477 }
2478 }
2479
2480 } // namespace net
2481