Roll src/third_party/WebKit b3f094a:f697bbd (svn 194310:194313)
[chromium-blink-merge.git] / extensions / common / file_util_unittest.cc
blobef284b520fcd71a19764d23ba5fb32c21e945839
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 "extensions/common/file_util.h"
7 #include "base/basictypes.h"
8 #include "base/files/file_util.h"
9 #include "base/files/scoped_temp_dir.h"
10 #include "base/json/json_string_value_serializer.h"
11 #include "base/path_service.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "extensions/common/constants.h"
15 #include "extensions/common/extension.h"
16 #include "extensions/common/extension_paths.h"
17 #include "extensions/common/manifest.h"
18 #include "extensions/common/manifest_constants.h"
19 #include "grit/extensions_strings.h"
20 #include "testing/gmock/include/gmock/gmock.h"
21 #include "testing/gtest/include/gtest/gtest.h"
22 #include "ui/base/l10n/l10n_util.h"
23 #include "url/gurl.h"
25 namespace extensions {
27 namespace {
29 scoped_refptr<Extension> LoadExtensionManifest(
30 base::DictionaryValue* manifest,
31 const base::FilePath& manifest_dir,
32 Manifest::Location location,
33 int extra_flags,
34 std::string* error) {
35 scoped_refptr<Extension> extension =
36 Extension::Create(manifest_dir, location, *manifest, extra_flags, error);
37 return extension;
40 scoped_refptr<Extension> LoadExtensionManifest(
41 const std::string& manifest_value,
42 const base::FilePath& manifest_dir,
43 Manifest::Location location,
44 int extra_flags,
45 std::string* error) {
46 JSONStringValueDeserializer deserializer(manifest_value);
47 scoped_ptr<base::Value> result(deserializer.Deserialize(NULL, error));
48 if (!result.get())
49 return NULL;
50 CHECK_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
51 return LoadExtensionManifest(
52 static_cast<base::DictionaryValue*>(result.get()),
53 manifest_dir,
54 location,
55 extra_flags,
56 error);
59 } // namespace
61 typedef testing::Test FileUtilTest;
63 TEST_F(FileUtilTest, InstallUninstallGarbageCollect) {
64 base::ScopedTempDir temp;
65 ASSERT_TRUE(temp.CreateUniqueTempDir());
67 // Create a source extension.
68 std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
69 std::string version("1.0");
70 base::FilePath src = temp.path().AppendASCII(extension_id);
71 ASSERT_TRUE(base::CreateDirectory(src));
73 base::FilePath extension_content;
74 base::CreateTemporaryFileInDir(src, &extension_content);
75 ASSERT_TRUE(base::PathExists(extension_content));
77 // Create a extensions tree.
78 base::FilePath all_extensions = temp.path().AppendASCII("extensions");
79 ASSERT_TRUE(base::CreateDirectory(all_extensions));
81 // Install in empty directory. Should create parent directories as needed.
82 base::FilePath version_1 =
83 file_util::InstallExtension(src, extension_id, version, all_extensions);
84 ASSERT_EQ(
85 version_1.value(),
86 all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0").value());
87 ASSERT_TRUE(base::DirectoryExists(version_1));
88 ASSERT_TRUE(base::PathExists(version_1.Append(extension_content.BaseName())));
90 // Should have moved the source.
91 ASSERT_FALSE(base::DirectoryExists(src));
93 // Install again. Should create a new one with different name.
94 ASSERT_TRUE(base::CreateDirectory(src));
95 base::FilePath version_2 =
96 file_util::InstallExtension(src, extension_id, version, all_extensions);
97 ASSERT_EQ(
98 version_2.value(),
99 all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1").value());
100 ASSERT_TRUE(base::DirectoryExists(version_2));
102 // Should have moved the source.
103 ASSERT_FALSE(base::DirectoryExists(src));
105 // Install yet again. Should create a new one with a different name.
106 ASSERT_TRUE(base::CreateDirectory(src));
107 base::FilePath version_3 =
108 file_util::InstallExtension(src, extension_id, version, all_extensions);
109 ASSERT_EQ(
110 version_3.value(),
111 all_extensions.AppendASCII(extension_id).AppendASCII("1.0_2").value());
112 ASSERT_TRUE(base::DirectoryExists(version_3));
114 // Uninstall. Should remove entire extension subtree.
115 file_util::UninstallExtension(all_extensions, extension_id);
116 ASSERT_FALSE(base::DirectoryExists(version_1.DirName()));
117 ASSERT_FALSE(base::DirectoryExists(version_2.DirName()));
118 ASSERT_FALSE(base::DirectoryExists(version_3.DirName()));
119 ASSERT_TRUE(base::DirectoryExists(all_extensions));
122 TEST_F(FileUtilTest, LoadExtensionWithValidLocales) {
123 base::FilePath install_dir;
124 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &install_dir));
125 install_dir = install_dir.AppendASCII("extension_with_locales");
127 std::string error;
128 scoped_refptr<Extension> extension(file_util::LoadExtension(
129 install_dir, Manifest::UNPACKED, Extension::NO_FLAGS, &error));
130 ASSERT_TRUE(extension.get() != NULL);
131 EXPECT_EQ("The first extension that I made.", extension->description());
134 TEST_F(FileUtilTest, LoadExtensionWithoutLocalesFolder) {
135 base::FilePath install_dir;
136 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &install_dir));
137 install_dir = install_dir.AppendASCII("extension_without_locales");
139 std::string error;
140 scoped_refptr<Extension> extension(file_util::LoadExtension(
141 install_dir, Manifest::UNPACKED, Extension::NO_FLAGS, &error));
142 ASSERT_FALSE(extension.get() == NULL);
143 EXPECT_TRUE(error.empty());
146 TEST_F(FileUtilTest, CheckIllegalFilenamesNoUnderscores) {
147 base::ScopedTempDir temp;
148 ASSERT_TRUE(temp.CreateUniqueTempDir());
150 base::FilePath src_path = temp.path().AppendASCII("some_dir");
151 ASSERT_TRUE(base::CreateDirectory(src_path));
153 std::string data = "{ \"name\": { \"message\": \"foobar\" } }";
154 ASSERT_TRUE(base::WriteFile(
155 src_path.AppendASCII("some_file.txt"), data.c_str(), data.length()));
156 std::string error;
157 EXPECT_TRUE(file_util::CheckForIllegalFilenames(temp.path(), &error));
160 TEST_F(FileUtilTest, CheckIllegalFilenamesOnlyReserved) {
161 base::ScopedTempDir temp;
162 ASSERT_TRUE(temp.CreateUniqueTempDir());
164 const base::FilePath::CharType* folders[] = {
165 extensions::kLocaleFolder, extensions::kPlatformSpecificFolder};
167 for (size_t i = 0; i < arraysize(folders); i++) {
168 base::FilePath src_path = temp.path().Append(folders[i]);
169 ASSERT_TRUE(base::CreateDirectory(src_path));
172 std::string error;
173 EXPECT_TRUE(file_util::CheckForIllegalFilenames(temp.path(), &error));
176 TEST_F(FileUtilTest, CheckIllegalFilenamesReservedAndIllegal) {
177 base::ScopedTempDir temp;
178 ASSERT_TRUE(temp.CreateUniqueTempDir());
180 base::FilePath src_path = temp.path().Append(extensions::kLocaleFolder);
181 ASSERT_TRUE(base::CreateDirectory(src_path));
183 src_path = temp.path().AppendASCII("_some_dir");
184 ASSERT_TRUE(base::CreateDirectory(src_path));
186 std::string error;
187 EXPECT_FALSE(file_util::CheckForIllegalFilenames(temp.path(), &error));
190 TEST_F(FileUtilTest, LoadExtensionGivesHelpfullErrorOnMissingManifest) {
191 base::FilePath install_dir;
192 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &install_dir));
193 install_dir =
194 install_dir.AppendASCII("file_util").AppendASCII("missing_manifest");
196 std::string error;
197 scoped_refptr<Extension> extension(file_util::LoadExtension(
198 install_dir, Manifest::UNPACKED, Extension::NO_FLAGS, &error));
199 ASSERT_TRUE(extension.get() == NULL);
200 ASSERT_FALSE(error.empty());
201 ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str());
204 TEST_F(FileUtilTest, LoadExtensionGivesHelpfullErrorOnBadManifest) {
205 base::FilePath install_dir;
206 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &install_dir));
207 install_dir =
208 install_dir.AppendASCII("file_util").AppendASCII("bad_manifest");
210 std::string error;
211 scoped_refptr<Extension> extension(file_util::LoadExtension(
212 install_dir, Manifest::UNPACKED, Extension::NO_FLAGS, &error));
213 ASSERT_TRUE(extension.get() == NULL);
214 ASSERT_FALSE(error.empty());
215 ASSERT_STREQ(
216 "Manifest is not valid JSON. "
217 "Line: 2, column: 16, Syntax error.",
218 error.c_str());
221 TEST_F(FileUtilTest, ValidateThemeUTF8) {
222 base::ScopedTempDir temp;
223 ASSERT_TRUE(temp.CreateUniqueTempDir());
225 // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
226 std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png";
227 base::FilePath non_ascii_path =
228 temp.path().Append(base::FilePath::FromUTF8Unsafe(non_ascii_file));
229 base::WriteFile(non_ascii_path, "", 0);
231 std::string kManifest = base::StringPrintf(
232 "{ \"name\": \"Test\", \"version\": \"1.0\", "
233 " \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }"
234 "}",
235 non_ascii_file.c_str());
236 std::string error;
237 scoped_refptr<Extension> extension = LoadExtensionManifest(
238 kManifest, temp.path(), Manifest::UNPACKED, 0, &error);
239 ASSERT_TRUE(extension.get()) << error;
241 std::vector<extensions::InstallWarning> warnings;
242 EXPECT_TRUE(file_util::ValidateExtension(extension.get(), &error, &warnings))
243 << error;
244 EXPECT_EQ(0U, warnings.size());
247 TEST_F(FileUtilTest, BackgroundScriptsMustExist) {
248 base::ScopedTempDir temp;
249 ASSERT_TRUE(temp.CreateUniqueTempDir());
251 scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
252 value->SetString("name", "test");
253 value->SetString("version", "1");
254 value->SetInteger("manifest_version", 1);
256 base::ListValue* scripts = new base::ListValue();
257 scripts->Append(new base::StringValue("foo.js"));
258 value->Set("background.scripts", scripts);
260 std::string error;
261 std::vector<extensions::InstallWarning> warnings;
262 scoped_refptr<Extension> extension = LoadExtensionManifest(
263 value.get(), temp.path(), Manifest::UNPACKED, 0, &error);
264 ASSERT_TRUE(extension.get()) << error;
266 EXPECT_FALSE(
267 file_util::ValidateExtension(extension.get(), &error, &warnings));
268 EXPECT_EQ(
269 l10n_util::GetStringFUTF8(IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED,
270 base::ASCIIToUTF16("foo.js")),
271 error);
272 EXPECT_EQ(0U, warnings.size());
274 scripts->Clear();
275 scripts->Append(new base::StringValue("http://google.com/foo.js"));
277 extension = LoadExtensionManifest(
278 value.get(), temp.path(), Manifest::UNPACKED, 0, &error);
279 ASSERT_TRUE(extension.get()) << error;
281 warnings.clear();
282 EXPECT_FALSE(
283 file_util::ValidateExtension(extension.get(), &error, &warnings));
284 EXPECT_EQ(
285 l10n_util::GetStringFUTF8(IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED,
286 base::ASCIIToUTF16("http://google.com/foo.js")),
287 error);
288 EXPECT_EQ(0U, warnings.size());
291 // Private key, generated by Chrome specifically for this test, and
292 // never used elsewhere.
293 const char private_key[] =
294 "-----BEGIN PRIVATE KEY-----\n"
295 "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKt02SR0FYaYy6fpW\n"
296 "MAA+kU1BgK3d+OmmWfdr+JATIjhRkyeSF4lTd/71JQsyKqPzYkQPi3EeROWM+goTv\n"
297 "EhJqq07q63BolpsFmlV+S4ny+sBA2B4aWwRYXlBWikdrQSA0mJMzvEHc6nKzBgXik\n"
298 "QSVbyyBNAsxlDB9WaCxRVOpK3AgMBAAECgYBGvSPlrVtAOAQ2V8j9FqorKZA8SLPX\n"
299 "IeJC/yzU3RB2nPMjI17aMOvrUHxJUhzMeh4jwabVvSzzDtKFozPGupW3xaI8sQdi2\n"
300 "WWMTQIk/Q9HHDWoQ9qA6SwX2qWCc5SyjCKqVp78ye+000kqTJYjBsDgXeAlzKcx2B\n"
301 "4GAAeWonDdkQJBANNb8wrqNWFn7DqyQTfELzcRTRnqQ/r1pdeJo6obzbnwGnlqe3t\n"
302 "KhLjtJNIGrQg5iC0OVLWFuvPJs0t3z62A1ckCQQDPq2JZuwTwu5Pl4DJ0r9O1FdqN\n"
303 "JgqPZyMptokCDQ3khLLGakIu+TqB9YtrzI69rJMSG2Egb+6McaDX+dh3XmR/AkB9t\n"
304 "xJf6qDnmA2td/tMtTc0NOk8Qdg/fD8xbZ/YfYMnVoYYs9pQoilBaWRePDRNURMLYZ\n"
305 "vHAI0Llmw7tj7jv17pAkEAz44uXRpjRKtllUIvi5pUENAHwDz+HvdpGH68jpU3hmb\n"
306 "uOwrmnQYxaMReFV68Z2w9DcLZn07f7/R9Wn72z89CxwJAFsDoNaDes4h48bX7plct\n"
307 "s9ACjmTwcCigZjN2K7AGv7ntCLF3DnV5dK0dTHNaAdD3SbY3jl29Rk2CwiURSX6Ee\n"
308 "g==\n"
309 "-----END PRIVATE KEY-----\n";
311 TEST_F(FileUtilTest, FindPrivateKeyFiles) {
312 base::ScopedTempDir temp;
313 ASSERT_TRUE(temp.CreateUniqueTempDir());
315 base::FilePath src_path = temp.path().AppendASCII("some_dir");
316 ASSERT_TRUE(base::CreateDirectory(src_path));
318 ASSERT_TRUE(base::WriteFile(
319 src_path.AppendASCII("a_key.pem"), private_key, arraysize(private_key)));
320 ASSERT_TRUE(base::WriteFile(src_path.AppendASCII("second_key.pem"),
321 private_key,
322 arraysize(private_key)));
323 // Shouldn't find a key with a different extension.
324 ASSERT_TRUE(base::WriteFile(src_path.AppendASCII("key.diff_ext"),
325 private_key,
326 arraysize(private_key)));
327 // Shouldn't find a key that isn't parsable.
328 ASSERT_TRUE(base::WriteFile(src_path.AppendASCII("unparsable_key.pem"),
329 private_key,
330 arraysize(private_key) - 30));
331 std::vector<base::FilePath> private_keys =
332 file_util::FindPrivateKeyFiles(temp.path());
333 EXPECT_EQ(2U, private_keys.size());
334 EXPECT_THAT(private_keys,
335 testing::Contains(src_path.AppendASCII("a_key.pem")));
336 EXPECT_THAT(private_keys,
337 testing::Contains(src_path.AppendASCII("second_key.pem")));
340 TEST_F(FileUtilTest, WarnOnPrivateKey) {
341 base::ScopedTempDir temp;
342 ASSERT_TRUE(temp.CreateUniqueTempDir());
344 base::FilePath ext_path = temp.path().AppendASCII("ext_root");
345 ASSERT_TRUE(base::CreateDirectory(ext_path));
347 const char manifest[] =
348 "{\n"
349 " \"name\": \"Test Extension\",\n"
350 " \"version\": \"1.0\",\n"
351 " \"manifest_version\": 2,\n"
352 " \"description\": \"The first extension that I made.\"\n"
353 "}\n";
354 ASSERT_TRUE(base::WriteFile(
355 ext_path.AppendASCII("manifest.json"), manifest, strlen(manifest)));
356 ASSERT_TRUE(base::WriteFile(
357 ext_path.AppendASCII("a_key.pem"), private_key, strlen(private_key)));
359 std::string error;
360 scoped_refptr<Extension> extension(
361 file_util::LoadExtension(ext_path,
362 "the_id",
363 Manifest::EXTERNAL_PREF,
364 Extension::NO_FLAGS,
365 &error));
366 ASSERT_TRUE(extension.get()) << error;
367 ASSERT_EQ(1u, extension->install_warnings().size());
368 EXPECT_THAT(extension->install_warnings(),
369 testing::ElementsAre(testing::Field(
370 &extensions::InstallWarning::message,
371 testing::ContainsRegex(
372 "extension includes the key file.*ext_root.a_key.pem"))));
374 // Turn the warning into an error with ERROR_ON_PRIVATE_KEY.
375 extension = file_util::LoadExtension(ext_path,
376 "the_id",
377 Manifest::EXTERNAL_PREF,
378 Extension::ERROR_ON_PRIVATE_KEY,
379 &error);
380 EXPECT_FALSE(extension.get());
381 EXPECT_THAT(error,
382 testing::ContainsRegex(
383 "extension includes the key file.*ext_root.a_key.pem"));
386 TEST_F(FileUtilTest, CheckZeroLengthIconFile) {
387 base::FilePath install_dir;
388 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &install_dir));
390 // Try to install an extension with a zero-length icon file.
391 base::FilePath ext_dir =
392 install_dir.AppendASCII("file_util").AppendASCII("bad_icon");
394 std::string error;
395 scoped_refptr<Extension> extension(file_util::LoadExtension(
396 ext_dir, Manifest::UNPACKED, Extension::NO_FLAGS, &error));
397 EXPECT_TRUE(extension.get() == NULL);
398 EXPECT_STREQ("Could not load extension icon 'icon.png'.", error.c_str());
401 TEST_F(FileUtilTest, ExtensionURLToRelativeFilePath) {
402 #define URL_PREFIX "chrome-extension://extension-id/"
403 struct TestCase {
404 const char* url;
405 const char* expected_relative_path;
406 } test_cases[] = {
407 { URL_PREFIX "simple.html",
408 "simple.html" },
409 { URL_PREFIX "directory/to/file.html",
410 "directory/to/file.html" },
411 { URL_PREFIX "escape%20spaces.html",
412 "escape spaces.html" },
413 { URL_PREFIX "%C3%9Cber.html",
414 "\xC3\x9C" "ber.html" },
415 #if defined(OS_WIN)
416 { URL_PREFIX "C%3A/simple.html",
417 "" },
418 #endif
419 { URL_PREFIX "////simple.html",
420 "simple.html" },
421 { URL_PREFIX "/simple.html",
422 "simple.html" },
423 { URL_PREFIX "\\simple.html",
424 "simple.html" },
425 { URL_PREFIX "\\\\foo\\simple.html",
426 "foo/simple.html" },
428 #undef URL_PREFIX
430 for (size_t i = 0; i < arraysize(test_cases); ++i) {
431 GURL url(test_cases[i].url);
432 base::FilePath expected_path =
433 base::FilePath::FromUTF8Unsafe(test_cases[i].expected_relative_path);
434 base::FilePath actual_path =
435 extensions::file_util::ExtensionURLToRelativeFilePath(url);
436 EXPECT_FALSE(actual_path.IsAbsolute()) <<
437 " For the path " << actual_path.value();
438 EXPECT_EQ(expected_path.value(), actual_path.value()) <<
439 " For the path " << url;
443 TEST_F(FileUtilTest, ExtensionResourceURLToFilePath) {
444 // Setup filesystem for testing.
445 base::FilePath root_path;
446 ASSERT_TRUE(base::CreateNewTempDirectory(
447 base::FilePath::StringType(), &root_path));
448 root_path = base::MakeAbsoluteFilePath(root_path);
449 ASSERT_FALSE(root_path.empty());
451 base::FilePath api_path = root_path.Append(FILE_PATH_LITERAL("apiname"));
452 ASSERT_TRUE(base::CreateDirectory(api_path));
454 const char data[] = "Test Data";
455 base::FilePath resource_path = api_path.Append(FILE_PATH_LITERAL("test.js"));
456 ASSERT_TRUE(base::WriteFile(resource_path, data, sizeof(data)));
457 resource_path = api_path.Append(FILE_PATH_LITERAL("escape spaces.js"));
458 ASSERT_TRUE(base::WriteFile(resource_path, data, sizeof(data)));
460 #ifdef FILE_PATH_USES_WIN_SEPARATORS
461 #define SEP "\\"
462 #else
463 #define SEP "/"
464 #endif
465 #define URL_PREFIX "chrome-extension-resource://"
466 struct TestCase {
467 const char* url;
468 const base::FilePath::CharType* expected_path;
469 } test_cases[] = {
470 { URL_PREFIX "apiname/test.js",
471 FILE_PATH_LITERAL("test.js") },
472 { URL_PREFIX "/apiname/test.js",
473 FILE_PATH_LITERAL("test.js") },
474 // Test % escape
475 { URL_PREFIX "apiname/%74%65st.js",
476 FILE_PATH_LITERAL("test.js") },
477 { URL_PREFIX "apiname/escape%20spaces.js",
478 FILE_PATH_LITERAL("escape spaces.js") },
479 // Test file does not exist.
480 { URL_PREFIX "apiname/directory/to/file.js",
481 NULL },
482 // Test apiname/../../test.js
483 { URL_PREFIX "apiname/../../test.js",
484 FILE_PATH_LITERAL("test.js") },
485 { URL_PREFIX "apiname/..%2F../test.js",
486 NULL },
487 { URL_PREFIX "apiname/f/../../../test.js",
488 FILE_PATH_LITERAL("test.js") },
489 { URL_PREFIX "apiname/f%2F..%2F..%2F../test.js",
490 NULL },
492 #undef SEP
493 #undef URL_PREFIX
495 for (size_t i = 0; i < arraysize(test_cases); ++i) {
496 GURL url(test_cases[i].url);
497 base::FilePath expected_path;
498 if (test_cases[i].expected_path)
499 expected_path = root_path.Append(FILE_PATH_LITERAL("apiname")).Append(
500 test_cases[i].expected_path);
501 base::FilePath actual_path =
502 extensions::file_util::ExtensionResourceURLToFilePath(url, root_path);
503 EXPECT_EQ(expected_path.value(), actual_path.value()) <<
504 " For the path " << url;
506 // Remove temp files.
507 ASSERT_TRUE(base::DeleteFile(root_path, true));
510 } // namespace extensions