File: bitmap_fetcher_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (359 lines) | stat: -rw-r--r-- 12,658 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
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/bitmap_fetcher/bitmap_fetcher.h"

#include "base/compiler_specific.h"
#include "base/containers/span.h"
#include "base/functional/bind.h"
#include "base/run_loop.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/referrer_policy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/skia_util.h"

const bool kAsyncCall = true;
const bool kSyncCall = false;
const char kStartTestURL[] = "/this-should-work";
const char kOnImageDecodedTestURL[] = "/this-should-work-as-well";
const char kOnURLFetchFailureTestURL[] = "/this-should-be-fetch-failure";

using net::test_server::BasicHttpResponse;
using net::test_server::HttpRequest;
using net::test_server::HttpResponse;

// Class to catch events from the BitmapFetcher for testing.
class BitmapFetcherTestDelegate : public BitmapFetcherDelegate {
 public:
  explicit BitmapFetcherTestDelegate(bool async) : async_(async) {}

  BitmapFetcherTestDelegate(const BitmapFetcherTestDelegate&) = delete;
  BitmapFetcherTestDelegate& operator=(const BitmapFetcherTestDelegate&) =
      delete;

  ~BitmapFetcherTestDelegate() override { EXPECT_EQ(expect_called_, called_); }

  // Method inherited from BitmapFetcherDelegate.
  void OnFetchComplete(const GURL& url, const SkBitmap* bitmap) override {
    called_ = true;
    url_ = url;
    if (bitmap) {
      success_ = true;
      if (bitmap_.tryAllocPixels(bitmap->info())) {
        bitmap->readPixels(bitmap_.info(), bitmap_.getPixels(),
                           bitmap_.rowBytes(), 0, 0);
      }
    }
    // For async calls, we need to quit the run loop so the test can continue.
    if (async_)
      run_loop_.Quit();
  }

  // Waits until OnFetchComplete() is called. Should only be used for
  // async tests.
  void Wait() {
    ASSERT_TRUE(async_);
    run_loop_.Run();
  }

  GURL url() const { return url_; }
  bool success() const { return success_; }
  const SkBitmap& bitmap() const { return bitmap_; }

  void SetExpectNotToGetCalled() { expect_called_ = false; }

 private:
  base::RunLoop run_loop_;
  bool called_ = false;
  bool expect_called_ = true;
  GURL url_;
  bool success_ = false;
  const bool async_;
  SkBitmap bitmap_;
};

class BitmapFetcherBrowserTest : public InProcessBrowserTest {
 public:
  // InProcessBrowserTest overrides:
  void SetUpOnMainThread() override {
    InProcessBrowserTest::SetUpOnMainThread();

    // Set up the test server.
    embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
        &BitmapFetcherBrowserTest::HandleRequest, base::Unretained(this)));
    ASSERT_TRUE(embedded_test_server()->Start());
  }

  void TearDownOnMainThread() override {
    // Tear down the test server.
    EXPECT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
    InProcessBrowserTest::TearDownOnMainThread();
  }

 protected:
  SkBitmap test_bitmap() const {
    // Return some realistic looking bitmap data
    SkBitmap image;

    // Put a real bitmap into "image".  2x2 bitmap of green 32 bit pixels.
    image.allocN32Pixels(2, 2);
    image.eraseColor(SK_ColorGREEN);
    return image;
  }

 private:
  std::unique_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
    std::unique_ptr<BasicHttpResponse> response(new BasicHttpResponse);
    if (request.relative_url == kStartTestURL) {
      // Encode the bits as a PNG.
      std::optional<std::vector<uint8_t>> compressed =
          gfx::PNGCodec::EncodeBGRASkBitmap(test_bitmap(),
                                            /*discard_transparency=*/true);
      // Copy the bits into a string and return them through the embedded
      // test server.
      std::string image_string(base::as_string_view(compressed.value()));
      response->set_code(net::HTTP_OK);
      response->set_content(image_string);
    } else if (request.relative_url == kOnImageDecodedTestURL) {
      response->set_code(net::HTTP_INTERNAL_SERVER_ERROR);
    } else if (request.relative_url == kOnURLFetchFailureTestURL) {
      response->set_code(net::HTTP_OK);
      response->set_content(std::string("Not a real bitmap"));
    }
    return std::move(response);
  }
};

