File: content_script_matching_browsertest.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 (410 lines) | stat: -rw-r--r-- 15,430 bytes parent folder | download | duplicates (9)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/memory/raw_ptr.h"
#include "extensions/browser/script_injection_tracker.h"

#include "base/strings/stringprintf.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/common/extension.h"
#include "extensions/shell/browser/shell_extension_loader.h"
#include "extensions/shell/test/shell_apitest.h"
#include "extensions/test/test_extension_dir.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace extensions {

// Test suite covering
// `extensions::ScriptInjectionTracker::DoStaticContentScriptsMatchForTesting`
// from //extensions/browser/script_injection_tracker.h.
//
// See also ScriptInjectionTrackerBrowserTest in
// //chrome/browser/extensions/script_injection_tracker_browsertest.cc.
// TODO(crbug.com/40061759): Add test coverage for dynamic content and user
// scripts matching.
class ContentScriptMatchingBrowserTest : public ShellApiTest,
                                         public content::WebContentsDelegate {
 public:
  ContentScriptMatchingBrowserTest() = default;

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

  ~ContentScriptMatchingBrowserTest() override = default;

  void SetUpOnMainThread() override {
    ShellApiTest::SetUpOnMainThread();

    host_resolver()->AddRule("*", "127.0.0.1");
    ASSERT_TRUE(embedded_test_server()->Start());
  }

  void TearDownOnMainThread() override {
    tab1_.reset();
    tab2_.reset();
    ShellApiTest::TearDownOnMainThread();
  }

  const Extension* InstallContentScriptsExtension(
      const std::string& content_scripts_manifest_declaration) {
    const char kManifestTemplate[] = R"(
        {
          "name": "ContentScriptsTest",
          "version": "1.0",
          "manifest_version": 2,
          %s
        } )";
    dir_.WriteManifest(base::StringPrintf(
        kManifestTemplate, content_scripts_manifest_declaration.c_str()));
    dir_.WriteFile(FILE_PATH_LITERAL("content_script.css"), "");
    dir_.WriteFile(FILE_PATH_LITERAL("content_script.js"), "");

    ShellExtensionLoader loader(browser_context());
    {
      base::ScopedAllowBlockingForTesting allow_blocking;
      extension_ = loader.LoadExtension(dir_.UnpackedPath());
    }
    return extension_;
  }

  // Returns whether the class-under-test (ScriptInjectionTracker) thinks that
  // the test extension (installed by individual test cases via
  // InstallContentScriptsExtension) may inject content scripts into the
  // foo_frame frame in tab1 (see SetUpFrameTree for a list of available test
  // frames).
  //
  // The optional |url| argument may be used to simulate a ready-to-commit
  // scenario where the frame's last committed URL may differ from the |url|
  // that a pending navigation is ready to commit.
  bool DoContentScriptsMatch_Tab1_FooFrame(GURL url = GURL("http://foo.com")) {
    return DoContentScriptsMatch(tab1_fooFrame(), url);
  }

  // Like DoContentScriptsMatch_Tab1_FooFrame, but for foo_about_blank_frame.
  bool DoContentScriptsMatch_Tab1_FooBlankFrame(
      GURL url = GURL(url::kAboutBlankURL)) {
    return DoContentScriptsMatch(tab1_fooBlankFrame(), url);
  }

  // Like DoContentScriptsMatch_Tab1_FooFrame, but for bar_frame.
  bool DoContentScriptsMatch_Tab1_BarFrame(GURL url = GURL("http://bar.com")) {
    return DoContentScriptsMatch(tab1_barFrame(), url);
  }

  // Like DoContentScriptsMatch_Tab1_FooFrame, but for bar_about_blank_frame.
  bool DoContentScriptsMatch_Tab1_BarBlankFrame(
      GURL url = GURL(url::kAboutBlankURL)) {
    return DoContentScriptsMatch(tab1_barBlankFrame(), url);
  }

  // Like DoContentScriptsMatch_Tab1_FooFrame, but for bar_about_blank_frame1 in
  // tab2.
  bool DoContentScriptsMatch_Tab2_BarBlankFrame1(
      GURL url = GURL(url::kAboutBlankURL)) {
    return DoContentScriptsMatch(tab2_barBlankFrame1(), url);
  }

  // Like DoContentScriptsMatch_Tab1_FooFrame, but for bar_about_blank_frame2 in
  // tab2.
  bool DoContentScriptsMatch_Tab2_BarBlankFrame2(
      GURL url = GURL(url::kAboutBlankURL)) {
    return DoContentScriptsMatch(tab2_barBlankFrame2(), url);
  }

  // SetUpFrameTree sets up the following frame tree(s) that are used by all the
  // ContentScriptMatchingBrowserTest.ContentScriptMatching_* tests.
  //
  // tab1_:
  //   foo_frame
  //   +-foo_about_blank_frame
  //   +-bar_frame
  //     +-bar_about_blank_frame <---\
  //                                 |
  // tab2_:                          |^opener
  //   bar_about_blank_frame1--------/
  //   +-bar_about_blank_frame2
  void SetUpFrameTree() {
    GURL foo_url = embedded_test_server()->GetURL("foo.com", "/empty.html");
    GURL bar_url = embedded_test_server()->GetURL("bar.com", "/empty.html");
    GURL blank_url = GURL(url::kAboutBlankURL);
    url::Origin foo_origin = url::Origin::Create(foo_url);
    url::Origin bar_origin = url::Origin::Create(bar_url);

    tab1_ = content::WebContents::Create(
        content::WebContents::CreateParams(browser_context()));
    tab1_->SetDelegate(this);
    ASSERT_TRUE(content::NavigateToURL(tab1_.get(), foo_url));

    AddFrame(tab1_fooFrame(), "fooBlankFrame");

    AddFrame(tab1_fooFrame(), "barFrame");
    ASSERT_TRUE(NavigateIframeToURL(tab1_.get(), "barFrame", bar_url));

    AddFrame(tab1_barFrame(), "barBlankFrame");

    content::WebContentsAddedObserver new_tab_observer;
    ASSERT_TRUE(content::ExecJs(tab1_barBlankFrame(),
                                "window.open('', 'barBlankFrame1');"));
    new_tab_observer.GetWebContents();

    AddFrame(tab2_barBlankFrame1(), "barBlankFrame2");

    EXPECT_EQ(foo_origin, tab1_fooFrame()->GetLastCommittedOrigin());
    EXPECT_EQ(foo_origin, tab1_fooBlankFrame()->GetLastCommittedOrigin());
    EXPECT_EQ(bar_origin, tab1_barFrame()->GetLastCommittedOrigin());
    EXPECT_EQ(bar_origin, tab1_barBlankFrame()->GetLastCommittedOrigin());
    EXPECT_EQ(bar_origin, tab2_barBlankFrame1()->GetLastCommittedOrigin());
    EXPECT_EQ(bar_origin, tab2_barBlankFrame2()->GetLastCommittedOrigin());

    EXPECT_EQ(foo_url, tab1_fooFrame()->GetLastCommittedURL());
    EXPECT_EQ(blank_url, tab1_fooBlankFrame()->GetLastCommittedURL());
    EXPECT_EQ(bar_url, tab1_barFrame()->GetLastCommittedURL());
    EXPECT_EQ(blank_url, tab1_barBlankFrame()->GetLastCommittedURL());
    EXPECT_EQ(blank_url, tab2_barBlankFrame1()->GetLastCommittedURL());
    EXPECT_EQ(blank_url, tab2_barBlankFrame2()->GetLastCommittedURL());
  }

 private:
  // WebContentsDelegate overrides:
  content::WebContents* AddNewContents(
      content::WebContents* source,
      std::unique_ptr<content::WebContents> new_contents,
      const GURL& target_url,
      WindowOpenDisposition disposition,
      const blink::mojom::WindowFeatures& window_features,
      bool user_gesture,
      bool* was_blocked) override {
    DCHECK_EQ(tab1_.get(), source);
    DCHECK(new_contents);
    tab2_ = std::move(new_contents);
    return nullptr;
  }

  bool DoContentScriptsMatch(content::RenderFrameHost* navigating_frame,
                             const GURL& navigation_target) {
    return ScriptInjectionTracker::DoStaticContentScriptsMatchForTesting(
        *extension_, navigating_frame, navigation_target);
  }

  void AddFrame(content::RenderFrameHost* parent,
                const std::string& subframe_id) {
    const char* kScriptTemplate = R"(
            var bar_frame = document.createElement('iframe');
            bar_frame.id = $1;
            document.body.appendChild(bar_frame);
        )";
    ASSERT_TRUE(content::ExecJs(
        parent, content::JsReplace(kScriptTemplate, subframe_id)));
  }

  content::RenderFrameHost* tab1_fooFrame() {
    EXPECT_TRUE(tab1_);
    return tab1_->GetPrimaryMainFrame();
  }

  content::RenderFrameHost* tab1_fooBlankFrame() {
    EXPECT_TRUE(tab1_);
    content::RenderFrameHost* child = ChildFrameAt(tab1_fooFrame(), 0);
    EXPECT_TRUE(child);
    return child;
  }

  content::RenderFrameHost* tab1_barFrame() {
    EXPECT_TRUE(tab1_);
    content::RenderFrameHost* child = ChildFrameAt(tab1_fooFrame(), 1);
    EXPECT_TRUE(child);
    return child;
  }

  content::RenderFrameHost* tab1_barBlankFrame() {
    EXPECT_TRUE(tab1_);
    content::RenderFrameHost* child = ChildFrameAt(tab1_barFrame(), 0);
    EXPECT_TRUE(child);
    return child;
  }

  content::RenderFrameHost* tab2_barBlankFrame1() {
    EXPECT_TRUE(tab2_);
    return tab2_->GetPrimaryMainFrame();
  }

  content::RenderFrameHost* tab2_barBlankFrame2() {
    EXPECT_TRUE(tab2_);
    content::RenderFrameHost* child = ChildFrameAt(tab2_barBlankFrame1(), 0);
    EXPECT_TRUE(child);
    return child;
  }

  // Populated by SetUpFrameTree (during test setup / in SetUpOnMainThread).
  std::unique_ptr<content::WebContents> tab1_;
  std::unique_ptr<content::WebContents> tab2_;

  // Populated by InstallContentScriptsExtension (called by individual tests).
  TestExtensionDir dir_;
  raw_ptr<const Extension, DanglingUntriaged> extension_ = nullptr;
};

