File: content_security_policy_apitest.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 (261 lines) | stat: -rw-r--r-- 9,968 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
// Copyright 2011 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/strings/stringprintf.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/common/extension.h"
#include "extensions/test/result_catcher.h"
#include "extensions/test/test_extension_dir.h"
#include "net/dns/mock_host_resolver.h"

#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/ui_test_utils.h"
#endif

namespace extensions {

using ExtensionCspApiTest = ExtensionApiTest;

IN_PROC_BROWSER_TEST_F(ExtensionCspApiTest, ContentSecurityPolicy) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(RunExtensionTest("content_security_policy")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionCspApiTest, DefaultContentSecurityPolicy) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(RunExtensionTest("default_content_security_policy")) <<
      message_;
}

// Tests that the Manifest V3 extension CSP allows localhost sources to be
// embedded in extension pages.
IN_PROC_BROWSER_TEST_F(ExtensionCspApiTest,
                       ManifestV3AllowsLocalhostInPagesForUnpackedExtensions) {
  ASSERT_TRUE(StartEmbeddedTestServer());

  static constexpr char kManifest[] =
      R"({
           "name": "manifest v3 allows localhost and 127.0.0.1",
           "version": "0.1",
           "manifest_version": 3,
           "content_security_policy": {
             "extension_pages":
                 "script-src 'self' http://localhost:* http://127.0.0.1:*;"
           }
         })";
  static constexpr char kPageHtmlTemplate[] =
      R"(<html>
           <script src="http://localhost:%d/extensions/local_includes/pass1.js">
           </script>
           <script src="http://127.0.0.1:%d/extensions/local_includes/pass2.js">
           </script>
           <script src="page.js"></script>
         </html>)";
  // Note that `jsPass1()` and `jsPass2()` are defined in the pass1.js and
  // pass2.js resources that are included; they each call chrome.test.succeed().
  static constexpr char kPageJs[] =
      R"(chrome.test.runTests([
           function testLocalHostInclude() {
             window.jsPass1();
           },
           function testLocalHostIPInclude() {
             window.jsPass2();
           }]);)";

  TestExtensionDir test_dir;
  test_dir.WriteManifest(kManifest);
  test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), kPageJs);
  test_dir.WriteFile(
      FILE_PATH_LITERAL("page.html"),
      base::StringPrintf(kPageHtmlTemplate, embedded_test_server()->port(),
                         embedded_test_server()->port()));

  ASSERT_TRUE(RunExtensionTest(test_dir.UnpackedPath(),
                               {.extension_url = "page.html"}, {}))
      << message_;
}

// Tests that the Manifest V3 extension CSP allows for localhost sources being
// imported from service workers.
IN_PROC_BROWSER_TEST_F(
    ExtensionCspApiTest,
    ManifestV3AllowsLocalhostInServiceWorkersForUnpackedExtensions) {
  ASSERT_TRUE(StartEmbeddedTestServer());

  static constexpr char kManifest[] =
      R"({
           "name": "manifest v3 allows localhost and 127.0.0.1",
           "version": "0.1",
           "manifest_version": 3,
           "content_security_policy": {
             "extension_pages":
                 "script-src 'self' http://localhost:* http://127.0.0.1:*; object-src 'self'"
           },
           "background": {"service_worker": "background.js", "type": "module"}
         })";
  static constexpr char kBackgroundJs[] =
      R"(import {jsPass1} from
             'http://localhost:%d/extensions/local_includes/module_pass1.js';
         import {jsPass2} from
             'http://localhost:%d/extensions/local_includes/module_pass2.js';
         chrome.test.runTests([
             function testLocalHostInclude() {
               jsPass1();
             },
             function testLocalHostIPInclude() {
               jsPass2();
             }]);)";

  TestExtensionDir test_dir;
  test_dir.WriteManifest(kManifest);
  test_dir.WriteFile(
      FILE_PATH_LITERAL("background.js"),
      base::StringPrintf(kBackgroundJs, embedded_test_server()->port(),
                         embedded_test_server()->port()));

  ASSERT_TRUE(RunExtensionTest(test_dir.UnpackedPath(), {}, {})) << message_;
}

