File: local_resource_url_loader_factory_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (347 lines) | stat: -rw-r--r-- 13,599 bytes parent folder | download | duplicates (3)
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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/renderer/local_resource_url_loader_factory.h"

#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "base/check.h"
#include "base/containers/flat_map.h"
#include "base/containers/span.h"
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/scoped_refptr.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/threading/sequence_bound.h"
#include "content/common/web_ui_loading_util.h"
#include "mojo/public/c/system/data_pipe.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_version.h"
#include "net/socket/socket.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "services/network/test/test_url_loader_client.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/loader/local_resource_loader_config.mojom.h"
#include "ui/base/resource/mock_resource_bundle_delegate.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/resource/resource_scale_factor.h"
#include "url/origin.h"
#include "url/url_util.h"

namespace {

// A URLLoaderFactory that always sends the string "out-of-process resource" to
// the client.
class FakeURLLoaderFactory : public network::mojom::URLLoaderFactory {
 public:
  FakeURLLoaderFactory() : receiver_(this) {}
  void CreateLoaderAndStart(
      mojo::PendingReceiver<network::mojom::URLLoader> loader,
      int32_t request_id,
      uint32_t options,
      const network::ResourceRequest& request,
      mojo::PendingRemote<network::mojom::URLLoaderClient> client,
      const net::MutableNetworkTrafficAnnotationTag& traffic_annotation)
      override {
    auto headers = network::mojom::URLResponseHead::New();
    auto bytes =
        base::MakeRefCounted<base::RefCountedString>("out-of-process resource");
    content::webui::SendData(std::move(headers), std::move(client),
                             std::nullopt, std::move(bytes));
  }
  void Clone(mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver)
      override {
    // Supports only one receiver at a time.
    receiver_.reset();
    receiver_.Bind(std::move(receiver));
  }

 private:
  mojo::Receiver<network::mojom::URLLoaderFactory> receiver_;
};

class LocalResourceURLLoaderFactoryTest : public ::testing::Test {
 public:
  void SetUp() override {
    // Swap in mock ResourceBundle.
    ui::ResourceBundle::InitSharedInstanceWithLocale(
        "en-US", &resource_bundle_delegate_,
        ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);

    source_ = blink::mojom::LocalResourceSource::New();
    source_->headers =
        net::HttpResponseHeaders::Builder(net::HttpVersion(1, 1), "200 OK")
            .Build()
            ->raw_headers();

    UpdateLoaderFactory();
  }

  void TearDown() override {
    ui::ResourceBundle::CleanupSharedInstance();
  }

 protected:
  // Used to control the behavior of the mock ResourceBundle.
  // Marked non-private so that tests can call EXPECT_CALL on it.
  testing::NiceMock<ui::MockResourceBundleDelegate> resource_bundle_delegate_;

  content::LocalResourceURLLoaderFactory* loader_factory() {
    return loader_factory_.get();
  }

  void SetShouldReplaceI18nInJs(bool value) {
    source_->should_replace_i18n_in_js = value;
    UpdateLoaderFactory();
  }

  void AddReplacementString(const std::string& key, const std::string& value) {
    source_->replacement_strings[key] = value;
    UpdateLoaderFactory();
  }

  void AddResourceID(const std::string& path, int id) {
    source_->path_to_resource_id_map[path] = id;
    UpdateLoaderFactory();
  }

  std::string ReadAllData(network::TestURLLoaderClient& client) {
    std::string result;
    CHECK(mojo::BlockingCopyToString(client.response_body_release(), &result));
    return result;
  }

 private:
  // Create a config with a |source_| as the single hardcoded entry in the map.
  void UpdateLoaderFactory() {
    const url::Origin origin = url::Origin::Create(GURL("chrome://sourcename"));
    auto config = blink::mojom::LocalResourceLoaderConfig::New();
    config->sources[origin] = source_.Clone();
    // Create a pipe and pass receiving end to |fake_fallback_factory_|.
    mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote;
    fake_fallback_factory_.Clone(
        pending_remote.InitWithNewPipeAndPassReceiver());
    // Pass other end to |loader_factory_|.
    loader_factory_ = std::make_unique<content::LocalResourceURLLoaderFactory>(
        std::move(config), std::move(pending_remote));
  }

