summaryrefslogtreecommitdiff
path: root/chromium/content/browser/loader/prefetch_browsertest.cc
blob: da0ea6f9f6460b7007939ca2df78e47a126c4678 (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
// Copyright 2018 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 <map>
#include <string>
#include <vector>

#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "content/browser/loader/prefetch_url_loader_service.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/web_package/mock_signed_exchange_handler.h"
#include "content/browser/web_package/web_package_loader.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "services/network/public/cpp/features.h"

namespace content {

struct PrefetchBrowserTestParam {
  PrefetchBrowserTestParam(bool network_service_enabled,
                           bool signed_exchange_enabled)
      : network_service_enabled(network_service_enabled),
        signed_exchange_enabled(signed_exchange_enabled) {}
  const bool network_service_enabled;
  const bool signed_exchange_enabled;
};

struct ScopedSignedExchangeHandlerFactory {
  explicit ScopedSignedExchangeHandlerFactory(
      SignedExchangeHandlerFactory* factory) {
    WebPackageLoader::SetSignedExchangeHandlerFactoryForTest(factory);
  }
  ~ScopedSignedExchangeHandlerFactory() {
    WebPackageLoader::SetSignedExchangeHandlerFactoryForTest(nullptr);
  }
};

class PrefetchBrowserTest
    : public ContentBrowserTest,
      public testing::WithParamInterface<PrefetchBrowserTestParam> {
 public:
  struct ResponseEntry {
    ResponseEntry() = default;
    explicit ResponseEntry(
        const std::string& content,
        const std::string& content_type = "text/html",
        const std::vector<std::pair<std::string, std::string>>& headers = {})
        : content(content), content_type(content_type), headers(headers) {}
    ~ResponseEntry() = default;
    std::string content;
    std::string content_type;
    std::vector<std::pair<std::string, std::string>> headers;
  };

  PrefetchBrowserTest() = default;
  ~PrefetchBrowserTest() = default;

  void SetUp() override {
    std::vector<base::Feature> enable_features;
    if (GetParam().network_service_enabled)
      enable_features.push_back(network::features::kNetworkService);
    if (GetParam().signed_exchange_enabled)
      enable_features.push_back(features::kSignedHTTPExchange);
    feature_list_.InitWithFeatures(enable_features, {});
    ContentBrowserTest::SetUp();
  }

  void SetUpOnMainThread() override {
    ContentBrowserTest::SetUpOnMainThread();
    StoragePartitionImpl* partition = static_cast<StoragePartitionImpl*>(
        BrowserContext::GetDefaultStoragePartition(
            shell()->web_contents()->GetBrowserContext()));
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        BindOnce(
            &PrefetchURLLoaderService::RegisterPrefetchLoaderCallbackForTest,
            base::RetainedRef(partition->GetPrefetchURLLoaderService()),
            base::BindRepeating(&PrefetchBrowserTest::OnPrefetchURLLoaderCalled,
                                base::Unretained(this))));
  }

  void RegisterResponse(const std::string& url, const ResponseEntry& entry) {
    response_map_[url] = entry;
  }

  std::unique_ptr<net::test_server::HttpResponse> ServeResponses(
      const net::test_server::HttpRequest& request) {
    auto found = response_map_.find(request.relative_url);
    if (found != response_map_.end()) {
      auto response = std::make_unique<net::test_server::BasicHttpResponse>();
      response->set_code(net::HTTP_OK);
      response->set_content(found->second.content);
      response->set_content_type(found->second.content_type);
      for (const auto& header : found->second.headers)
        response->AddCustomHeader(header.first, header.second);
      return std::move(response);
    }
    return nullptr;
  }

  void WatchURLAndRunClosure(const std::string& relative_url,
                             int* visit_count,
                             base::OnceClosure closure,
                             const net::test_server::HttpRequest& request) {
    if (request.relative_url == relative_url) {
      (*visit_count)++;
      if (closure)
        std::move(closure).Run();
    }
  }

  void OnPrefetchURLLoaderCalled() { prefetch_url_loader_called_++; }

  bool CheckPrefetchURLLoaderCountIfSupported(int expected) const {
    if (!base::FeatureList::IsEnabled(features::kSignedHTTPExchange) &&
        !base::FeatureList::IsEnabled(network::features::kNetworkService))
      return true;
    return prefetch_url_loader_called_ == expected;
  }

  int prefetch_url_loader_called_ = 0;

 private:
  base::test::ScopedFeatureList feature_list_;
  std::map<std::string, ResponseEntry> response_map_;

  DISALLOW_COPY_AND_ASSIGN(PrefetchBrowserTest);
};

IN_PROC_BROWSER_TEST_P(PrefetchBrowserTest, Simple) {
  int target_fetch_count = 0;
  const char* prefetch_url = "/prefetch.html";
  const char* target_url = "/target.html";
  RegisterResponse(
      prefetch_url,
      ResponseEntry(base::StringPrintf(
          "<body><link rel='prefetch' href='%s'></body>", target_url)));
  RegisterResponse(
      target_url, ResponseEntry("<head><title>Prefetch Target</title></head>"));

  base::RunLoop prefetch_waiter;
  embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
      &PrefetchBrowserTest::WatchURLAndRunClosure, base::Unretained(this),
      target_url, &target_fetch_count, prefetch_waiter.QuitClosure()));
  embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
      &PrefetchBrowserTest::ServeResponses, base::Unretained(this)));
  ASSERT_TRUE(embedded_test_server()->Start());
  EXPECT_EQ(0, target_fetch_count);
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(0));

  // Loading a page that prefetches the target URL would increment the
  // |target_fetch_count|.
  NavigateToURL(shell(), embedded_test_server()->GetURL(prefetch_url));
  prefetch_waiter.Run();
  EXPECT_EQ(1, target_fetch_count);
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(1));

  // Subsequent navigation to the target URL wouldn't hit the network for
  // the target URL (therefore not increment |target_fetch_count|.
  // The target content should still be read correctly.
  base::string16 title = base::ASCIIToUTF16("Prefetch Target");
  TitleWatcher title_watcher(shell()->web_contents(), title);
  NavigateToURL(shell(), embedded_test_server()->GetURL(target_url));
  EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
  EXPECT_EQ(1, target_fetch_count);
}

