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