IN_PROC_BROWSER_TEST_F(ContentScriptMatchingBrowserTest,
                       ContentScriptMatching_ChainTraversalForBar) {
  SetUpFrameTree();
  ASSERT_FALSE(::testing::Test::HasFailure());

  const Extension* extension = InstallContentScriptsExtension(R"(
      "content_scripts": [{
        "all_frames": true,
        "match_about_blank": true,
        "matches": ["http://bar.com/*"],
        "js": ["content_script.js"]
      }] )");
  ASSERT_TRUE(extension);

  // Matching should consider parent/opener chain.
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_FooFrame());
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_FooBlankFrame());
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_BarFrame());
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_BarBlankFrame());
  EXPECT_TRUE(DoContentScriptsMatch_Tab2_BarBlankFrame1());
  EXPECT_TRUE(DoContentScriptsMatch_Tab2_BarBlankFrame2());
}

IN_PROC_BROWSER_TEST_F(ContentScriptMatchingBrowserTest,
                       ContentScriptMatching_ChainTraversalForFoo) {
  SetUpFrameTree();
  ASSERT_FALSE(::testing::Test::HasFailure());

  const Extension* extension = InstallContentScriptsExtension(R"(
      "content_scripts": [{
        "all_frames": true,
        "match_about_blank": true,
        "matches": ["http://foo.com/*"],
        "js": ["content_script.js"]
      }] )");
  ASSERT_TRUE(extension);

  // Matching should consider parent/opener chain.
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_FooFrame());
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_FooBlankFrame());
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_BarFrame());
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_BarBlankFrame());
  EXPECT_FALSE(DoContentScriptsMatch_Tab2_BarBlankFrame1());
  EXPECT_FALSE(DoContentScriptsMatch_Tab2_BarBlankFrame2());
}