  std::unique_ptr<content::LocalResourceURLLoaderFactory> loader_factory_;

  FakeURLLoaderFactory fake_fallback_factory_;

  // Intermediate state that is updated by the test and eventually used to
  // update the loader factory state.
  blink::mojom::LocalResourceSourcePtr source_;

  // Temporary storage of original ResourceBundle while we swap in the test
  // mock.
  ui::ResourceBundle::SharedInstanceSwapperForTesting resource_bundle_swapper_;

  // For CreateLoaderAndStart, which posts a task.
  base::test::TaskEnvironment task_environment_;
};

struct CanServeTestCase {
  std::optional<int> resource_id;
  bool has_resource;
  bool can_serve;
};

struct ServeTestCase {
  std::string path;
  std::string mime_type;
  std::string resource_data;
  std::string response_body;
};

struct RequestRangeTestCase {
  std::string request_range;
  int error_code;
  std::string resource_data;
  std::string response_body;
};

class LocalResourceURLLoaderFactoryCanServeTest
    : public LocalResourceURLLoaderFactoryTest,
      public ::testing::WithParamInterface<CanServeTestCase> {};
class LocalResourceURLLoaderFactoryServeTest
    : public LocalResourceURLLoaderFactoryTest,
      public ::testing::WithParamInterface<ServeTestCase> {};
class LocalResourceURLLoaderFactoryRequestRangeTest
    : public LocalResourceURLLoaderFactoryTest,
      public ::testing::WithParamInterface<RequestRangeTestCase> {};

}  // namespace

// Check if loader factory can service a particular request.
TEST_P(LocalResourceURLLoaderFactoryCanServeTest, CanServe) {
  const std::string path = "path/to/resource";
  if (GetParam().resource_id) {
    AddResourceID(path, *GetParam().resource_id);
  }
  const scoped_refptr<base::RefCountedString> resource_data =
      base::MakeRefCounted<base::RefCountedString>("in-process resource");
  ON_CALL(resource_bundle_delegate_, HasDataResource)
      .WillByDefault(testing::Return(GetParam().has_resource));
  ON_CALL(resource_bundle_delegate_, LoadDataResourceBytes)
      .WillByDefault(testing::Return(resource_data.get()));

  network::TestURLLoaderClient client;
  network::ResourceRequest request;
  // The test fixture hardcodes the origin to 'chrome://sourcename'.
  request.url = GURL("chrome://sourcename/" + path);
  mojo::PendingRemote<network::mojom::URLLoader> loader;
  loader_factory()->CreateLoaderAndStart(
      loader.InitWithNewPipeAndPassReceiver(), 0, 0, request,
      client.CreateRemote(), net::MutableNetworkTrafficAnnotationTag());
  client.RunUntilComplete();

  ASSERT_EQ(net::OK, client.completion_status().error_code);
  ASSERT_TRUE(client.response_body().is_valid());
  std::string response_body = ReadAllData(client);
  if (GetParam().can_serve) {
    EXPECT_EQ(response_body, "in-process resource");
  } else {
    EXPECT_EQ(response_body, "out-of-process resource");
  }
}

INSTANTIATE_TEST_SUITE_P(
    LocalResourceURLLoaderFactoryCanServeTest,
    LocalResourceURLLoaderFactoryCanServeTest,
    ::testing::Values(
        // Resource ID exists and ResourceBundle has the resource.
        CanServeTestCase(std::make_optional(1), true, true),
        // Resource ID exists but ResourceBundle does not have the resource.
        CanServeTestCase(std::make_optional(1), false, false),
        // Resource ID does not exist in mapping.
        CanServeTestCase(std::nullopt, false, false)));

