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