summaryrefslogtreecommitdiff
path: root/chromium/components/data_reduction_proxy/core/browser/data_reduction_proxy_interceptor_unittest.cc
blob: 4d8f08897a217ff1563328cb2ef847cd04774909 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_interceptor.h"

#include <string>
#include <utility>
#include <vector>

#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/test/histogram_tester.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_test_utils.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_configurator.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_server.h"
#include "components/data_reduction_proxy/proto/client_config.pb.h"
#include "components/prefs/pref_service.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/http/http_response_headers.h"
#include "net/log/test_net_log.h"
#include "net/proxy/proxy_server.h"
#include "net/socket/socket_test_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_interceptor.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"

using net::MockRead;

namespace data_reduction_proxy {

namespace {

class CountingURLRequestInterceptor : public net::URLRequestInterceptor {
 public:
  CountingURLRequestInterceptor()
      : request_count_(0), redirect_count_(0), response_count_(0) {
  }

  // URLRequestInterceptor implementation:
  net::URLRequestJob* MaybeInterceptRequest(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const override {
    request_count_++;
    return nullptr;
  }

  net::URLRequestJob* MaybeInterceptRedirect(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate,
      const GURL& location) const override {
    redirect_count_++;
    return nullptr;
  }

  net::URLRequestJob* MaybeInterceptResponse(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const override {
    response_count_++;
    return nullptr;
  }

  int request_count() const {
    return request_count_;
  }

  int redirect_count() const {
    return redirect_count_;
  }

  int response_count() const {
    return response_count_;
  }

 private:
  mutable int request_count_;
  mutable int redirect_count_;
  mutable int response_count_;
};

class TestURLRequestContextWithDataReductionProxy
    : public net::TestURLRequestContext {
 public:
  TestURLRequestContextWithDataReductionProxy(const net::ProxyServer& origin,
                                              net::NetworkDelegate* delegate)
      : net::TestURLRequestContext(true) {
    context_storage_.set_proxy_service(
        net::ProxyService::CreateFixed(origin.ToURI()));
    set_network_delegate(delegate);
  }

  ~TestURLRequestContextWithDataReductionProxy() override {}
};

class DataReductionProxyInterceptorTest : public testing::Test {
 public:
  DataReductionProxyInterceptorTest() {
    test_context_ =
        DataReductionProxyTestContext::Builder()
            .WithParamsFlags(0)
            .WithParamsDefinitions(TestDataReductionProxyParams::HAS_EVERYTHING)
            .Build();
    default_context_.reset(new TestURLRequestContextWithDataReductionProxy(
        test_context_->config()
            ->test_params()
            ->proxies_for_http()
            .front()
            .proxy_server(),
        &default_network_delegate_));
    default_context_->set_network_delegate(&default_network_delegate_);
    default_context_->set_net_log(test_context_->net_log());
  }

  ~DataReductionProxyInterceptorTest() override {
    // URLRequestJobs may post clean-up tasks on destruction.
    base::RunLoop().RunUntilIdle();
  }

  void Init(std::unique_ptr<net::URLRequestJobFactory> factory) {
    job_factory_ = std::move(factory);
    default_context_->set_job_factory(job_factory_.get());
    default_context_->Init();
  }

  base::MessageLoopForIO message_loop_;
  std::unique_ptr<DataReductionProxyTestContext> test_context_;
  net::TestNetworkDelegate default_network_delegate_;
  std::unique_ptr<net::URLRequestJobFactory> job_factory_;
  std::unique_ptr<net::TestURLRequestContext> default_context_;
};

// Disabled on Mac due to flakiness. See crbug.com/601562.
#if defined(OS_MACOSX)
#define MAYBE_TestJobFactoryChaining DISABLED_TestJobFactoryChaining
#else
#define MAYBE_TestJobFactoryChaining TestJobFactoryChaining
#endif
TEST_F(DataReductionProxyInterceptorTest, MAYBE_TestJobFactoryChaining) {
  // Verifies that job factories can be chained.
  std::unique_ptr<net::URLRequestJobFactory> impl(
      new net::URLRequestJobFactoryImpl());

  CountingURLRequestInterceptor* interceptor2 =
      new CountingURLRequestInterceptor();
  std::unique_ptr<net::URLRequestJobFactory> factory2(
      new net::URLRequestInterceptingJobFactory(
          std::move(impl), base::WrapUnique(interceptor2)));

  CountingURLRequestInterceptor* interceptor1 =
      new CountingURLRequestInterceptor();
  std::unique_ptr<net::URLRequestJobFactory> factory1(
      new net::URLRequestInterceptingJobFactory(
          std::move(factory2), base::WrapUnique(interceptor1)));

  Init(std::move(factory1));

  net::TestDelegate d;
  std::unique_ptr<net::URLRequest> req(default_context_->CreateRequest(
      GURL("http://foo"), net::DEFAULT_PRIORITY, &d));

  req->Start();
  base::RunLoop().Run();
  EXPECT_EQ(1, interceptor1->request_count());
  EXPECT_EQ(0, interceptor1->redirect_count());
  EXPECT_EQ(1, interceptor1->response_count());
  EXPECT_EQ(1, interceptor2->request_count());
  EXPECT_EQ(0, interceptor2->redirect_count());
  EXPECT_EQ(1, interceptor2->response_count());
}

class DataReductionProxyInterceptorWithServerTest : public testing::Test {
 public:
  DataReductionProxyInterceptorWithServerTest()
      : context_(true) {
    context_.set_network_delegate(&network_delegate_);
    context_.set_net_log(&net_log_);
  }

  ~DataReductionProxyInterceptorWithServerTest() override {
    test_context_->io_data()->ShutdownOnUIThread();
    // URLRequestJobs may post clean-up tasks on destruction.
    test_context_->RunUntilIdle();
  }

  void SetUp() override {
    base::FilePath root_path, proxy_file_path, direct_file_path;
    PathService::Get(base::DIR_SOURCE_ROOT, &root_path);
    proxy_file_path = root_path.AppendASCII(
        "components/test/data/data_reduction_proxy/proxy");
    direct_file_path = root_path.AppendASCII(
        "components/test/data/data_reduction_proxy/direct");
    proxy_.ServeFilesFromDirectory(proxy_file_path);
    direct_.ServeFilesFromDirectory(direct_file_path);
    ASSERT_TRUE(proxy_.Start());
    ASSERT_TRUE(direct_.Start());

    test_context_ = DataReductionProxyTestContext::Builder()
                        .WithParamsFlags(0)
                        .WithURLRequestContext(&context_)
                        .Build();
    std::string spec;
    base::TrimString(proxy_.GetURL("/").spec(), "/", &spec);
    net::ProxyServer origin =
        net::ProxyServer::FromURI(spec, net::ProxyServer::SCHEME_HTTP);
    std::vector<DataReductionProxyServer> proxies_for_http;
    proxies_for_http.push_back(
        DataReductionProxyServer(origin, ProxyServer::UNSPECIFIED_TYPE));
    test_context_->config()->test_params()->SetProxiesForHttp(proxies_for_http);
    std::string proxy_name = origin.ToURI();
    proxy_service_ = net::ProxyService::CreateFixedFromPacResult(
        "PROXY " + proxy_name + "; DIRECT");

    context_.set_proxy_service(proxy_service_.get());

    std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory_impl(
        new net::URLRequestJobFactoryImpl());
    job_factory_.reset(new net::URLRequestInterceptingJobFactory(
        std::move(job_factory_impl),
        test_context_->io_data()->CreateInterceptor()));
    context_.set_job_factory(job_factory_.get());
    context_.Init();
  }

  const net::TestURLRequestContext& context() {
    return context_;
  }

  const net::EmbeddedTestServer& direct() { return direct_; }

 private:
  base::MessageLoopForIO message_loop_;
  net::TestNetLog net_log_;
  net::TestNetworkDelegate network_delegate_;
  net::TestURLRequestContext context_;
  net::EmbeddedTestServer proxy_;
  net::EmbeddedTestServer direct_;
  std::unique_ptr<net::ProxyService> proxy_service_;
  std::unique_ptr<net::URLRequestJobFactory> job_factory_;
  std::unique_ptr<DataReductionProxyTestContext> test_context_;
};

TEST_F(DataReductionProxyInterceptorWithServerTest, TestBypass) {
  // Tests the mechanics of proxy bypass work with a "real" server. For tests
  // that cover every imaginable response that could trigger a bypass, see:
  // DataReductionProxyProtocolTest.
  net::TestDelegate delegate;
  std::unique_ptr<net::URLRequest> request(context().CreateRequest(
      direct().GetURL("/block10.html"), net::DEFAULT_PRIORITY, &delegate));
  request->Start();
  EXPECT_TRUE(request->is_pending());
  base::RunLoop().Run();

  EXPECT_EQ(net::OK, delegate.request_status());
  EXPECT_EQ("hello", delegate.data_received());
}

TEST_F(DataReductionProxyInterceptorWithServerTest, TestNoBypass) {
  net::TestDelegate delegate;
  std::unique_ptr<net::URLRequest> request(context().CreateRequest(
      direct().GetURL("/noblock.html"), net::DEFAULT_PRIORITY, &delegate));
  request->Start();
  EXPECT_TRUE(request->is_pending());
  base::RunLoop().Run();

  EXPECT_EQ(net::OK, delegate.request_status());
  EXPECT_EQ("hello", delegate.data_received());
}

class DataReductionProxyInterceptorEndToEndTest : public testing::Test {
 public:
  DataReductionProxyInterceptorEndToEndTest()
      : context_(true), context_storage_(&context_) {}

  ~DataReductionProxyInterceptorEndToEndTest() override {}

  void SetUp() override {
    drp_test_context_ =
        DataReductionProxyTestContext::Builder()
            .WithURLRequestContext(&context_)
            .WithMockClientSocketFactory(&mock_socket_factory_)
            .Build();
    drp_test_context_->AttachToURLRequestContext(&context_storage_);
    context_.set_client_socket_factory(&mock_socket_factory_);
    proxy_delegate_ = drp_test_context_->io_data()->CreateProxyDelegate();
    context_.set_proxy_delegate(proxy_delegate_.get());
    context_.Init();
    drp_test_context_->EnableDataReductionProxyWithSecureProxyCheckSuccess();

    // Three proxies should be available for use: primary, fallback, and direct.
    const net::ProxyConfig& proxy_config =
        drp_test_context_->configurator()->GetProxyConfig();
    EXPECT_EQ(3U, proxy_config.proxy_rules().proxies_for_http.size());
  }

  // Creates a URLRequest using the test's TestURLRequestContext and executes
  // it. Returns the created URLRequest.
  std::unique_ptr<net::URLRequest> CreateAndExecuteRequest(const GURL& url) {
    std::unique_ptr<net::URLRequest> request(
        context_.CreateRequest(url, net::IDLE, &delegate_));
    request->Start();
    drp_test_context_->RunUntilIdle();
    return request;
  }

  const net::TestDelegate& delegate() const { return delegate_; }

  net::MockClientSocketFactory* mock_socket_factory() {
    return &mock_socket_factory_;
  }

  TestDataReductionProxyConfig* config() const {
    return drp_test_context_->config();
  }

  net::ProxyServer origin() const {
    return config()->test_params()->proxies_for_http().front().proxy_server();
  }

 private:
  base::MessageLoopForIO message_loop_;
  net::TestDelegate delegate_;
  net::MockClientSocketFactory mock_socket_factory_;
  net::TestURLRequestContext context_;
  net::URLRequestContextStorage context_storage_;
  std::unique_ptr<net::ProxyDelegate> proxy_delegate_;
  std::unique_ptr<DataReductionProxyTestContext> drp_test_context_;
};

const std::string kBody = "response body";

TEST_F(DataReductionProxyInterceptorEndToEndTest, ResponseWithoutRetry) {
  // The response comes through the proxy and should not be retried.
  MockRead mock_reads[] = {
      MockRead("HTTP/1.1 200 OK\r\nVia: 1.1 Chrome-Compression-Proxy\r\n\r\n"),
      MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider socket_data_provider(
      mock_reads, arraysize(mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&socket_data_provider);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_EQ(origin(), request->proxy_server());
}

TEST_F(DataReductionProxyInterceptorEndToEndTest, RedirectWithoutRetry) {
  // The redirect comes through the proxy and should not be retried.
  MockRead redirect_mock_reads[] = {
      MockRead("HTTP/1.1 302 Found\r\n"
               "Via: 1.1 Chrome-Compression-Proxy\r\n"
               "Location: http://bar.com/\r\n\r\n"),
      MockRead(""),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider redirect_socket_data_provider(
      redirect_mock_reads, arraysize(redirect_mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&redirect_socket_data_provider);

  // The response after the redirect comes through proxy and should not be
  // retried.
  MockRead response_mock_reads[] = {
      MockRead("HTTP/1.1 200 OK\r\nVia: 1.1 Chrome-Compression-Proxy\r\n\r\n"),
      MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider response_socket_data_provider(
      response_mock_reads, arraysize(response_mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&response_socket_data_provider);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_EQ(origin(), request->proxy_server());
  // The redirect should have been processed and followed normally.
  EXPECT_EQ(1, delegate().received_redirect_count());
}

// Test that data reduction proxy is byppassed if there is a URL redirect cycle.
TEST_F(DataReductionProxyInterceptorEndToEndTest, URLRedirectCycle) {
  base::HistogramTester histogram_tester;
  MockRead redirect_mock_reads_1[] = {
      MockRead("HTTP/1.1 302 Found\r\n"
               "Via: 1.1 Chrome-Compression-Proxy\r\n"
               "Location: http://bar.com/\r\n\r\n"),
      MockRead(""), MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider redirect_socket_data_provider_1(
      redirect_mock_reads_1, arraysize(redirect_mock_reads_1), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(
      &redirect_socket_data_provider_1);

  MockRead redirect_mock_reads_2[] = {
      MockRead("HTTP/1.1 302 Found\r\n"
               "Via: 1.1 Chrome-Compression-Proxy\r\n"
               "Location: http://foo.com/\r\n\r\n"),
      MockRead(""), MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider redirect_socket_data_provider_2(
      redirect_mock_reads_2, arraysize(redirect_mock_reads_2), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(
      &redirect_socket_data_provider_2);

  // Redirect cycle.
  MockRead redirect_mock_reads_3[] = {
      MockRead("HTTP/1.1 302 Found\r\n"
               "Via: 1.1 Chrome-Compression-Proxy\r\n"
               "Location: http://bar.com/\r\n\r\n"),
      MockRead(""), MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider redirect_socket_data_provider_3(
      redirect_mock_reads_3, arraysize(redirect_mock_reads_3), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(
      &redirect_socket_data_provider_3);

  // Data reduction proxy should be bypassed.
  MockRead redirect_mock_reads_4[] = {
      MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider redirect_socket_data_provider_4(
      redirect_mock_reads_4, arraysize(redirect_mock_reads_4), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(
      &redirect_socket_data_provider_4);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_FALSE(request->was_fetched_via_proxy());
  histogram_tester.ExpectTotalCount(
      "DataReductionProxy.BypassedBytes.URLRedirectCycle", 1);
}

TEST_F(DataReductionProxyInterceptorEndToEndTest, ResponseWithBypassAndRetry) {
  // The first try gives a bypass.
  MockRead initial_mock_reads[] = {
      MockRead("HTTP/1.1 502 Bad Gateway\r\n"
               "Via: 1.1 Chrome-Compression-Proxy\r\n"
               "Chrome-Proxy: block-once\r\n\r\n"),
      MockRead(""),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider initial_socket_data_provider(
      initial_mock_reads, arraysize(initial_mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&initial_socket_data_provider);

  // The retry after the bypass is successful.
  MockRead retry_mock_reads[] = {
      MockRead("HTTP/1.1 200 OK\r\n\r\n"),
      MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider retry_socket_data_provider(
      retry_mock_reads, arraysize(retry_mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&retry_socket_data_provider);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_FALSE(request->was_fetched_via_proxy());
  // The bypassed response should have been intercepted before the response was
  // processed, so only the final response after the retry should have been
  // processed.
  EXPECT_EQ(1, delegate().response_started_count());
}

TEST_F(DataReductionProxyInterceptorEndToEndTest, RedirectWithBypassAndRetry) {
  MockRead mock_reads_array[][3] = {
      // First, get a redirect without a via header, which should be retried
      // using the fallback proxy.
      {
          MockRead("HTTP/1.1 302 Found\r\n"
                   "Location: http://bar.com/\r\n\r\n"),
          MockRead(""),
          MockRead(net::SYNCHRONOUS, net::OK),
      },
      // Same as before, but through the fallback proxy. Now both proxies are
      // bypassed, and the request should be retried over direct.
      {
          MockRead("HTTP/1.1 302 Found\r\n"
                   "Location: http://baz.com/\r\n\r\n"),
          MockRead(""),
          MockRead(net::SYNCHRONOUS, net::OK),
      },
      // Finally, a successful response is received.
      {
          MockRead("HTTP/1.1 200 OK\r\n\r\n"),
          MockRead(kBody.c_str()),
          MockRead(net::SYNCHRONOUS, net::OK),
      },
  };
  std::vector<std::unique_ptr<net::SocketDataProvider>> socket_data_providers;
  for (MockRead* mock_reads : mock_reads_array) {
    socket_data_providers.push_back(
        base::MakeUnique<net::StaticSocketDataProvider>(mock_reads, 3, nullptr,
                                                        0));
    mock_socket_factory()->AddSocketDataProvider(
        socket_data_providers.back().get());
  }

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_FALSE(request->was_fetched_via_proxy());

  // Each of the redirects should have been intercepted before being followed.
  EXPECT_EQ(0, delegate().received_redirect_count());
  EXPECT_EQ(std::vector<GURL>(1, GURL("http://foo.com")), request->url_chain());
}

// https://crbug.com/668197: Flaky on android_n5x_swarming_rel bot.
#if defined(OS_ANDROID)
#define MAYBE_RedirectChainToHttps DISABLED_RedirectChainToHttps
#else
#define MAYBE_RedirectChainToHttps RedirectChainToHttps
#endif
TEST_F(DataReductionProxyInterceptorEndToEndTest, MAYBE_RedirectChainToHttps) {
  // First, a redirect is successfully received through the Data Reduction
  // Proxy. HSTS is forced for play.google.com and prebaked into Chrome, so
  // http://play.google.com will automatically be redirected to
  // https://play.google.com. See net/http/transport_security_state_static.json.
  MockRead first_redirect_reads[] = {
      MockRead(
          "HTTP/1.1 302 Found\r\n"
          "Location: http://play.google.com\r\n"
          "Via: 1.1 Chrome-Compression-Proxy\r\n\r\n"),
      MockRead(""),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider first_redirect_socket(
      first_redirect_reads, arraysize(first_redirect_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&first_redirect_socket);

  // Receive the response for https://play.google.com.
  MockRead https_response_reads[] = {
      MockRead("HTTP/1.1 200 OK\r\n\r\n"),
      MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider https_response_socket(
      https_response_reads, arraysize(https_response_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&https_response_socket);
  net::SSLSocketDataProvider https_response_ssl_socket(net::SYNCHRONOUS,
                                                       net::OK);
  mock_socket_factory()->AddSSLSocketDataProvider(&https_response_ssl_socket);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://music.google.com"));
  EXPECT_FALSE(delegate().request_failed());
  EXPECT_EQ(kBody, delegate().data_received());

  std::vector<GURL> expected_url_chain;
  expected_url_chain.push_back(GURL("http://music.google.com"));
  expected_url_chain.push_back(GURL("http://play.google.com"));
  expected_url_chain.push_back(GURL("https://play.google.com"));
  EXPECT_EQ(expected_url_chain, request->url_chain());
}

}  // namespace

}  // namespace data_reduction_proxy