#if !BUILDFLAG(IS_ANDROID)
// Tests that MV3 disallows localhost in packed extensions.
// TODO(https://crbug.com/391924202): Enable on Android once packed extensions
// are supported.
IN_PROC_BROWSER_TEST_F(ExtensionCspApiTest,
                       ManifestV3DisallowsLocalhostForPackedExtensions) {
  ASSERT_TRUE(StartEmbeddedTestServer());

  static constexpr char kManifest[] =
      R"({
           "name": "manifest v3 allows localhost and 127.0.0.1",
           "version": "0.1",
           "manifest_version": 3,
           "content_security_policy": {
             "extension_pages":
                 "script-src 'self' http://localhost:* http://127.0.0.1:*; object-src 'self'"
           }
         })";

  static constexpr char kPageHtmlTemplate[] =
      R"(<html>
           <script src="http://localhost:%d/extensions/local_includes/pass1.js">
           </script>
           <script src="http://127.0.0.1:%d/extensions/local_includes/pass2.js">
           </script>
           <script src="page.js"></script>
         </html>)";
  // Note that `jsPass1()` and `jsPass2()` are defined in the pass1.js and
  // pass2.js resources that are included. However, since the scripts should be
  // blocked by CSP, the variables should be undefined.
  static constexpr char kPageJs[] =
      R"(chrome.test.runTests([
           function testLocalHostInclude() {
             chrome.test.assertTrue(!window.jsPass1);
             chrome.test.succeed();
           },
           function testLocalHostIPInclude() {
             chrome.test.assertTrue(!window.jsPass2);
             chrome.test.succeed();
           }]);)";

  TestExtensionDir test_dir;
  test_dir.WriteManifest(kManifest);
  test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), kPageJs);
  test_dir.WriteFile(
      FILE_PATH_LITERAL("page.html"),
      base::StringPrintf(kPageHtmlTemplate, embedded_test_server()->port(),
                         embedded_test_server()->port()));

  ResultCatcher result_catcher;
  ChromeTestExtensionLoader test_loader(profile());
  test_loader.set_pack_extension(true);
  scoped_refptr<const Extension> extension =
      test_loader.LoadExtension(test_dir.UnpackedPath());
  ASSERT_TRUE(extension);
  ASSERT_FALSE(Manifest::IsUnpackedLocation(extension->location()));

  // Blocking the script load should emit a log.
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  content::WebContentsConsoleObserver console_observer(web_contents);
  console_observer.SetPattern("Refused to load the script '*");

  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), extension->ResolveExtensionURL("page.html")));
  ASSERT_TRUE(result_catcher.GetNextResult()) << result_catcher.message();

  EXPECT_EQ(2u, console_observer.messages().size());
}
#endif  // !BUILDFLAG(IS_ANDROID)

// A simple subclass that also sets up page navigation with the host resolver.
class ExtensionCspApiTestWithPageNavigation : public ExtensionCspApiTest {
 public:
  ExtensionCspApiTestWithPageNavigation() = default;
  ~ExtensionCspApiTestWithPageNavigation() override = default;

  void SetUpOnMainThread() override {
    ExtensionCspApiTest::SetUpOnMainThread();
    host_resolver()->AddRule("*", "127.0.0.1");
    ASSERT_TRUE(StartEmbeddedTestServer());
  }
};

// Exercises importing resources exposed in web-accessible resources with
// dynamic URLs in content scripts.
// Regression test for https://crbug.com/363027634.
IN_PROC_BROWSER_TEST_F(ExtensionCspApiTestWithPageNavigation,
                       ContentScriptsCanImportDynamicUrlResources) {
  static constexpr char kManifest[] =
      R"({
           "name": "Test Extension",
           "manifest_version": 3,
           "version": "0.1",
           "web_accessible_resources": [{
             "resources": ["accessible_resource.js"],
             "matches": ["http://example.com/*"],
             "use_dynamic_url": true
           }],
           "content_scripts": [{
             "matches": ["http://example.com/*"],
             "js": ["content_script.js"]
           }]
         })";
  // The content script attempts to import() a resource that's exposed in
  // web-accessible resources using the extension's dynamic URL. This resource
  // then exposes a `passTest()` function, which will pass the test.
  static constexpr char kContentScriptJs[] =
      R"((async () => {
           try {
             const url = chrome.runtime.getURL('./accessible_resource.js');
             const mod = await import(url);
             mod.passTest();
           } catch(e) {
             chrome.test.notifyFail('Failed to import: ' + e.toString());
           }
         })();)";
  static constexpr char kAccessibleResourceJs[] =
      R"(export function passTest() {
           chrome.test.notifyPass();
         })";

  TestExtensionDir test_dir;
  test_dir.WriteManifest(kManifest);
  test_dir.WriteFile(FILE_PATH_LITERAL("content_script.js"), kContentScriptJs);
  test_dir.WriteFile(FILE_PATH_LITERAL("accessible_resource.js"),
                     kAccessibleResourceJs);

  const GURL url =
      embedded_test_server()->GetURL("example.com", "/simple.html");
  ASSERT_TRUE(RunExtensionTest(test_dir.UnpackedPath(),
                               {.page_url = url.spec().c_str()}, {}))
      << message_;
}

}  // namespace extensions