summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/fetch_apitest.cc
blob: c35ad6e07731f60ff23cfc174e28ce42785a8d4d (plain)
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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/files/file_path.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/test_extension_dir.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/common/extension.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"

namespace extensions {

namespace {

// JavaScript snippet which performs a fetch given a URL expression to be
// substituted as %s, then sends back the fetched content using the
// domAutomationController.
const char* kFetchScript =
    "fetch(%s).then(function(result) {\n"
    "  return result.text();\n"
    "}).then(function(text) {\n"
    "  window.domAutomationController.send(text);\n"
    "}).catch(function(err) {\n"
    "  window.domAutomationController.send(String(err));\n"
    "});\n";

class ExtensionFetchTest : public ExtensionApiTest {
 protected:
  // Writes an empty background page and a text file called "text" with content
  // "text content", then loads and returns the extension. |dir| must already
  // have a manifest.
  const Extension* WriteFilesAndLoadTestExtension(TestExtensionDir* dir) {
    dir->WriteFile(FILE_PATH_LITERAL("text"), "text content");
    dir->WriteFile(FILE_PATH_LITERAL("bg.js"), "");
    return LoadExtension(dir->unpacked_path());
  }

  // Returns |kFetchScript| with |url_expression| substituted as its test URL.
  std::string GetFetchScript(const std::string& url_expression) {
    return base::StringPrintf(kFetchScript, url_expression.c_str());
  }

  // Returns |url| as a string surrounded by single quotes, for passing to
  // JavaScript as a string literal.
  std::string GetQuotedURL(const GURL& url) {
    return base::StringPrintf("'%s'", url.spec().c_str());
  }

  // Like GetQuotedURL(), but fetching the URL from the test server's |host|
  // and |path|.
  std::string GetQuotedTestServerURL(const std::string& host,
                                     const std::string& path) {
    return GetQuotedURL(embedded_test_server()->GetURL(host, path));
  }

  // Opens a tab, puts it in the foreground, navigates it to |url| then returns
  // its WebContents.
  content::WebContents* CreateAndNavigateTab(const GURL& url) {
    chrome::NavigateParams params(browser(), url, ui::PAGE_TRANSITION_LINK);
    params.disposition = NEW_FOREGROUND_TAB;
    ui_test_utils::NavigateToURL(&params);
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

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

IN_PROC_BROWSER_TEST_F(ExtensionFetchTest, ExtensionCanFetchExtensionResource) {
  TestExtensionDir dir;
  dir.WriteManifestWithSingleQuotes(
      "{"
      "'background': {'scripts': ['bg.js']},"
      "'manifest_version': 2,"
      "'name': 'ExtensionCanFetchExtensionResource',"
      "'version': '1'"
      "}");
  const Extension* extension = WriteFilesAndLoadTestExtension(&dir);
  ASSERT_TRUE(extension);

  EXPECT_EQ(
      "text content",
      ExecuteScriptInBackgroundPage(
          extension->id(), GetFetchScript("chrome.runtime.getURL('text')")));
}

IN_PROC_BROWSER_TEST_F(ExtensionFetchTest,
                       ExtensionCanFetchHostedResourceWithHostPermissions) {
  TestExtensionDir dir;
  dir.WriteManifestWithSingleQuotes(
      "{"
      "'background': {'scripts': ['bg.js']},"
      "'manifest_version': 2,"
      "'name': 'ExtensionCanFetchHostedResourceWithHostPermissions',"
      "'permissions': ['http://example.com/*'],"
      "'version': '1'"
      "}");
  const Extension* extension = WriteFilesAndLoadTestExtension(&dir);
  ASSERT_TRUE(extension);

  EXPECT_EQ("Hello!", ExecuteScriptInBackgroundPage(
                          extension->id(),
                          GetFetchScript(GetQuotedTestServerURL(
                              "example.com", "/extensions/test_file.txt"))));
}

IN_PROC_BROWSER_TEST_F(
    ExtensionFetchTest,
    ExtensionCannotFetchHostedResourceWithoutHostPermissions) {
  TestExtensionDir dir;
  dir.WriteManifestWithSingleQuotes(
      "{"
      "'background': {'scripts': ['bg.js']},"
      "'manifest_version': 2,"
      "'name': 'ExtensionCannotFetchHostedResourceWithoutHostPermissions',"
      "'version': '1'"
      "}");
  const Extension* extension = WriteFilesAndLoadTestExtension(&dir);
  ASSERT_TRUE(extension);

  // TODO(kalman): Another test would be to configure the test server to work
  // with CORS, and test that the fetch succeeds.
  EXPECT_EQ(
      "TypeError: Failed to fetch",
      ExecuteScriptInBackgroundPage(
          extension->id(), GetFetchScript(GetQuotedTestServerURL(
                               "example.com", "/extensions/test_file.txt"))));
}

IN_PROC_BROWSER_TEST_F(ExtensionFetchTest,
                       HostCanFetchWebAccessibleExtensionResource) {
  TestExtensionDir dir;
  dir.WriteManifestWithSingleQuotes(
      "{"
      "'background': {'scripts': ['bg.js']},"
      "'manifest_version': 2,"
      "'name': 'HostCanFetchWebAccessibleExtensionResource',"
      "'version': '1',"
      "'web_accessible_resources': ['text']"
      "}");
  const Extension* extension = WriteFilesAndLoadTestExtension(&dir);
  ASSERT_TRUE(extension);

  content::WebContents* empty_tab = CreateAndNavigateTab(
      embedded_test_server()->GetURL("example.com", "/empty.html"));

  // TODO(kalman): Test this from a content script too.
  std::string fetch_result;
  ASSERT_TRUE(content::ExecuteScriptAndExtractString(
      empty_tab,
      GetFetchScript(GetQuotedURL(extension->GetResourceURL("text"))),
      &fetch_result));
  EXPECT_EQ("text content", fetch_result);
}

IN_PROC_BROWSER_TEST_F(ExtensionFetchTest,
                       HostCannotFetchNonWebAccessibleExtensionResource) {
  TestExtensionDir dir;
  dir.WriteManifestWithSingleQuotes(
      "{"
      "'background': {'scripts': ['bg.js']},"
      "'manifest_version': 2,"
      "'name': 'HostCannotFetchNonWebAccessibleExtensionResource',"
      "'version': '1'"
      "}");
  const Extension* extension = WriteFilesAndLoadTestExtension(&dir);
  ASSERT_TRUE(extension);

  content::WebContents* empty_tab = CreateAndNavigateTab(
      embedded_test_server()->GetURL("example.com", "/empty.html"));

  // TODO(kalman): Test this from a content script too.
  std::string fetch_result;
  ASSERT_TRUE(content::ExecuteScriptAndExtractString(
      empty_tab,
      GetFetchScript(GetQuotedURL(extension->GetResourceURL("text"))),
      &fetch_result));
  EXPECT_EQ("TypeError: Failed to fetch", fetch_result);
}

}  // namespace

}  // namespace extensions