1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/error_console/error_console.h"
7 #include "base/files/file_path.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/strings/string16.h"
10 #include "base/strings/stringprintf.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/browser/extensions/extension_browsertest.h"
13 #include "chrome/browser/extensions/extension_toolbar_model.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/common/pref_names.h"
16 #include "chrome/common/url_constants.h"
17 #include "chrome/test/base/ui_test_utils.h"
18 #include "extensions/browser/extension_error.h"
19 #include "extensions/common/constants.h"
20 #include "extensions/common/error_utils.h"
21 #include "extensions/common/extension.h"
22 #include "extensions/common/extension_urls.h"
23 #include "extensions/common/feature_switch.h"
24 #include "extensions/common/manifest_constants.h"
25 #include "net/test/embedded_test_server/embedded_test_server.h"
26 #include "testing/gtest/include/gtest/gtest.h"
30 using base::UTF8ToUTF16;
32 namespace extensions {
36 const char kTestingPage[] = "/extensions/test_file.html";
37 const char kAnonymousFunction[] = "(anonymous function)";
38 const char* kBackgroundPageName =
39 extensions::kGeneratedBackgroundPageFilename;
40 const int kNoFlags = 0;
42 const StackTrace& GetStackTraceFromError(const ExtensionError* error) {
43 CHECK(error->type() == ExtensionError::RUNTIME_ERROR);
44 return (static_cast<const RuntimeError*>(error))->stack_trace();
47 // Verify that a given |frame| has the proper source and function name.
48 void CheckStackFrame(const StackFrame& frame,
49 const std::string& source,
50 const std::string& function) {
51 EXPECT_EQ(base::UTF8ToUTF16(source), frame.source);
52 EXPECT_EQ(base::UTF8ToUTF16(function), frame.function);
55 // Verify that all properties of a given |frame| are correct. Overloaded because
56 // we commonly do not check line/column numbers, as they are too likely
58 void CheckStackFrame(const StackFrame& frame,
59 const std::string& source,
60 const std::string& function,
62 size_t column_number) {
63 CheckStackFrame(frame, source, function);
64 EXPECT_EQ(line_number, frame.line_number);
65 EXPECT_EQ(column_number, frame.column_number);
68 // Verify that all properties of a given |error| are correct.
69 void CheckError(const ExtensionError* error,
70 ExtensionError::Type type,
71 const std::string& id,
72 const std::string& source,
74 const std::string& message) {
76 EXPECT_EQ(type, error->type());
77 EXPECT_EQ(id, error->extension_id());
78 EXPECT_EQ(base::UTF8ToUTF16(source), error->source());
79 EXPECT_EQ(from_incognito, error->from_incognito());
80 EXPECT_EQ(base::UTF8ToUTF16(message), error->message());
83 // Verify that all properties of a JS runtime error are correct.
84 void CheckRuntimeError(const ExtensionError* error,
85 const std::string& id,
86 const std::string& source,
88 const std::string& message,
89 logging::LogSeverity level,
91 size_t expected_stack_size) {
93 ExtensionError::RUNTIME_ERROR,
99 const RuntimeError* runtime_error = static_cast<const RuntimeError*>(error);
100 EXPECT_EQ(level, runtime_error->level());
101 EXPECT_EQ(context, runtime_error->context_url());
102 EXPECT_EQ(expected_stack_size, runtime_error->stack_trace().size());
105 void CheckManifestError(const ExtensionError* error,
106 const std::string& id,
107 const std::string& message,
108 const std::string& manifest_key,
109 const std::string& manifest_specific) {
111 ExtensionError::MANIFEST_ERROR,
113 // source is always the manifest for ManifestErrors.
114 base::FilePath(kManifestFilename).AsUTF8Unsafe(),
115 false, // manifest errors are never from incognito.
118 const ManifestError* manifest_error =
119 static_cast<const ManifestError*>(error);
120 EXPECT_EQ(base::UTF8ToUTF16(manifest_key), manifest_error->manifest_key());
121 EXPECT_EQ(base::UTF8ToUTF16(manifest_specific),
122 manifest_error->manifest_specific());
127 class ErrorConsoleBrowserTest : public ExtensionBrowserTest {
129 ErrorConsoleBrowserTest() : error_console_(NULL) { }
130 virtual ~ErrorConsoleBrowserTest() { }
133 // A helper class in order to wait for the proper number of errors to be
134 // caught by the ErrorConsole. This will run the MessageLoop until a given
135 // number of errors are observed.
138 // ErrorObserver observer(3, error_console);
139 // <Cause three errors...>
140 // observer.WaitForErrors();
141 // <Perform any additional checks...>
142 class ErrorObserver : public ErrorConsole::Observer {
144 ErrorObserver(size_t errors_expected, ErrorConsole* error_console)
145 : errors_observed_(0),
146 errors_expected_(errors_expected),
148 error_console_(error_console) {
149 error_console_->AddObserver(this);
151 virtual ~ErrorObserver() {
153 error_console_->RemoveObserver(this);
156 // ErrorConsole::Observer implementation.
157 virtual void OnErrorAdded(const ExtensionError* error) OVERRIDE {
159 if (errors_observed_ >= errors_expected_) {
161 base::MessageLoopForUI::current()->Quit();
165 virtual void OnErrorConsoleDestroyed() OVERRIDE {
166 error_console_ = NULL;
169 // Spin until the appropriate number of errors have been observed.
170 void WaitForErrors() {
171 if (errors_observed_ < errors_expected_) {
173 content::RunMessageLoop();
179 size_t errors_observed_;
180 size_t errors_expected_;
183 ErrorConsole* error_console_;
185 DISALLOW_COPY_AND_ASSIGN(ErrorObserver);
188 // The type of action which we take after we load an extension in order to
191 // Navigate to a (non-chrome) page to allow a content script to run.
193 // Simulate a browser action click.
194 ACTION_BROWSER_ACTION,
195 // Navigate to the new tab page.
197 // Do nothing (errors will be caused by a background script,
198 // or by a manifest/loading warning).
202 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
203 ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
205 // We need to enable the ErrorConsole FeatureSwitch in order to collect
207 FeatureSwitch::error_console()->SetOverrideValue(
208 FeatureSwitch::OVERRIDE_ENABLED);
211 virtual void SetUpOnMainThread() OVERRIDE {
212 ExtensionBrowserTest::SetUpOnMainThread();
214 // Errors are only kept if we have Developer Mode enabled.
215 profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true);
217 error_console_ = ErrorConsole::Get(profile());
218 CHECK(error_console_);
220 test_data_dir_ = test_data_dir_.AppendASCII("error_console");
223 const GURL& GetTestURL() {
224 if (test_url_.is_empty()) {
225 CHECK(embedded_test_server()->InitializeAndWaitUntilReady());
226 test_url_ = embedded_test_server()->GetURL(kTestingPage);
231 // Load the extension at |path|, take the specified |action|, and wait for
232 // |expected_errors| errors. Populate |extension| with a pointer to the loaded
234 void LoadExtensionAndCheckErrors(
235 const std::string& path,
237 size_t errors_expected,
239 const Extension** extension) {
240 ErrorObserver observer(errors_expected, error_console_);
242 LoadExtensionWithFlags(test_data_dir_.AppendASCII(path), flags);
243 ASSERT_TRUE(*extension);
246 case ACTION_NAVIGATE: {
247 ui_test_utils::NavigateToURL(browser(), GetTestURL());
250 case ACTION_BROWSER_ACTION: {
251 ExtensionToolbarModel::Get(profile())->ExecuteBrowserAction(
252 *extension, browser(), NULL, true);
255 case ACTION_NEW_TAB: {
256 ui_test_utils::NavigateToURL(browser(),
257 GURL(chrome::kChromeUINewTabURL));
266 observer.WaitForErrors();
268 // We should only have errors for a single extension, or should have no
269 // entries, if no errors were expected.
270 ASSERT_EQ(errors_expected > 0 ? 1u : 0u,
271 error_console()->get_num_entries_for_test());
274 error_console()->GetErrorsForExtension((*extension)->id()).size());
277 ErrorConsole* error_console() { return error_console_; }
279 // The URL used in testing for simple page navigations.
282 // Weak reference to the ErrorConsole.
283 ErrorConsole* error_console_;
286 // Test to ensure that we are successfully reporting manifest errors as an
287 // extension is installed.
288 IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, ReportManifestErrors) {
289 const Extension* extension = NULL;
290 // We expect two errors - one for an invalid permission, and a second for
292 LoadExtensionAndCheckErrors("manifest_warnings",
293 ExtensionBrowserTest::kFlagIgnoreManifestWarnings,
298 const ErrorList& errors =
299 error_console()->GetErrorsForExtension(extension->id());
301 // Unfortunately, there's not always a hard guarantee of order in parsing the
302 // manifest, so there's not a definitive order in which these errors may
303 // occur. As such, we need to determine which error corresponds to which
305 const ExtensionError* permissions_error = NULL;
306 const ExtensionError* unknown_key_error = NULL;
307 const char kFakeKey[] = "not_a_real_key";
308 for (size_t i = 0; i < errors.size(); ++i) {
309 ASSERT_EQ(ExtensionError::MANIFEST_ERROR, errors[i]->type());
310 std::string utf8_key = base::UTF16ToUTF8(
311 (static_cast<const ManifestError*>(errors[i]))->manifest_key());
312 if (utf8_key == manifest_keys::kPermissions)
313 permissions_error = errors[i];
314 else if (utf8_key == kFakeKey)
315 unknown_key_error = errors[i];
317 ASSERT_TRUE(permissions_error);
318 ASSERT_TRUE(unknown_key_error);
320 const char kFakePermission[] = "not_a_real_permission";
321 CheckManifestError(permissions_error,
323 ErrorUtils::FormatErrorMessage(
324 manifest_errors::kPermissionUnknownOrMalformed,
326 manifest_keys::kPermissions,
329 CheckManifestError(unknown_key_error,
331 ErrorUtils::FormatErrorMessage(
332 manifest_errors::kUnrecognizedManifestKey,
338 // Test that we do not store any errors unless the Developer Mode switch is
339 // toggled on the profile.
340 IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest,
341 DontStoreErrorsWithoutDeveloperMode) {
342 profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, false);
344 const Extension* extension = NULL;
345 // Same test as ReportManifestErrors, except we don't expect any errors since
346 // we disable Developer Mode.
347 LoadExtensionAndCheckErrors("manifest_warnings",
348 ExtensionBrowserTest::kFlagIgnoreManifestWarnings,
353 // Now if we enable developer mode, the errors should be reported...
354 profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true);
355 EXPECT_EQ(2u, error_console()->GetErrorsForExtension(extension->id()).size());
357 // ... and if we disable it again, all errors which we were holding should be
359 profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, false);
360 EXPECT_EQ(0u, error_console()->GetErrorsForExtension(extension->id()).size());
363 // Load an extension which, upon visiting any page, first sends out a console
364 // log, and then crashes with a JS TypeError.
365 IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest,
366 ContentScriptLogAndRuntimeError) {
367 const Extension* extension = NULL;
368 LoadExtensionAndCheckErrors(
369 "content_script_log_and_runtime_error",
371 2u, // Two errors: A log message and a JS type error.
375 std::string script_url = extension->url().Resolve("content_script.js").spec();
377 const ErrorList& errors =
378 error_console()->GetErrorsForExtension(extension->id());
380 // The first error should be a console log.
381 CheckRuntimeError(errors[0],
383 script_url, // The source should be the content script url.
384 false, // Not from incognito.
385 "Hello, World!", // The error message is the log.
387 GetTestURL(), // Content scripts run in the web page.
390 const StackTrace& stack_trace1 = GetStackTraceFromError(errors[0]);
391 CheckStackFrame(stack_trace1[0],
393 "logHelloWorld", // function name
395 11u /* column number */ );
397 CheckStackFrame(stack_trace1[1],
403 // The second error should be a runtime error.
404 CheckRuntimeError(errors[1],
407 false, // not from incognito
408 "Uncaught TypeError: "
409 "Cannot set property 'foo' of undefined",
410 logging::LOG_ERROR, // JS errors are always ERROR level.
414 const StackTrace& stack_trace2 = GetStackTraceFromError(errors[1]);
415 CheckStackFrame(stack_trace2[0],
422 // Catch an error from a BrowserAction; this is more complex than a content
423 // script error, since browser actions are routed through our own code.
424 IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, BrowserActionRuntimeError) {
425 const Extension* extension = NULL;
426 LoadExtensionAndCheckErrors(
427 "browser_action_runtime_error",
429 1u, // One error: A reference error from within the browser action.
430 ACTION_BROWSER_ACTION,
433 std::string script_url = extension->url().Resolve("browser_action.js").spec();
435 const ErrorList& errors =
436 error_console()->GetErrorsForExtension(extension->id());
438 std::string event_bindings_str =
439 base::StringPrintf("extensions::%s", kEventBindings);
441 std::string event_dispatch_to_listener_str =
442 base::StringPrintf("publicClass.%s [as dispatchToListener]",
449 false, // not incognito
450 "Error in event handler for browserAction.onClicked: baz is not defined\n"
451 "Stack trace: ReferenceError: baz is not defined",
453 extension->url().Resolve(kBackgroundPageName),
456 const StackTrace& stack_trace = GetStackTraceFromError(errors[0]);
458 CheckStackFrame(stack_trace[0], script_url, kAnonymousFunction);
459 CheckStackFrame(stack_trace[1],
460 "extensions::SafeBuiltins",
461 std::string("Function.target.") + kAnonymousFunction);
463 stack_trace[2], event_bindings_str, "EventImpl.dispatchToListener");
464 CheckStackFrame(stack_trace[3],
465 "extensions::SafeBuiltins",
466 std::string("Function.target.") + kAnonymousFunction);
467 CheckStackFrame(stack_trace[4], "extensions::utils",
468 event_dispatch_to_listener_str);
469 CheckStackFrame(stack_trace[5], event_bindings_str, "EventImpl.dispatch_");
470 CheckStackFrame(stack_trace[6], event_bindings_str, "dispatchArgs");
471 CheckStackFrame(stack_trace[7], event_bindings_str, "dispatchEvent");
474 // Test that we can catch an error for calling an API with improper arguments.
475 IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, BadAPIArgumentsRuntimeError) {
476 const Extension* extension = NULL;
477 LoadExtensionAndCheckErrors(
478 "bad_api_arguments_runtime_error",
480 1, // One error: call an API with improper arguments.
484 const ErrorList& errors =
485 error_console()->GetErrorsForExtension(extension->id());
487 std::string schema_utils_str =
488 base::StringPrintf("extensions::%s", kSchemaUtils);
493 schema_utils_str, // API calls are checked in schemaUtils.js.
494 false, // not incognito
495 "Uncaught Error: Invocation of form "
496 "tabs.get(string, function) doesn't match definition "
497 "tabs.get(integer tabId, function callback)",
499 extension->url().Resolve(kBackgroundPageName),
502 const StackTrace& stack_trace = GetStackTraceFromError(errors[0]);
503 ASSERT_EQ(1u, stack_trace.size());
504 CheckStackFrame(stack_trace[0],
509 // Test that we catch an error when we try to call an API method without
511 IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, BadAPIPermissionsRuntimeError) {
512 const Extension* extension = NULL;
513 LoadExtensionAndCheckErrors(
514 "bad_api_permissions_runtime_error",
516 1, // One error: we try to call addUrl() on chrome.history without
517 // permission, which results in a TypeError.
521 std::string script_url = extension->url().Resolve("background.js").spec();
523 const ErrorList& errors =
524 error_console()->GetErrorsForExtension(extension->id());
530 false, // not incognito
531 "Uncaught TypeError: Cannot read property 'addUrl' of undefined",
533 extension->url().Resolve(kBackgroundPageName),
536 const StackTrace& stack_trace = GetStackTraceFromError(errors[0]);
537 ASSERT_EQ(1u, stack_trace.size());
538 CheckStackFrame(stack_trace[0],
544 IN_PROC_BROWSER_TEST_F(ErrorConsoleBrowserTest, BadExtensionPage) {
545 const Extension* extension = NULL;
546 LoadExtensionAndCheckErrors(
547 "bad_extension_page",
549 1, // One error: the page will load JS which has a reference error.
554 } // namespace extensions