// WARNING:  These tests work with --single-process-tests, but not
// --single-process.  The reason is that the sandbox does not get created
// for us by the test process if --single-process is used.

IN_PROC_BROWSER_TEST_F(BitmapFetcherBrowserTest, StartTest) {
  GURL url = embedded_test_server()->GetURL(kStartTestURL);

  // Set up a delegate to wait for the callback.
  BitmapFetcherTestDelegate delegate(kAsyncCall);

  BitmapFetcher fetcher(url, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);

  // We expect that the image decoder will get called and return
  // an image in a callback to OnImageDecoded().
  fetcher.Init(
      net::ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
      network::mojom::CredentialsMode::kOmit);
  fetcher.Start(browser()
                    ->profile()
                    ->GetDefaultStoragePartition()
                    ->GetURLLoaderFactoryForBrowserProcess()
                    .get());

  // Blocks until test delegate is notified via a callback.
  delegate.Wait();

  ASSERT_TRUE(delegate.success());

  // Make sure we get back the bitmap we expect.
  const SkBitmap& found_image = delegate.bitmap();
  EXPECT_TRUE(gfx::BitmapsAreEqual(test_bitmap(), found_image));
}

IN_PROC_BROWSER_TEST_F(BitmapFetcherBrowserTest, OnImageDecodedTest) {
  GURL url = embedded_test_server()->GetURL(kOnImageDecodedTestURL);
  SkBitmap image = test_bitmap();

  BitmapFetcherTestDelegate delegate(kSyncCall);

  BitmapFetcher fetcher(url, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);

  fetcher.OnImageDecoded(image);

  // Ensure image is marked as succeeded.
  EXPECT_TRUE(delegate.success());

  // Test that the image is what we expect.
  EXPECT_TRUE(gfx::BitmapsAreEqual(image, delegate.bitmap()));
}

IN_PROC_BROWSER_TEST_F(BitmapFetcherBrowserTest, OnURLFetchFailureTest) {
  GURL url = embedded_test_server()->GetURL(kOnURLFetchFailureTestURL);

  // We intentionally put no data into the bitmap to simulate a failure.

  // Set up a delegate to wait for the callback.
  BitmapFetcherTestDelegate delegate(kAsyncCall);

  BitmapFetcher fetcher(url, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);

  fetcher.Init(
      net::ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
      network::mojom::CredentialsMode::kOmit);
  fetcher.Start(browser()
                    ->profile()
                    ->GetDefaultStoragePartition()
                    ->GetURLLoaderFactoryForBrowserProcess()
                    .get());

  // Blocks until test delegate is notified via a callback.
  delegate.Wait();

  EXPECT_FALSE(delegate.success());
}

IN_PROC_BROWSER_TEST_F(BitmapFetcherBrowserTest, HandleImageFailedTest) {
  GURL url("http://example.com/this-should-be-a-decode-failure");
  BitmapFetcherTestDelegate delegate(kAsyncCall);
  BitmapFetcher fetcher(url, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);

  fetcher.Init(
      net::ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
      network::mojom::CredentialsMode::kOmit);
  fetcher.Start(browser()
                    ->profile()
                    ->GetDefaultStoragePartition()
                    ->GetURLLoaderFactoryForBrowserProcess()
                    .get());

  // Blocks until test delegate is notified via a callback.
  delegate.Wait();

  EXPECT_FALSE(delegate.success());
}

IN_PROC_BROWSER_TEST_F(BitmapFetcherBrowserTest, DataURLNonImage) {
  GURL url("data:,Hello");
  BitmapFetcherTestDelegate delegate(kAsyncCall);
  BitmapFetcher fetcher(url, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);

  fetcher.Init(
      net::ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
      network::mojom::CredentialsMode::kOmit);
  fetcher.Start(browser()
                    ->profile()
                    ->GetDefaultStoragePartition()
                    ->GetURLLoaderFactoryForBrowserProcess()
                    .get());
  delegate.Wait();

  EXPECT_FALSE(delegate.success());
}