IN_PROC_BROWSER_TEST_F(ContentScriptMatchingBrowserTest,
                       ContentScriptMatching_NoMatchingOfAboutBlank) {
  SetUpFrameTree();
  ASSERT_FALSE(::testing::Test::HasFailure());

  const Extension* extension = InstallContentScriptsExtension(R"(
      "content_scripts": [{
        "all_frames": true,
        "match_about_blank": false,
        "matches": ["http://bar.com/*"],
        "js": ["content_script.js"]
      }] )");
  ASSERT_TRUE(extension);

  // In absence of "match_about_blank", parent/opener chain should not be
  // considered (and matching against about:blank should fail).
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_FooFrame());
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_FooBlankFrame());
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_BarFrame());
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_BarBlankFrame());
  EXPECT_FALSE(DoContentScriptsMatch_Tab2_BarBlankFrame1());
  EXPECT_FALSE(DoContentScriptsMatch_Tab2_BarBlankFrame2());
}

// Flaky on MacOS since r622662. See https://crbug.com/921883
#if BUILDFLAG(IS_MAC)
#define MAYBE_ContentScriptMatching_NotAllFrames \
  DISABLED_ContentScriptMatching_NotAllFrames
#else
#define MAYBE_ContentScriptMatching_NotAllFrames \
  ContentScriptMatching_NotAllFrames
