blob: 7f3931dd74911c9ed50fc0b0d1e4465a44d024de [file] [log] [blame]
[email protected]1791e6c92014-04-11 08:29:011// Copyright 2014 The Chromium Authors. All rights reserved.
[email protected]5e212ed2012-03-21 23:29:152// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
avia2f4804a2015-12-24 23:11:135#include <stddef.h>
6
dchengc963c7142016-04-08 03:55:227#include <memory>
[email protected]5e212ed2012-03-21 23:29:158#include <string>
vabr9984ea62017-04-10 11:33:499#include <utility>
[email protected]5e212ed2012-03-21 23:29:1510
lazyboyd6dbb262017-03-30 00:57:3011#include "base/command_line.h"
thestigc9e38a22014-09-13 01:02:1112#include "base/files/file_util.h"
avia2f4804a2015-12-24 23:11:1313#include "base/macros.h"
fdoraycb32419d2016-06-23 15:52:5514#include "base/run_loop.h"
[email protected]774cebd2013-09-26 04:55:0115#include "base/strings/string_number_conversions.h"
[email protected]00e7bef2013-06-10 20:35:1716#include "base/strings/string_util.h"
lazyboyd6dbb262017-03-30 00:57:3017#include "base/test/test_file_util.h"
[email protected]06492ed2013-03-24 22:13:1418#include "base/values.h"
lazyboyd6dbb262017-03-30 00:57:3019#include "chrome/browser/extensions/chrome_content_verifier_delegate.h"
[email protected]93ac047a2012-12-13 02:53:4920#include "chrome/common/chrome_paths.h"
lazyboyd6dbb262017-03-30 00:57:3021#include "chrome/common/chrome_switches.h"
22#include "chrome/test/base/testing_profile.h"
23#include "components/crx_file/id_util.h"
[email protected]5e212ed2012-03-21 23:29:1524#include "content/public/browser/resource_request_info.h"
jam7e588d6b2016-10-21 16:56:0625#include "content/public/common/browser_side_navigation_policy.h"
megjabloncaf312f2017-01-12 18:47:4926#include "content/public/common/previews_state.h"
[email protected]08a932d52012-06-03 21:42:1227#include "content/public/test/mock_resource_context.h"
[email protected]ec04d3f2013-06-06 21:31:3928#include "content/public/test/test_browser_thread_bundle.h"
lazyboyd6dbb262017-03-30 00:57:3029#include "content/public/test/test_utils.h"
30#include "extensions/browser/content_verifier.h"
[email protected]1791e6c92014-04-11 08:29:0131#include "extensions/browser/extension_protocols.h"
[email protected]38427a12013-11-09 17:34:2032#include "extensions/browser/info_map.h"
[email protected]885c0e92012-11-13 20:27:4233#include "extensions/common/constants.h"
[email protected]e4452d32013-11-15 23:07:4134#include "extensions/common/extension.h"
lazyboyd6dbb262017-03-30 00:57:3035#include "extensions/common/extension_builder.h"
asargenta093ec32016-02-13 01:36:4336#include "extensions/common/file_util.h"
[email protected]2ca01e52013-10-31 22:05:1937#include "net/base/request_priority.h"
rhalavati04b93382017-04-07 19:00:5438#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]5e212ed2012-03-21 23:29:1539#include "net/url_request/url_request.h"
[email protected]9d5730b2012-08-24 17:42:4940#include "net/url_request/url_request_job_factory_impl.h"
[email protected]5e212ed2012-03-21 23:29:1541#include "net/url_request/url_request_status.h"
42#include "net/url_request/url_request_test_util.h"
43#include "testing/gtest/include/gtest/gtest.h"
44
[email protected]7491ad02014-07-05 19:10:0745using content::ResourceType;
46
[email protected]702d8b42013-02-27 20:55:5047namespace extensions {
jamescook8816ae52014-09-05 17:02:3748namespace {
[email protected]5e212ed2012-03-21 23:29:1549
asargenta093ec32016-02-13 01:36:4350base::FilePath GetTestPath(const std::string& name) {
51 base::FilePath path;
52 EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
53 return path.AppendASCII("extensions").AppendASCII(name);
54}
55
lazyboyd6dbb262017-03-30 00:57:3056// Helper function that creates a file at |relative_path| within |directory|
57// and fills it with |content|.
58bool AddFileToDirectory(const base::FilePath& directory,
59 const base::FilePath& relative_path,
60 const std::string& content) {
61 base::FilePath full_path = directory.Append(relative_path);
62 int result = base::WriteFile(full_path, content.data(), content.size());
63 return static_cast<size_t>(result) == content.size();
64}
65
[email protected]5e212ed2012-03-21 23:29:1566scoped_refptr<Extension> CreateTestExtension(const std::string& name,
67 bool incognito_split_mode) {
[email protected]023b3d12013-12-23 18:46:4968 base::DictionaryValue manifest;
[email protected]5e212ed2012-03-21 23:29:1569 manifest.SetString("name", name);
70 manifest.SetString("version", "1");
[email protected]b109bdd2013-11-04 18:08:4371 manifest.SetInteger("manifest_version", 2);
[email protected]5e212ed2012-03-21 23:29:1572 manifest.SetString("incognito", incognito_split_mode ? "split" : "spanning");
73
asargenta093ec32016-02-13 01:36:4374 base::FilePath path = GetTestPath("response_headers");
[email protected]5e212ed2012-03-21 23:29:1575
76 std::string error;
77 scoped_refptr<Extension> extension(
[email protected]1d5e58b2013-01-31 08:41:4078 Extension::Create(path, Manifest::INTERNAL, manifest,
[email protected]ed3b9b12012-05-31 18:37:5179 Extension::NO_FLAGS, &error));
[email protected]5e212ed2012-03-21 23:29:1580 EXPECT_TRUE(extension.get()) << error;
81 return extension;
82}
83
[email protected]93ac047a2012-12-13 02:53:4984scoped_refptr<Extension> CreateWebStoreExtension() {
[email protected]023b3d12013-12-23 18:46:4985 base::DictionaryValue manifest;
[email protected]93ac047a2012-12-13 02:53:4986 manifest.SetString("name", "WebStore");
87 manifest.SetString("version", "1");
88 manifest.SetString("icons.16", "webstore_icon_16.png");
89
[email protected]650b2d52013-02-10 03:41:4590 base::FilePath path;
[email protected]93ac047a2012-12-13 02:53:4991 EXPECT_TRUE(PathService::Get(chrome::DIR_RESOURCES, &path));
92 path = path.AppendASCII("web_store");
93
94 std::string error;
95 scoped_refptr<Extension> extension(
[email protected]1d5e58b2013-01-31 08:41:4096 Extension::Create(path, Manifest::COMPONENT, manifest,
[email protected]93ac047a2012-12-13 02:53:4997 Extension::NO_FLAGS, &error));
98 EXPECT_TRUE(extension.get()) << error;
99 return extension;
100}
101
[email protected]6f7d7062013-06-04 03:49:33102scoped_refptr<Extension> CreateTestResponseHeaderExtension() {
[email protected]023b3d12013-12-23 18:46:49103 base::DictionaryValue manifest;
[email protected]6f7d7062013-06-04 03:49:33104 manifest.SetString("name", "An extension with web-accessible resources");
105 manifest.SetString("version", "2");
106
Jinho Bangb5216cec2018-01-17 19:43:11107 auto web_accessible_list = std::make_unique<base::ListValue>();
[email protected]6f7d7062013-06-04 03:49:33108 web_accessible_list->AppendString("test.dat");
vabr9984ea62017-04-10 11:33:49109 manifest.Set("web_accessible_resources", std::move(web_accessible_list));
[email protected]6f7d7062013-06-04 03:49:33110
asargenta093ec32016-02-13 01:36:43111 base::FilePath path = GetTestPath("response_headers");
[email protected]6f7d7062013-06-04 03:49:33112
113 std::string error;
114 scoped_refptr<Extension> extension(
115 Extension::Create(path, Manifest::UNPACKED, manifest,
116 Extension::NO_FLAGS, &error));
117 EXPECT_TRUE(extension.get()) << error;
118 return extension;
119}
120
lazyboyd6dbb262017-03-30 00:57:30121// A ContentVerifyJob::TestDelegate that observes DoneReading().
122class JobDelegate : public ContentVerifyJob::TestDelegate {
123 public:
124 explicit JobDelegate(const std::string& expected_contents)
125 : expected_contents_(expected_contents), run_loop_(new base::RunLoop()) {
126 ContentVerifyJob::SetDelegateForTests(this);
127 }
128 ~JobDelegate() override { ContentVerifyJob::SetDelegateForTests(nullptr); }
129
130 ContentVerifyJob::FailureReason BytesRead(const ExtensionId& id,
131 int count,
132 const char* data) override {
133 read_contents_.append(data, count);
134 return ContentVerifyJob::NONE;
135 }
136
137 ContentVerifyJob::FailureReason DoneReading(const ExtensionId& id) override {
138 seen_done_reading_extension_ids_.insert(id);
139 if (waiting_for_extension_id_ == id)
140 run_loop_->Quit();
141
142 if (!base::StartsWith(expected_contents_, read_contents_,
143 base::CompareCase::SENSITIVE)) {
144 ADD_FAILURE() << "Unexpected read, expected: " << expected_contents_
145 << ", but found: " << read_contents_;
146 }
147 return ContentVerifyJob::NONE;
148 }
149
150 void WaitForDoneReading(const ExtensionId& id) {
151 ASSERT_FALSE(waiting_for_extension_id_);
152 if (seen_done_reading_extension_ids_.count(id))
153 return;
154 waiting_for_extension_id_ = id;
155 run_loop_->Run();
156 }
157
158 void Reset() {
159 read_contents_.clear();
160 waiting_for_extension_id_.reset();
161 seen_done_reading_extension_ids_.clear();
Jinho Bangb5216cec2018-01-17 19:43:11162 run_loop_ = std::make_unique<base::RunLoop>();
lazyboyd6dbb262017-03-30 00:57:30163 }
164
165 private:
166 std::string expected_contents_;
167 std::string read_contents_;
168 std::set<ExtensionId> seen_done_reading_extension_ids_;
169 base::Optional<ExtensionId> waiting_for_extension_id_;
170 std::unique_ptr<base::RunLoop> run_loop_;
171
172 DISALLOW_COPY_AND_ASSIGN(JobDelegate);
173};
174
jamescook8816ae52014-09-05 17:02:37175} // namespace
176
177// This test lives in src/chrome instead of src/extensions because it tests
178// functionality delegated back to Chrome via ChromeExtensionsBrowserClient.
lfg048201a2014-09-16 19:09:36179// See chrome/browser/extensions/chrome_url_request_util.cc.
lazyboyd6dbb262017-03-30 00:57:30180class ExtensionProtocolsTest : public testing::Test {
[email protected]5e212ed2012-03-21 23:29:15181 public:
lazyboyd6dbb262017-03-30 00:57:30182 ExtensionProtocolsTest()
[email protected]1791e6c92014-04-11 08:29:01183 : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
184 old_factory_(NULL),
185 resource_context_(&test_url_request_context_) {}
[email protected]5e212ed2012-03-21 23:29:15186
dcheng72191812014-10-28 20:49:56187 void SetUp() override {
[email protected]06492ed2013-03-24 22:13:14188 testing::Test::SetUp();
lazyboyd6dbb262017-03-30 00:57:30189 testing_profile_ = TestingProfile::Builder().Build();
[email protected]38427a12013-11-09 17:34:20190 extension_info_map_ = new InfoMap();
[email protected]5e212ed2012-03-21 23:29:15191 net::URLRequestContext* request_context =
192 resource_context_.GetRequestContext();
193 old_factory_ = request_context->job_factory();
lazyboyd6dbb262017-03-30 00:57:30194
195 // Set up content verification.
196 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
197 command_line->AppendSwitchASCII(
198 switches::kExtensionContentVerification,
199 switches::kExtensionContentVerificationEnforce);
200 content_verifier_ = new ContentVerifier(
Jinho Bangb5216cec2018-01-17 19:43:11201 testing_profile_.get(), std::make_unique<ChromeContentVerifierDelegate>(
lazyboy528dedac2017-03-30 17:33:32202 testing_profile_.get()));
lazyboyd6dbb262017-03-30 00:57:30203 extension_info_map_->SetContentVerifier(content_verifier_.get());
[email protected]5e212ed2012-03-21 23:29:15204 }
205
dcheng72191812014-10-28 20:49:56206 void TearDown() override {
[email protected]5e212ed2012-03-21 23:29:15207 net::URLRequestContext* request_context =
208 resource_context_.GetRequestContext();
209 request_context->set_job_factory(old_factory_);
lazyboyd6dbb262017-03-30 00:57:30210 content_verifier_->Shutdown();
[email protected]5e212ed2012-03-21 23:29:15211 }
212
[email protected]1791e6c92014-04-11 08:29:01213 void SetProtocolHandler(bool is_incognito) {
[email protected]93ac047a2012-12-13 02:53:49214 net::URLRequestContext* request_context =
215 resource_context_.GetRequestContext();
216 job_factory_.SetProtocolHandler(
[email protected]702d8b42013-02-27 20:55:50217 kExtensionScheme,
[email protected]1791e6c92014-04-11 08:29:01218 CreateExtensionProtocolHandler(is_incognito,
[email protected]7b7e0b32014-03-17 16:09:23219 extension_info_map_.get()));
[email protected]93ac047a2012-12-13 02:53:49220 request_context->set_job_factory(&job_factory_);
221 }
222
[email protected]5e212ed2012-03-21 23:29:15223 void StartRequest(net::URLRequest* request,
[email protected]6c1e05212014-07-31 00:59:40224 ResourceType resource_type) {
gabf9d15582014-11-13 16:40:15225 content::ResourceRequestInfo::AllocateForTesting(
megjabloncaf312f2017-01-12 18:47:49226 request, resource_type, &resource_context_,
227 /*render_process_id=*/-1,
228 /*render_view_id=*/-1,
229 /*render_frame_id=*/-1,
230 /*is_main_frame=*/resource_type == content::RESOURCE_TYPE_MAIN_FRAME,
megjabloncaf312f2017-01-12 18:47:49231 /*allow_download=*/true,
Jian Li18173422017-11-08 03:00:02232 /*is_async=*/false, content::PREVIEWS_OFF,
233 /*navigation_ui_data*/ nullptr);
[email protected]5e212ed2012-03-21 23:29:15234 request->Start();
fdoraycb32419d2016-06-23 15:52:55235 base::RunLoop().Run();
[email protected]5e212ed2012-03-21 23:29:15236 }
237
asargenta093ec32016-02-13 01:36:43238 // Helper method to create a URLRequest, call StartRequest on it, and return
239 // the result. If |extension| hasn't already been added to
240 // |extension_info_map_|, this will add it.
maksim.sisov1b83bb72016-10-07 06:07:23241 int DoRequest(const Extension& extension, const std::string& relative_path) {
asargenta093ec32016-02-13 01:36:43242 if (!extension_info_map_->extensions().Contains(extension.id())) {
243 extension_info_map_->AddExtension(&extension,
244 base::Time::Now(),
245 false, // incognito_enabled
246 false); // notifications_disabled
247 }
dchengc963c7142016-04-08 03:55:22248 std::unique_ptr<net::URLRequest> request(
asargenta093ec32016-02-13 01:36:43249 resource_context_.GetRequestContext()->CreateRequest(
dchengc963c7142016-04-08 03:55:22250 extension.GetResourceURL(relative_path), net::DEFAULT_PRIORITY,
rhalavati04b93382017-04-07 19:00:54251 &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
asargenta093ec32016-02-13 01:36:43252 StartRequest(request.get(), content::RESOURCE_TYPE_MAIN_FRAME);
maksim.sisov1b83bb72016-10-07 06:07:23253 return test_delegate_.request_status();
asargenta093ec32016-02-13 01:36:43254 }
255
[email protected]5e212ed2012-03-21 23:29:15256 protected:
[email protected]ec04d3f2013-06-06 21:31:39257 content::TestBrowserThreadBundle thread_bundle_;
[email protected]38427a12013-11-09 17:34:20258 scoped_refptr<InfoMap> extension_info_map_;
[email protected]9d5730b2012-08-24 17:42:49259 net::URLRequestJobFactoryImpl job_factory_;
[email protected]5e212ed2012-03-21 23:29:15260 const net::URLRequestJobFactory* old_factory_;
[email protected]2086a3d2012-11-13 17:49:20261 net::TestDelegate test_delegate_;
[email protected]37ac95b2013-07-23 23:39:35262 net::TestURLRequestContext test_url_request_context_;
[email protected]5e212ed2012-03-21 23:29:15263 content::MockResourceContext resource_context_;
lazyboyd6dbb262017-03-30 00:57:30264 scoped_refptr<ContentVerifier> content_verifier_;
265 std::unique_ptr<TestingProfile> testing_profile_;
[email protected]5e212ed2012-03-21 23:29:15266};
267
268// Tests that making a chrome-extension request in an incognito context is
269// only allowed under the right circumstances (if the extension is allowed
270// in incognito, and it's either a non-main-frame request or a split-mode
271// extension).
lazyboyd6dbb262017-03-30 00:57:30272TEST_F(ExtensionProtocolsTest, IncognitoRequest) {
[email protected]93ac047a2012-12-13 02:53:49273 // Register an incognito extension protocol handler.
[email protected]1791e6c92014-04-11 08:29:01274 SetProtocolHandler(true);
[email protected]93ac047a2012-12-13 02:53:49275
[email protected]5e212ed2012-03-21 23:29:15276 struct TestCase {
277 // Inputs.
278 std::string name;
279 bool incognito_split_mode;
280 bool incognito_enabled;
281
282 // Expected results.
283 bool should_allow_main_frame_load;
284 bool should_allow_sub_frame_load;
285 } cases[] = {
286 {"spanning disabled", false, false, false, false},
287 {"split disabled", true, false, false, false},
nasko5cf9d452016-06-01 05:34:56288 {"spanning enabled", false, true, false, false},
289 {"split enabled", true, true, true, false},
[email protected]5e212ed2012-03-21 23:29:15290 };
291
viettrungluu9e65ad12014-10-16 04:22:26292 for (size_t i = 0; i < arraysize(cases); ++i) {
[email protected]5e212ed2012-03-21 23:29:15293 scoped_refptr<Extension> extension =
294 CreateTestExtension(cases[i].name, cases[i].incognito_split_mode);
295 extension_info_map_->AddExtension(
[email protected]9afacd22013-11-13 20:23:31296 extension.get(), base::Time::Now(), cases[i].incognito_enabled, false);
[email protected]5e212ed2012-03-21 23:29:15297
298 // First test a main frame request.
299 {
300 // It doesn't matter that the resource doesn't exist. If the resource
naskob9164c42016-06-07 01:21:35301 // is blocked, we should see BLOCKED_BY_CLIENT. Otherwise, the request
[email protected]5e212ed2012-03-21 23:29:15302 // should just fail because the file doesn't exist.
dchengc963c7142016-04-08 03:55:22303 std::unique_ptr<net::URLRequest> request(
[email protected]f7022f32014-08-21 16:32:19304 resource_context_.GetRequestContext()->CreateRequest(
dchengc963c7142016-04-08 03:55:22305 extension->GetResourceURL("404.html"), net::DEFAULT_PRIORITY,
rhalavati04b93382017-04-07 19:00:54306 &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:19307 StartRequest(request.get(), content::RESOURCE_TYPE_MAIN_FRAME);
[email protected]5e212ed2012-03-21 23:29:15308
309 if (cases[i].should_allow_main_frame_load) {
maksim.sisov1b83bb72016-10-07 06:07:23310 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, test_delegate_.request_status())
311 << cases[i].name;
[email protected]5e212ed2012-03-21 23:29:15312 } else {
maksim.sisov1b83bb72016-10-07 06:07:23313 EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, test_delegate_.request_status())
naskob9164c42016-06-07 01:21:35314 << cases[i].name;
[email protected]5e212ed2012-03-21 23:29:15315 }
316 }
317
318 // Now do a subframe request.
319 {
jam7e588d6b2016-10-21 16:56:06320 // With PlzNavigate, the subframe navigation requests are blocked in
321 // ExtensionNavigationThrottle which isn't added in this unit test. This
322 // is tested in an integration test in
323 // ExtensionResourceRequestPolicyTest.IframeNavigateToInaccessible.
324 if (!content::IsBrowserSideNavigationEnabled()) {
325 std::unique_ptr<net::URLRequest> request(
326 resource_context_.GetRequestContext()->CreateRequest(
327 extension->GetResourceURL("404.html"), net::DEFAULT_PRIORITY,
rhalavati04b93382017-04-07 19:00:54328 &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
jam7e588d6b2016-10-21 16:56:06329 StartRequest(request.get(), content::RESOURCE_TYPE_SUB_FRAME);
[email protected]5e212ed2012-03-21 23:29:15330
jam7e588d6b2016-10-21 16:56:06331 if (cases[i].should_allow_sub_frame_load) {
332 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, test_delegate_.request_status())
333 << cases[i].name;
334 } else {
335 EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, test_delegate_.request_status())
336 << cases[i].name;
337 }
[email protected]5e212ed2012-03-21 23:29:15338 }
339 }
340 }
341}
342
[email protected]774cebd2013-09-26 04:55:01343void CheckForContentLengthHeader(net::URLRequest* request) {
344 std::string content_length;
345 request->GetResponseHeaderByName(net::HttpRequestHeaders::kContentLength,
346 &content_length);
347 EXPECT_FALSE(content_length.empty());
348 int length_value = 0;
349 EXPECT_TRUE(base::StringToInt(content_length, &length_value));
350 EXPECT_GT(length_value, 0);
351}
352
[email protected]93ac047a2012-12-13 02:53:49353// Tests getting a resource for a component extension works correctly, both when
354// the extension is enabled and when it is disabled.
lazyboyd6dbb262017-03-30 00:57:30355TEST_F(ExtensionProtocolsTest, ComponentResourceRequest) {
[email protected]93ac047a2012-12-13 02:53:49356 // Register a non-incognito extension protocol handler.
[email protected]1791e6c92014-04-11 08:29:01357 SetProtocolHandler(false);
[email protected]93ac047a2012-12-13 02:53:49358
359 scoped_refptr<Extension> extension = CreateWebStoreExtension();
[email protected]9afacd22013-11-13 20:23:31360 extension_info_map_->AddExtension(extension.get(),
361 base::Time::Now(),
362 false,
363 false);
[email protected]93ac047a2012-12-13 02:53:49364
365 // First test it with the extension enabled.
366 {
dchengc963c7142016-04-08 03:55:22367 std::unique_ptr<net::URLRequest> request(
[email protected]f7022f32014-08-21 16:32:19368 resource_context_.GetRequestContext()->CreateRequest(
369 extension->GetResourceURL("webstore_icon_16.png"),
rhalavati04b93382017-04-07 19:00:54370 net::DEFAULT_PRIORITY, &test_delegate_,
371 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:19372 StartRequest(request.get(), content::RESOURCE_TYPE_MEDIA);
maksim.sisov1b83bb72016-10-07 06:07:23373 EXPECT_EQ(net::OK, test_delegate_.request_status());
[email protected]f7022f32014-08-21 16:32:19374 CheckForContentLengthHeader(request.get());
Chris Mumford9f87e392017-12-15 20:44:55375 std::string mime_type;
376 request->GetResponseHeaderByName(net::HttpRequestHeaders::kContentType,
377 &mime_type);
378 EXPECT_EQ("image/png", mime_type);
[email protected]93ac047a2012-12-13 02:53:49379 }
380
381 // And then test it with the extension disabled.
382 extension_info_map_->RemoveExtension(extension->id(),
limasdf0deef2042017-05-03 19:17:17383 UnloadedExtensionReason::DISABLE);
[email protected]93ac047a2012-12-13 02:53:49384 {
dchengc963c7142016-04-08 03:55:22385 std::unique_ptr<net::URLRequest> request(
[email protected]f7022f32014-08-21 16:32:19386 resource_context_.GetRequestContext()->CreateRequest(
387 extension->GetResourceURL("webstore_icon_16.png"),
rhalavati04b93382017-04-07 19:00:54388 net::DEFAULT_PRIORITY, &test_delegate_,
389 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:19390 StartRequest(request.get(), content::RESOURCE_TYPE_MEDIA);
maksim.sisov1b83bb72016-10-07 06:07:23391 EXPECT_EQ(net::OK, test_delegate_.request_status());
[email protected]f7022f32014-08-21 16:32:19392 CheckForContentLengthHeader(request.get());
Chris Mumford9f87e392017-12-15 20:44:55393 std::string mime_type;
394 request->GetResponseHeaderByName(net::HttpRequestHeaders::kContentType,
395 &mime_type);
396 EXPECT_EQ("image/png", mime_type);
[email protected]93ac047a2012-12-13 02:53:49397 }
398}
399
[email protected]6f7d7062013-06-04 03:49:33400// Tests that a URL request for resource from an extension returns a few
401// expected response headers.
lazyboyd6dbb262017-03-30 00:57:30402TEST_F(ExtensionProtocolsTest, ResourceRequestResponseHeaders) {
[email protected]6f7d7062013-06-04 03:49:33403 // Register a non-incognito extension protocol handler.
[email protected]1791e6c92014-04-11 08:29:01404 SetProtocolHandler(false);
[email protected]6f7d7062013-06-04 03:49:33405
406 scoped_refptr<Extension> extension = CreateTestResponseHeaderExtension();
[email protected]9afacd22013-11-13 20:23:31407 extension_info_map_->AddExtension(extension.get(),
408 base::Time::Now(),
409 false,
410 false);
[email protected]6f7d7062013-06-04 03:49:33411
412 {
dchengc963c7142016-04-08 03:55:22413 std::unique_ptr<net::URLRequest> request(
[email protected]f7022f32014-08-21 16:32:19414 resource_context_.GetRequestContext()->CreateRequest(
dchengc963c7142016-04-08 03:55:22415 extension->GetResourceURL("test.dat"), net::DEFAULT_PRIORITY,
rhalavati04b93382017-04-07 19:00:54416 &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:19417 StartRequest(request.get(), content::RESOURCE_TYPE_MEDIA);
maksim.sisov1b83bb72016-10-07 06:07:23418 EXPECT_EQ(net::OK, test_delegate_.request_status());
[email protected]6f7d7062013-06-04 03:49:33419
420 // Check that cache-related headers are set.
421 std::string etag;
[email protected]f7022f32014-08-21 16:32:19422 request->GetResponseHeaderByName("ETag", &etag);
brettw66d1b81b2015-07-06 19:29:40423 EXPECT_TRUE(base::StartsWith(etag, "\"", base::CompareCase::SENSITIVE));
424 EXPECT_TRUE(base::EndsWith(etag, "\"", base::CompareCase::SENSITIVE));
[email protected]6f7d7062013-06-04 03:49:33425
426 std::string revalidation_header;
[email protected]f7022f32014-08-21 16:32:19427 request->GetResponseHeaderByName("cache-control", &revalidation_header);
[email protected]6f7d7062013-06-04 03:49:33428 EXPECT_EQ("no-cache", revalidation_header);
429
430 // We set test.dat as web-accessible, so it should have a CORS header.
431 std::string access_control;
[email protected]f7022f32014-08-21 16:32:19432 request->GetResponseHeaderByName("Access-Control-Allow-Origin",
[email protected]6f7d7062013-06-04 03:49:33433 &access_control);
434 EXPECT_EQ("*", access_control);
435 }
436}
437
[email protected]b109bdd2013-11-04 18:08:43438// Tests that a URL request for main frame or subframe from an extension
439// succeeds, but subresources fail. See http://crbug.com/312269.
lazyboyd6dbb262017-03-30 00:57:30440TEST_F(ExtensionProtocolsTest, AllowFrameRequests) {
[email protected]b109bdd2013-11-04 18:08:43441 // Register a non-incognito extension protocol handler.
[email protected]1791e6c92014-04-11 08:29:01442 SetProtocolHandler(false);
[email protected]b109bdd2013-11-04 18:08:43443
444 scoped_refptr<Extension> extension = CreateTestExtension("foo", false);
[email protected]9afacd22013-11-13 20:23:31445 extension_info_map_->AddExtension(extension.get(),
446 base::Time::Now(),
447 false,
448 false);
[email protected]b109bdd2013-11-04 18:08:43449
nasko5cf9d452016-06-01 05:34:56450 // All MAIN_FRAME requests should succeed. SUB_FRAME requests that are not
451 // explicitly listed in web_accesible_resources or same-origin to the parent
452 // should not succeed.
[email protected]b109bdd2013-11-04 18:08:43453 {
dchengc963c7142016-04-08 03:55:22454 std::unique_ptr<net::URLRequest> request(
[email protected]f7022f32014-08-21 16:32:19455 resource_context_.GetRequestContext()->CreateRequest(
dchengc963c7142016-04-08 03:55:22456 extension->GetResourceURL("test.dat"), net::DEFAULT_PRIORITY,
rhalavati04b93382017-04-07 19:00:54457 &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:19458 StartRequest(request.get(), content::RESOURCE_TYPE_MAIN_FRAME);
maksim.sisov1b83bb72016-10-07 06:07:23459 EXPECT_EQ(net::OK, test_delegate_.request_status());
[email protected]b109bdd2013-11-04 18:08:43460 }
461 {
jam7e588d6b2016-10-21 16:56:06462 // With PlzNavigate, the subframe navigation requests are blocked in
463 // ExtensionNavigationThrottle which isn't added in this unit test. This is
464 // tested in an integration test in
465 // ExtensionResourceRequestPolicyTest.IframeNavigateToInaccessible.
466 if (!content::IsBrowserSideNavigationEnabled()) {
467 std::unique_ptr<net::URLRequest> request(
468 resource_context_.GetRequestContext()->CreateRequest(
469 extension->GetResourceURL("test.dat"), net::DEFAULT_PRIORITY,
rhalavati04b93382017-04-07 19:00:54470 &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
jam7e588d6b2016-10-21 16:56:06471 StartRequest(request.get(), content::RESOURCE_TYPE_SUB_FRAME);
472 EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, test_delegate_.request_status());
473 }
[email protected]b109bdd2013-11-04 18:08:43474 }
475
476 // And subresource types, such as media, should fail.
477 {
dchengc963c7142016-04-08 03:55:22478 std::unique_ptr<net::URLRequest> request(
[email protected]f7022f32014-08-21 16:32:19479 resource_context_.GetRequestContext()->CreateRequest(
dchengc963c7142016-04-08 03:55:22480 extension->GetResourceURL("test.dat"), net::DEFAULT_PRIORITY,
rhalavati04b93382017-04-07 19:00:54481 &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:19482 StartRequest(request.get(), content::RESOURCE_TYPE_MEDIA);
maksim.sisov1b83bb72016-10-07 06:07:23483 EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, test_delegate_.request_status());
[email protected]b109bdd2013-11-04 18:08:43484 }
485}
486
lazyboyd6dbb262017-03-30 00:57:30487TEST_F(ExtensionProtocolsTest, MetadataFolder) {
asargenta093ec32016-02-13 01:36:43488 SetProtocolHandler(false);
489
490 base::FilePath extension_dir = GetTestPath("metadata_folder");
491 std::string error;
492 scoped_refptr<Extension> extension =
493 file_util::LoadExtension(extension_dir, Manifest::INTERNAL,
494 Extension::NO_FLAGS, &error);
495 ASSERT_NE(extension.get(), nullptr) << "error: " << error;
496
497 // Loading "/test.html" should succeed.
maksim.sisov1b83bb72016-10-07 06:07:23498 EXPECT_EQ(net::OK, DoRequest(*extension, "test.html"));
asargenta093ec32016-02-13 01:36:43499
500 // Loading "/_metadata/verified_contents.json" should fail.
501 base::FilePath relative_path =
502 base::FilePath(kMetadataFolder).Append(kVerifiedContentsFilename);
503 EXPECT_TRUE(base::PathExists(extension_dir.Append(relative_path)));
maksim.sisov1b83bb72016-10-07 06:07:23504 EXPECT_EQ(net::ERR_FAILED,
asargenta093ec32016-02-13 01:36:43505 DoRequest(*extension, relative_path.AsUTF8Unsafe()));
506
507 // Loading "/_metadata/a.txt" should also fail.
508 relative_path = base::FilePath(kMetadataFolder).AppendASCII("a.txt");
509 EXPECT_TRUE(base::PathExists(extension_dir.Append(relative_path)));
maksim.sisov1b83bb72016-10-07 06:07:23510 EXPECT_EQ(net::ERR_FAILED,
asargenta093ec32016-02-13 01:36:43511 DoRequest(*extension, relative_path.AsUTF8Unsafe()));
512}
513
lazyboyd6dbb262017-03-30 00:57:30514// Tests that unreadable files and deleted files correctly go through
515// ContentVerifyJob.
516TEST_F(ExtensionProtocolsTest, VerificationSeenForFileAccessErrors) {
517 const char kFooJsContents[] = "hello world.";
518 JobDelegate test_job_delegate(kFooJsContents);
519 SetProtocolHandler(false);
520
521 const std::string kFooJs("foo.js");
522 // Create a temporary directory that a fake extension will live in and fill
523 // it with some test files.
524 base::ScopedTempDir temp_dir;
525 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
526 base::FilePath foo_js(FILE_PATH_LITERAL("foo.js"));
527 ASSERT_TRUE(AddFileToDirectory(temp_dir.GetPath(), foo_js, kFooJsContents))
528 << "Failed to write " << temp_dir.GetPath().value() << "/"
529 << foo_js.value();
530
531 ExtensionBuilder builder;
532 builder
533 .SetManifest(DictionaryBuilder()
534 .Set("name", "Foo")
535 .Set("version", "1.0")
536 .Set("manifest_version", 2)
537 .Set("update_url",
538 "https://clients2.google.com/service/update2/crx")
539 .Build())
540 .SetID(crx_file::id_util::GenerateId("whatever"))
541 .SetPath(temp_dir.GetPath())
542 .SetLocation(Manifest::INTERNAL);
543 scoped_refptr<Extension> extension(builder.Build());
544
545 ASSERT_TRUE(extension.get());
546 content_verifier_->OnExtensionLoaded(testing_profile_.get(), extension.get());
547 // Wait for PostTask to ContentVerifierIOData::AddData() to finish.
548 content::RunAllPendingInMessageLoop();
549
550 // Valid and readable foo.js.
551 EXPECT_EQ(net::OK, DoRequest(*extension, kFooJs));
552 test_job_delegate.WaitForDoneReading(extension->id());
553
554 // chmod -r foo.js.
555 base::FilePath foo_path = temp_dir.GetPath().AppendASCII(kFooJs);
556 ASSERT_TRUE(base::MakeFileUnreadable(foo_path));
557 test_job_delegate.Reset();
558 EXPECT_EQ(net::ERR_ACCESS_DENIED, DoRequest(*extension, kFooJs));
559 test_job_delegate.WaitForDoneReading(extension->id());
560
561 // Delete foo.js.
562 ASSERT_TRUE(base::DieFileDie(foo_path, false));
563 test_job_delegate.Reset();
564 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, DoRequest(*extension, kFooJs));
565 test_job_delegate.WaitForDoneReading(extension->id());
566}
567
lazyboye83ab9c62017-03-30 03:18:26568// Tests that zero byte files correctly go through ContentVerifyJob.
569TEST_F(ExtensionProtocolsTest, VerificationSeenForZeroByteFile) {
570 const char kFooJsContents[] = ""; // Empty.
571 JobDelegate test_job_delegate(kFooJsContents);
572 SetProtocolHandler(false);
573
574 const std::string kFooJs("foo.js");
575 // Create a temporary directory that a fake extension will live in and fill
576 // it with some test files.
577 base::ScopedTempDir temp_dir;
578 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
579 base::FilePath foo_js(FILE_PATH_LITERAL("foo.js"));
580 ASSERT_TRUE(AddFileToDirectory(temp_dir.GetPath(), foo_js, kFooJsContents))
581 << "Failed to write " << temp_dir.GetPath().value() << "/"
582 << foo_js.value();
583
584 // Sanity check foo.js.
585 base::FilePath foo_path = temp_dir.GetPath().AppendASCII(kFooJs);
586 int64_t foo_file_size = -1;
587 ASSERT_TRUE(base::GetFileSize(foo_path, &foo_file_size));
588 ASSERT_EQ(0, foo_file_size);
589
590 ExtensionBuilder builder;
591 builder
592 .SetManifest(DictionaryBuilder()
593 .Set("name", "Foo")
594 .Set("version", "1.0")
595 .Set("manifest_version", 2)
596 .Set("update_url",
597 "https://clients2.google.com/service/update2/crx")
598 .Build())
599 .SetID(crx_file::id_util::GenerateId("whatever"))
600 .SetPath(temp_dir.GetPath())
601 .SetLocation(Manifest::INTERNAL);
602 scoped_refptr<Extension> extension(builder.Build());
603
604 ASSERT_TRUE(extension.get());
605 content_verifier_->OnExtensionLoaded(testing_profile_.get(), extension.get());
606 // Wait for PostTask to ContentVerifierIOData::AddData() to finish.
607 content::RunAllPendingInMessageLoop();
608
609 // Request foo.js.
610 EXPECT_EQ(net::OK, DoRequest(*extension, kFooJs));
611 test_job_delegate.WaitForDoneReading(extension->id());
612}
613
[email protected]702d8b42013-02-27 20:55:50614} // namespace extensions