File: extension_unload_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 (258 lines) | stat: -rw-r--r-- 9,955 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
// Copyright 2016 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/feature_list.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/no_renderer_crashes_assertion.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.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 "services/network/public/cpp/features.h"
#include "ui/base/window_open_disposition.h"
#include "url/origin.h"
#include "url/url_constants.h"

namespace extensions {

namespace {

// A helper class to wait for a particular tab count. Requires the tab strip
// to outlive this object.
class TestTabStripModelObserver : public TabStripModelObserver {
 public:
  explicit TestTabStripModelObserver(TabStripModel* model)
      : model_(model), desired_count_(0) {
    model->AddObserver(this);
  }

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

  ~TestTabStripModelObserver() override = default;

  void WaitForTabCount(int count) {
    if (model_->count() == count)
      return;
    desired_count_ = count;
    run_loop_.Run();
  }

 private:
  // TabStripModelObserver:
  void OnTabStripModelChanged(
      TabStripModel* tab_strip_model,
      const TabStripModelChange& change,
      const TabStripSelectionChange& selection) override {
    if (model_->count() == desired_count_)
      run_loop_.Quit();
  }

  raw_ptr<TabStripModel> model_;
  int desired_count_;
  base::RunLoop run_loop_;
};

}  // namespace

class ExtensionUnloadBrowserTest : public ExtensionBrowserTest {
 public:
  void SetUpOnMainThread() override {
    ExtensionBrowserTest::SetUpOnMainThread();
    host_resolver()->AddRule("maps.google.com", "127.0.0.1");
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionUnloadBrowserTest, TestUnload) {
  // Load an extension that installs unload and beforeunload listeners.
  const Extension* extension =
      LoadExtension(test_data_dir_.AppendASCII("unload_listener"));
  ASSERT_TRUE(extension);
  std::string id = extension->id();
  ASSERT_EQ(1, browser()->tab_strip_model()->count());
  GURL initial_tab_url =
      browser()->tab_strip_model()->GetWebContentsAt(0)->GetLastCommittedURL();
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), extension->ResolveExtensionURL("page.html"),
      WindowOpenDisposition::NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  EXPECT_EQ(2, browser()->tab_strip_model()->count());
  DisableExtension(id);
  // There should only be one remaining web contents - the initial one.
  ASSERT_EQ(1, browser()->tab_strip_model()->count());
  EXPECT_EQ(
      initial_tab_url,
      browser()->tab_strip_model()->GetWebContentsAt(0)->GetLastCommittedURL());
}

// After an extension is uninstalled, network requests from its content scripts
// should fail but not kill the renderer process.
IN_PROC_BROWSER_TEST_F(ExtensionUnloadBrowserTest, UnloadWithContentScripts) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Load an extension with a content script that has a button to send XHRs.
  const Extension* extension =
      LoadExtension(test_data_dir_.AppendASCII("xhr_from_content_script"));
  ASSERT_TRUE(extension);
  std::string id = extension->id();
  ASSERT_EQ(1, browser()->tab_strip_model()->count());
  GURL test_url = embedded_test_server()->GetURL("/title1.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url));

  // The content script sends an XHR with the webpage's (rather than
  // extension's) Origin header - this should succeed (given that
  // xhr.txt.mock-http-headers says `Access-Control-Allow-Origin: *`).
  const char kSendXhrScript[] = "document.getElementById('xhrButton').click();";
  content::DOMMessageQueue message_queue;
  EXPECT_TRUE(content::ExecJs(
      browser()->tab_strip_model()->GetActiveWebContents(), kSendXhrScript));
  std::string ack;
  EXPECT_TRUE(message_queue.WaitForMessage(&ack));
  EXPECT_EQ("true", ack);

  DisableExtension(id);

  // The tab should still be open with the content script injected.
  ASSERT_EQ(1, browser()->tab_strip_model()->count());
  EXPECT_EQ(
      test_url,
      browser()->tab_strip_model()->GetWebContentsAt(0)->GetLastCommittedURL());

  // The content script sends an XHR with the webpage's (rather than
  // extension's) Origin header - this should succeed (given that
  // xhr.txt.mock-http-headers says `Access-Control-Allow-Origin: *`).
  EXPECT_TRUE(content::ExecJs(
      browser()->tab_strip_model()->GetActiveWebContents(), kSendXhrScript));
  EXPECT_TRUE(message_queue.WaitForMessage(&ack));
  EXPECT_EQ("true", ack);

  // Ensure the process has not been killed.
  EXPECT_TRUE(browser()
                  ->tab_strip_model()
                  ->GetActiveWebContents()
                  ->GetPrimaryMainFrame()
                  ->IsRenderFrameLive());
}

// Tests that windows with opaque origins opened by the extension are closed
// when the extension is unloaded. Regression test for https://crbug.com/894477.
IN_PROC_BROWSER_TEST_F(ExtensionUnloadBrowserTest, OpenedOpaqueWindows) {
  TestExtensionDir test_dir;
  constexpr char kManifest[] =
      R"({
           "name": "Test",
           "manifest_version": 2,
           "version": "0.1",
           "background": {
             "scripts": ["background.js"]
           }
         })";
  test_dir.WriteManifest(kManifest);
  test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
                     "window.open('about:blank');");

  const GURL about_blank(url::kAboutBlankURL);
  content::TestNavigationObserver about_blank_observer(about_blank);
  about_blank_observer.StartWatchingNewWebContents();
  const Extension* extension = LoadExtension(test_dir.UnpackedPath());
  ASSERT_TRUE(extension);
  about_blank_observer.WaitForNavigationFinished();

  EXPECT_EQ(2, browser()->tab_strip_model()->count());
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(about_blank, web_contents->GetLastCommittedURL());
  url::Origin frame_origin =
      web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin();
  url::SchemeHostPort precursor_tuple =
      frame_origin.GetTupleOrPrecursorTupleIfOpaque();
  EXPECT_EQ(kExtensionScheme, precursor_tuple.scheme());
  EXPECT_EQ(extension->id(), precursor_tuple.host());

  TestTabStripModelObserver test_tab_strip_model_observer(
      browser()->tab_strip_model());
  extension_registrar()->DisableExtension(
      extension->id(), {disable_reason::DISABLE_USER_ACTION});
  test_tab_strip_model_observer.WaitForTabCount(1);

  EXPECT_EQ(1, browser()->tab_strip_model()->count());
}