IN_PROC_BROWSER_TEST_P(PrefetchBrowserTest, DoublePrefetch) {
  int target_fetch_count = 0;
  const char* prefetch_url = "/prefetch.html";
  const char* target_url = "/target.html";
  RegisterResponse(prefetch_url, ResponseEntry(base::StringPrintf(
                                     "<body><link rel='prefetch' href='%s'>"
                                     "<link rel='prefetch' href='%s'></body>",
                                     target_url, target_url)));
  RegisterResponse(
      target_url, ResponseEntry("<head><title>Prefetch Target</title></head>"));

  base::RunLoop prefetch_waiter;
  embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
      &PrefetchBrowserTest::WatchURLAndRunClosure, base::Unretained(this),
      target_url, &target_fetch_count, prefetch_waiter.QuitClosure()));
  embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
      &PrefetchBrowserTest::ServeResponses, base::Unretained(this)));
  ASSERT_TRUE(embedded_test_server()->Start());
  EXPECT_EQ(0, target_fetch_count);
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(0));

  // Loading a page that prefetches the target URL would increment the
  // |target_fetch_count|, but it should hit only once.
  NavigateToURL(shell(), embedded_test_server()->GetURL(prefetch_url));
  prefetch_waiter.Run();
  EXPECT_EQ(1, target_fetch_count);
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(1));

  // Subsequent navigation to the target URL wouldn't hit the network for
  // the target URL (therefore not increment |target_fetch_count|.
  // The target content should still be read correctly.
  base::string16 title = base::ASCIIToUTF16("Prefetch Target");
  TitleWatcher title_watcher(shell()->web_contents(), title);
  NavigateToURL(shell(), embedded_test_server()->GetURL(target_url));
  EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
  EXPECT_EQ(1, target_fetch_count);
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(1));
}