// Create loader, read bytes from the ResourceBundle and send them to the
// client.
TEST_P(LocalResourceURLLoaderFactoryServeTest, Serve) {
  const int resource_id = 1;
  const scoped_refptr<base::RefCountedString> resource_data =
      base::MakeRefCounted<base::RefCountedString>(GetParam().resource_data);
  AddResourceID(GetParam().path, resource_id);
  AddReplacementString("foo", "bar");
  SetShouldReplaceI18nInJs(true);
  // Bypass the fallback by making CanServe return true.
  ON_CALL(resource_bundle_delegate_, HasDataResource)
      .WillByDefault(testing::Return(true));
  EXPECT_CALL(resource_bundle_delegate_,
              LoadDataResourceBytes(resource_id,
                                    ui::ResourceScaleFactor::kScaleFactorNone))
      .WillOnce(testing::Return(resource_data.get()));

  network::TestURLLoaderClient client;
  network::ResourceRequest request;
  // The test fixture hardcodes the origin to 'chrome://sourcename'.
  request.url = GURL("chrome://sourcename/" + GetParam().path);
  mojo::PendingRemote<network::mojom::URLLoader> loader;
  loader_factory()->CreateLoaderAndStart(
      loader.InitWithNewPipeAndPassReceiver(), 0, 0, request,
      client.CreateRemote(), net::MutableNetworkTrafficAnnotationTag());
  client.RunUntilComplete();

  ASSERT_EQ(net::OK, client.completion_status().error_code);
  EXPECT_EQ(GetParam().mime_type, client.response_head()->mime_type);
  ASSERT_TRUE(client.response_body().is_valid());
  std::string response_body = ReadAllData(client);
  EXPECT_EQ(GetParam().response_body, response_body);
}

INSTANTIATE_TEST_SUITE_P(
    LocalResourceURLLoaderFactoryServeTest,
    LocalResourceURLLoaderFactoryServeTest,
    ::testing::Values(
        // MIME type is assumed to be text/html. String replacement occurs.
        ServeTestCase("path/to/resource",
                      "text/html",
                      "this is $i18n{foo}",
                      "this is bar"),
        // MIME type is text/html. String replacement occurs.
        ServeTestCase("path/to/resource.html",
                      "text/html",
                      "this is $i18n{foo}",
                      "this is bar"),
        // MIME type is text/css. String replacement occurs.
        ServeTestCase("path/to/resource.css",
                      "text/css",
                      "this is $i18n{foo}",
                      "this is bar"),
        // MIME type is text/javascript. String replacement only occurs within
        // HTML template section.
        ServeTestCase("path/to/resource.js",
                      "text/javascript",
                      "this is $i18n{foo}",
                      "this is $i18n{foo}")));

// Request various byte ranges which may or may not be valid.
TEST_P(LocalResourceURLLoaderFactoryRequestRangeTest, RequestRange) {
  const std::string path = "path/to/resource";
  const int resource_id = 1;
  const scoped_refptr<base::RefCountedString> resource_data =
      base::MakeRefCounted<base::RefCountedString>(GetParam().resource_data);
  AddResourceID(path, resource_id);
  // Bypass the fallback by making CanServe return true.
  ON_CALL(resource_bundle_delegate_, HasDataResource)
      .WillByDefault(testing::Return(true));
  EXPECT_CALL(resource_bundle_delegate_,
              LoadDataResourceBytes(resource_id,
                                    ui::ResourceScaleFactor::kScaleFactorNone))
      .WillOnce(testing::Return(resource_data.get()));

  network::TestURLLoaderClient client;
  network::ResourceRequest request;
  // The test fixture hardcodes the origin to 'chrome://sourcename'.
  request.url = GURL("chrome://sourcename/" + path);
  request.headers.SetHeader(net::HttpRequestHeaders::kRange,
                            GetParam().request_range);
  mojo::PendingRemote<network::mojom::URLLoader> loader;
  loader_factory()->CreateLoaderAndStart(
      loader.InitWithNewPipeAndPassReceiver(), 0, 0, request,
      client.CreateRemote(), net::MutableNetworkTrafficAnnotationTag());
  client.RunUntilComplete();

  EXPECT_EQ(GetParam().error_code, client.completion_status().error_code);
  if (GetParam().error_code != net::OK) {
    return;
  }
  ASSERT_TRUE(client.response_body().is_valid());
  std::string response_body = ReadAllData(client);
  EXPECT_EQ(GetParam().response_body, response_body);
}

INSTANTIATE_TEST_SUITE_P(
    LocalResourceURLLoaderFactoryRequestRangeTest,
    LocalResourceURLLoaderFactoryRequestRangeTest,
    ::testing::Values(
        // Valid range.
        RequestRangeTestCase("bytes=3-10",
                             net::OK,
                             "resource data",
                             "ource da"),
        // Valid range, but starting byte is greater than resource size.
        // Error expected.
        RequestRangeTestCase("bytes=100-101",
                             net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)));