IN_PROC_BROWSER_TEST_F(ExtensionUnloadBrowserTest, CrashedTabs) {
  TestExtensionDir test_dir;
  test_dir.WriteManifest(
      R"({
           "name": "test extension",
           "manifest_version": 2,
           "version": "0.1"
         })");
  test_dir.WriteFile(FILE_PATH_LITERAL("page.html"),
                     "<!doctype html><html><body>Hello world</body></html>");
  scoped_refptr<const Extension> extension(
      LoadExtension(test_dir.UnpackedPath()));
  ASSERT_TRUE(extension);
  const GURL page_url = extension->ResolveExtensionURL("page.html");
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), page_url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  EXPECT_EQ(2, browser()->tab_strip_model()->count());

  content::WebContents* active_tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(page_url, active_tab->GetLastCommittedURL());

  {
    content::ScopedAllowRendererCrashes allow_renderer_crashes(
        active_tab->GetPrimaryMainFrame()->GetProcess());
    ui_test_utils::NavigateToURLWithDisposition(
        browser(), GURL("chrome://crash"), WindowOpenDisposition::CURRENT_TAB,
        ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  }

  // There should still be two open tabs, but the active one is crashed.
  EXPECT_EQ(2, browser()->tab_strip_model()->count());
  EXPECT_TRUE(active_tab->IsCrashed());

  // Even though the tab is crashed, it should still have the last committed
  // URL of the extension page.
  EXPECT_EQ(page_url, active_tab->GetLastCommittedURL());

  // Unloading the extension should close the crashed tab, since its origin was
  // still the extension's origin.
  TestTabStripModelObserver test_tab_strip_model_observer(
      browser()->tab_strip_model());
  extension_registrar()->DisableExtension(
      extension->id(), {disable_reason::DISABLE_USER_ACTION});
  test_tab_strip_model_observer.WaitForTabCount(1);

  EXPECT_EQ(1, browser()->tab_strip_model()->count());
  EXPECT_NE(extension->url().DeprecatedGetOriginAsURL(),
            browser()
                ->tab_strip_model()
                ->GetActiveWebContents()
                ->GetLastCommittedURL()
                .DeprecatedGetOriginAsURL());
}

// TODO(devlin): Investigate what to do for embedded iframes.

}  // namespace extensions