#endif
IN_PROC_BROWSER_TEST_F(ContentScriptMatchingBrowserTest,
                       MAYBE_ContentScriptMatching_NotAllFrames) {
  SetUpFrameTree();
  ASSERT_FALSE(::testing::Test::HasFailure());

  const Extension* extension = InstallContentScriptsExtension(R"(
      "content_scripts": [{
        "all_frames": false,
        "match_about_blank": true,
        "matches": ["http://foo.com/*", "http://bar.com/*"],
        "js": ["content_script.js"]
      }] )");
  ASSERT_TRUE(extension);

  // Main frame should be matched.
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_FooFrame());

  // Based on the `all_frames` from the manifest the subframe should not be
  // matched (even though the patterns in the manifest do match bar.com).  OTOH,
  // the URL Pattern matching in ScriptInjectionTracker ignroes `all_frames` and
  // accepts additional false positives to solve extra corner cases.
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_BarFrame());
}

IN_PROC_BROWSER_TEST_F(ContentScriptMatchingBrowserTest,
                       ContentScriptMatching_NotYetCommittedURL) {
  SetUpFrameTree();
  ASSERT_FALSE(::testing::Test::HasFailure());

  const Extension* extension = InstallContentScriptsExtension(R"(
      "content_scripts": [{
        "all_frames": true,
        "match_about_blank": true,
        "matches": ["http://matching.com/*"],
        "js": ["content_script.js"]
      }] )");
  ASSERT_TRUE(extension);

  // Content scripts should match, even though baz.com has not yet committed in
  // the frames (i.e. GetLastCommittedOrigin() in the frames is different -
  // either foo.com or bar.com).
  GURL matching_url("http://matching.com");
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_FooFrame(matching_url));
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_BarFrame(matching_url));
  EXPECT_TRUE(DoContentScriptsMatch_Tab1_FooBlankFrame(matching_url));

  // Content scripts should not match, since other.com is not covered by the
  // extension manifest.
  GURL other_url("http://other.com");
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_FooFrame(other_url));
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_BarFrame(other_url));
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_FooBlankFrame(other_url));
}

IN_PROC_BROWSER_TEST_F(ContentScriptMatchingBrowserTest,
                       ContentScriptMatching_CssIsIgnored) {
  SetUpFrameTree();
  ASSERT_FALSE(::testing::Test::HasFailure());

  const Extension* extension = InstallContentScriptsExtension(R"(
      "content_scripts": [{
        "all_frames": true,
        "match_about_blank": false,
        "matches": ["http://bar.com/*"],
        "css": ["content_script.css"]
      }] )");
  ASSERT_TRUE(extension);

  // Only Javascript should result in a match.
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_FooFrame());
  EXPECT_FALSE(DoContentScriptsMatch_Tab1_BarFrame());
}

}  // namespace extensions