IN_PROC_BROWSER_TEST_P(PrefetchBrowserTest, NoCacheAndNoStore) {
  int nocache_fetch_count = 0;
  int nostore_fetch_count = 0;
  const char* prefetch_url = "/prefetch.html";
  const char* nocache_url = "/target1.html";
  const char* nostore_url = "/target2.html";
  RegisterResponse(prefetch_url, ResponseEntry(base::StringPrintf(
                                     "<body>"
                                     "<link rel='prefetch' href='%s'>"
                                     "<link rel='prefetch' href='%s'></body>",
                                     nocache_url, nostore_url)));
  RegisterResponse(nocache_url,
                   ResponseEntry("<head><title>NoCache Target</title></head>",
                                 "text/html", {{"cache-control", "no-cache"}}));
  RegisterResponse(nostore_url,
                   ResponseEntry("<head><title>NoStore Target</title></head>",
                                 "text/html", {{"cache-control", "no-store"}}));

  base::RunLoop nocache_waiter;
  base::RunLoop nostore_waiter;
  embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
      &PrefetchBrowserTest::WatchURLAndRunClosure, base::Unretained(this),
      nocache_url, &nocache_fetch_count, nocache_waiter.QuitClosure()));
  embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
      &PrefetchBrowserTest::WatchURLAndRunClosure, base::Unretained(this),
      nostore_url, &nostore_fetch_count, nostore_waiter.QuitClosure()));
  embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
      &PrefetchBrowserTest::ServeResponses, base::Unretained(this)));
  ASSERT_TRUE(embedded_test_server()->Start());
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(0));

  // Loading a page that prefetches the target URL would increment the
  // fetch count for the both targets.
  NavigateToURL(shell(), embedded_test_server()->GetURL(prefetch_url));
  nocache_waiter.Run();
  nostore_waiter.Run();
  EXPECT_EQ(1, nocache_fetch_count);
  EXPECT_EQ(1, nostore_fetch_count);
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(2));

  {
    // Subsequent navigation to the no-cache URL wouldn't hit the network,
    // because no-cache resource is kept available up to kPrefetchReuseMins.
    base::string16 title = base::ASCIIToUTF16("NoCache Target");
    TitleWatcher title_watcher(shell()->web_contents(), title);
    NavigateToURL(shell(), embedded_test_server()->GetURL(nocache_url));
    EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
    EXPECT_EQ(1, nocache_fetch_count);
  }
  {
    // Subsequent navigation to the no-store URL hit the network again,
    // because no-store resource is not cached even for prefetch.
    base::string16 title = base::ASCIIToUTF16("NoStore Target");
    TitleWatcher title_watcher(shell()->web_contents(), title);
    NavigateToURL(shell(), embedded_test_server()->GetURL(nostore_url));
    EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
    EXPECT_EQ(2, nostore_fetch_count);
  }
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(2));
}

IN_PROC_BROWSER_TEST_P(PrefetchBrowserTest, WithPreload) {
  int target_fetch_count = 0;
  int preload_fetch_count = 0;
  const char* prefetch_url = "/prefetch.html";
  const char* target_url = "/target.html";
  const char* preload_url = "/preload.js";
  RegisterResponse(
      prefetch_url,
      ResponseEntry(base::StringPrintf(
          "<body><link rel='prefetch' href='%s'></body>", target_url)));
  RegisterResponse(
      target_url,
      ResponseEntry(
          "<head><title>Prefetch Target</title></head>", "text/html",
          {{"link", "<./preload.js>;rel=\"preload\";as=\"script\""}}));
  RegisterResponse(preload_url,
                   ResponseEntry("function foo() {}", "text/javascript"));

  base::RunLoop preload_waiter;
  embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
      &PrefetchBrowserTest::WatchURLAndRunClosure, base::Unretained(this),
      target_url, &target_fetch_count, base::RepeatingClosure()));
  embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
      &PrefetchBrowserTest::WatchURLAndRunClosure, base::Unretained(this),
      preload_url, &preload_fetch_count, preload_waiter.QuitClosure()));
  embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
      &PrefetchBrowserTest::ServeResponses, base::Unretained(this)));
  ASSERT_TRUE(embedded_test_server()->Start());
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(0));

  // Loading a page that prefetches the target URL would increment both
  // |target_fetch_count| and |preload_fetch_count|.
  NavigateToURL(shell(), embedded_test_server()->GetURL(prefetch_url));
  preload_waiter.Run();
  EXPECT_EQ(1, target_fetch_count);
  EXPECT_EQ(1, preload_fetch_count);
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(1));

  int preload_url_entries = 0;
  while (preload_url_entries == 0) {
    const bool result = ExecuteScriptAndExtractInt(
        shell()->web_contents(),
        base::StringPrintf(
            "window.domAutomationController.send(performance.getEntriesByName('"
            "%s').length)",
            embedded_test_server()->GetURL(preload_url).spec().c_str()),
        &preload_url_entries);
    ASSERT_TRUE(result);
  }
  EXPECT_GE(preload_url_entries, 1);
}