IN_PROC_BROWSER_TEST_F(BitmapFetcherBrowserTest, DataURLImage) {
  // This is test_bitmap() in data: URL form.
  GURL url(
      "data:image/"
      "png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFElEQVQYlWNk+"
      "M/wn4GBgYGJAQoAHhgCAh6X4CYAAAAASUVORK5CYII=");

  BitmapFetcherTestDelegate delegate(kAsyncCall);
  BitmapFetcher fetcher(url, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);

  fetcher.Init(
      net::ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
      network::mojom::CredentialsMode::kOmit);
  fetcher.Start(browser()
                    ->profile()
                    ->GetDefaultStoragePartition()
                    ->GetURLLoaderFactoryForBrowserProcess()
                    .get());
  delegate.Wait();

  // Ensure image is marked as succeeded.
  EXPECT_TRUE(delegate.success());
  EXPECT_TRUE(gfx::BitmapsAreEqual(test_bitmap(), delegate.bitmap()));
}

// Verifies that bitmap fetch callback gets canceled gracefully when the fetcher
// gets deleted.
IN_PROC_BROWSER_TEST_F(BitmapFetcherBrowserTest,
                       FetcherDeletedBeforeDataURLImageResponse) {
  // This is test_bitmap() in data: URL form.
  GURL url(
      "data:image/"
      "png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFElEQVQYlWNk+"
      "M/wn4GBgYGJAQoAHhgCAh6X4CYAAAAASUVORK5CYII=");

  BitmapFetcherTestDelegate delegate(kAsyncCall);
  delegate.SetExpectNotToGetCalled();
  {
    BitmapFetcher fetcher(url, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);

    fetcher.Init(
        net::ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
        network::mojom::CredentialsMode::kOmit);
    fetcher.Start(browser()
                      ->profile()
                      ->GetDefaultStoragePartition()
                      ->GetURLLoaderFactoryForBrowserProcess()
                      .get());
  }

  EXPECT_FALSE(delegate.success());
}

class BitmapFetcherInitiatorBrowserTest : public InProcessBrowserTest {
 public:
  // InProcessBrowserTest:
  void SetUpOnMainThread() override {
    InProcessBrowserTest::SetUpOnMainThread();

    // Set up the test server.
    embedded_test_server()->RegisterRequestHandler(
        base::BindRepeating(&BitmapFetcherInitiatorBrowserTest::HandleRequest,
                            base::Unretained(this)));
    ASSERT_TRUE(embedded_test_server()->Start());
  }

  void TearDownOnMainThread() override {
    // Tear down the test server.
    EXPECT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
    InProcessBrowserTest::TearDownOnMainThread();
  }

  const std::string& all_headers() const { return all_headers_; }

 private:
  std::unique_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
    all_headers_ = request.all_headers;
    std::unique_ptr<BasicHttpResponse> response(new BasicHttpResponse);
    response->set_code(net::HTTP_OK);
    return response;
  }

  std::string all_headers_;
};

IN_PROC_BROWSER_TEST_F(BitmapFetcherInitiatorBrowserTest, SameOrigin) {
  GURL image_url = embedded_test_server()->GetURL(kStartTestURL);

  BitmapFetcherTestDelegate delegate(kAsyncCall);
  BitmapFetcher fetcher(image_url, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);

  fetcher.Init(net::ReferrerPolicy::NEVER_CLEAR,
               network::mojom::CredentialsMode::kOmit,
               net::HttpRequestHeaders(),
               /*initiator=*/url::Origin::Create(image_url));
  fetcher.Start(browser()
                    ->profile()
                    ->GetDefaultStoragePartition()
                    ->GetURLLoaderFactoryForBrowserProcess()
                    .get());
  delegate.Wait();

  EXPECT_THAT(all_headers(), testing::HasSubstr("Sec-Fetch-Site: same-origin"));
}