IN_PROC_BROWSER_TEST_P(PrefetchBrowserTest, WebPackageWithPreload) {
  int target_fetch_count = 0;
  int preload_fetch_count = 0;
  const char* prefetch_url = "/prefetch.html";
  const char* target_htxg = "/target.htxg";
  const char* target_url = "/target.html";
  const char* preload_url_in_htxg = "/preload.js";

  RegisterResponse(
      prefetch_url,
      ResponseEntry(base::StringPrintf(
          "<body><link rel='prefetch' href='%s'></body>", target_htxg)));
  RegisterResponse(
      target_htxg,
      // We mock the SignedExchangeHandler, so just return a HTML content
      // as "application/signed-exchange;v=b0".
      ResponseEntry("<head><title>Prefetch Target (HTXG)</title></head>",
                    "application/signed-exchange;v=b0"));
  RegisterResponse(preload_url_in_htxg,
                   ResponseEntry("function foo() {}", "text/javascript"));

  base::RunLoop preload_waiter;
  base::RunLoop prefetch_waiter;
  embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
      &PrefetchBrowserTest::WatchURLAndRunClosure, base::Unretained(this),
      target_htxg, &target_fetch_count, prefetch_waiter.QuitClosure()));
  embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
      &PrefetchBrowserTest::WatchURLAndRunClosure, base::Unretained(this),
      preload_url_in_htxg, &preload_fetch_count, preload_waiter.QuitClosure()));
  embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
      &PrefetchBrowserTest::ServeResponses, base::Unretained(this)));
  ASSERT_TRUE(embedded_test_server()->Start());
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(0));

  MockSignedExchangeHandlerFactory factory(
      net::OK, GURL(target_url), "text/html",
      {base::StringPrintf(
          "Link: <%s>;rel=\"preload\";as=\"script\"",
          embedded_test_server()->GetURL(preload_url_in_htxg).spec().c_str())});
  ScopedSignedExchangeHandlerFactory scoped_factory(&factory);

  // Loading a page that prefetches the target URL would increment both
  // |target_fetch_count| and |preload_fetch_count|.
  NavigateToURL(shell(), embedded_test_server()->GetURL(prefetch_url));
  prefetch_waiter.Run();
  EXPECT_EQ(1, target_fetch_count);
  EXPECT_TRUE(CheckPrefetchURLLoaderCountIfSupported(1));

  // Test after this point requires SignedHTTPExchange support.
  if (!base::FeatureList::IsEnabled(features::kSignedHTTPExchange))
    return;

  // If the header in the .htxg file is correctly extracted, we should
  // be able to also see the preload.
  preload_waiter.Run();
  EXPECT_EQ(1, preload_fetch_count);
}

INSTANTIATE_TEST_CASE_P(PrefetchBrowserTest,
                        PrefetchBrowserTest,
                        testing::Values(PrefetchBrowserTestParam(true, true),
                                        PrefetchBrowserTestParam(true, false),
                                        PrefetchBrowserTestParam(false, true),
                                        PrefetchBrowserTestParam(false,
                                                                 false)));

}  // namespace content