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"
25 namespace extensions
{
29 scoped_refptr
<Extension
> LoadExtensionManifest(
30 base::DictionaryValue
* manifest
,
31 const base::FilePath
& manifest_dir
,
32 Manifest::Location location
,
35 scoped_refptr
<Extension
> extension
=
36 Extension::Create(manifest_dir
, location
, *manifest
, extra_flags
, error
);
40 scoped_refptr
<Extension
> LoadExtensionManifest(
41 const std::string
& manifest_value
,
42 const base::FilePath
& manifest_dir
,
43 Manifest::Location location
,
46 JSONStringValueDeserializer
deserializer(manifest_value
);
47 scoped_ptr
<base::Value
> result(deserializer
.Deserialize(NULL
, error
));
50 CHECK_EQ(base::Value::TYPE_DICTIONARY
, result
->GetType());
51 return LoadExtensionManifest(
52 static_cast<base::DictionaryValue
*>(result
.get()),
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
);
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
);
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
);
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");
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");
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()));
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
));
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
));
187 EXPECT_FALSE(file_util::CheckForIllegalFilenames(temp
.path(), &error
));
190 // These tests do not work on Windows, because it is illegal to create a
191 // file/directory with a Windows reserved name. Because we cannot create a
192 // file that will cause the test to fail, let's skip the test.
194 TEST_F(FileUtilTest
, CheckIllegalFilenamesDirectoryWindowsReserved
) {
195 base::ScopedTempDir temp
;
196 ASSERT_TRUE(temp
.CreateUniqueTempDir());
198 base::FilePath src_path
= temp
.path().AppendASCII("aux");
199 ASSERT_TRUE(base::CreateDirectory(src_path
));
203 file_util::CheckForWindowsReservedFilenames(temp
.path(), &error
));
207 CheckIllegalFilenamesWindowsReservedFilenameWithExtension
) {
208 base::ScopedTempDir temp
;
209 ASSERT_TRUE(temp
.CreateUniqueTempDir());
211 base::FilePath src_path
= temp
.path().AppendASCII("some_dir");
212 ASSERT_TRUE(base::CreateDirectory(src_path
));
214 std::string data
= "{ \"name\": { \"message\": \"foobar\" } }";
215 ASSERT_TRUE(base::WriteFile(src_path
.AppendASCII("lpt1.txt"), data
.c_str(),
220 file_util::CheckForWindowsReservedFilenames(temp
.path(), &error
));
224 TEST_F(FileUtilTest
, LoadExtensionGivesHelpfullErrorOnMissingManifest
) {
225 base::FilePath install_dir
;
226 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &install_dir
));
228 install_dir
.AppendASCII("file_util").AppendASCII("missing_manifest");
231 scoped_refptr
<Extension
> extension(file_util::LoadExtension(
232 install_dir
, Manifest::UNPACKED
, Extension::NO_FLAGS
, &error
));
233 ASSERT_TRUE(extension
.get() == NULL
);
234 ASSERT_FALSE(error
.empty());
235 ASSERT_STREQ("Manifest file is missing or unreadable.", error
.c_str());
238 TEST_F(FileUtilTest
, LoadExtensionGivesHelpfullErrorOnBadManifest
) {
239 base::FilePath install_dir
;
240 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &install_dir
));
242 install_dir
.AppendASCII("file_util").AppendASCII("bad_manifest");
245 scoped_refptr
<Extension
> extension(file_util::LoadExtension(
246 install_dir
, Manifest::UNPACKED
, Extension::NO_FLAGS
, &error
));
247 ASSERT_TRUE(extension
.get() == NULL
);
248 ASSERT_FALSE(error
.empty());
250 "Manifest is not valid JSON. "
251 "Line: 2, column: 16, Syntax error.",
255 TEST_F(FileUtilTest
, ValidateThemeUTF8
) {
256 base::ScopedTempDir temp
;
257 ASSERT_TRUE(temp
.CreateUniqueTempDir());
259 // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
260 std::string non_ascii_file
= "\xC3\xA0\xC3\xA8\xC3\xB2.png";
261 base::FilePath non_ascii_path
=
262 temp
.path().Append(base::FilePath::FromUTF8Unsafe(non_ascii_file
));
263 base::WriteFile(non_ascii_path
, "", 0);
265 std::string kManifest
= base::StringPrintf(
266 "{ \"name\": \"Test\", \"version\": \"1.0\", "
267 " \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }"
269 non_ascii_file
.c_str());
271 scoped_refptr
<Extension
> extension
= LoadExtensionManifest(
272 kManifest
, temp
.path(), Manifest::UNPACKED
, 0, &error
);
273 ASSERT_TRUE(extension
.get()) << error
;
275 std::vector
<extensions::InstallWarning
> warnings
;
276 EXPECT_TRUE(file_util::ValidateExtension(extension
.get(), &error
, &warnings
))
278 EXPECT_EQ(0U, warnings
.size());
281 TEST_F(FileUtilTest
, BackgroundScriptsMustExist
) {
282 base::ScopedTempDir temp
;
283 ASSERT_TRUE(temp
.CreateUniqueTempDir());
285 scoped_ptr
<base::DictionaryValue
> value(new base::DictionaryValue());
286 value
->SetString("name", "test");
287 value
->SetString("version", "1");
288 value
->SetInteger("manifest_version", 1);
290 base::ListValue
* scripts
= new base::ListValue();
291 scripts
->Append(new base::StringValue("foo.js"));
292 value
->Set("background.scripts", scripts
);
295 std::vector
<extensions::InstallWarning
> warnings
;
296 scoped_refptr
<Extension
> extension
= LoadExtensionManifest(
297 value
.get(), temp
.path(), Manifest::UNPACKED
, 0, &error
);
298 ASSERT_TRUE(extension
.get()) << error
;
301 file_util::ValidateExtension(extension
.get(), &error
, &warnings
));
303 l10n_util::GetStringFUTF8(IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED
,
304 base::ASCIIToUTF16("foo.js")),
306 EXPECT_EQ(0U, warnings
.size());
309 scripts
->Append(new base::StringValue("http://google.com/foo.js"));
311 extension
= LoadExtensionManifest(
312 value
.get(), temp
.path(), Manifest::UNPACKED
, 0, &error
);
313 ASSERT_TRUE(extension
.get()) << error
;
317 file_util::ValidateExtension(extension
.get(), &error
, &warnings
));
319 l10n_util::GetStringFUTF8(IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED
,
320 base::ASCIIToUTF16("http://google.com/foo.js")),
322 EXPECT_EQ(0U, warnings
.size());
325 // Private key, generated by Chrome specifically for this test, and
326 // never used elsewhere.
327 const char private_key
[] =
328 "-----BEGIN PRIVATE KEY-----\n"
329 "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKt02SR0FYaYy6fpW\n"
330 "MAA+kU1BgK3d+OmmWfdr+JATIjhRkyeSF4lTd/71JQsyKqPzYkQPi3EeROWM+goTv\n"
331 "EhJqq07q63BolpsFmlV+S4ny+sBA2B4aWwRYXlBWikdrQSA0mJMzvEHc6nKzBgXik\n"
332 "QSVbyyBNAsxlDB9WaCxRVOpK3AgMBAAECgYBGvSPlrVtAOAQ2V8j9FqorKZA8SLPX\n"
333 "IeJC/yzU3RB2nPMjI17aMOvrUHxJUhzMeh4jwabVvSzzDtKFozPGupW3xaI8sQdi2\n"
334 "WWMTQIk/Q9HHDWoQ9qA6SwX2qWCc5SyjCKqVp78ye+000kqTJYjBsDgXeAlzKcx2B\n"
335 "4GAAeWonDdkQJBANNb8wrqNWFn7DqyQTfELzcRTRnqQ/r1pdeJo6obzbnwGnlqe3t\n"
336 "KhLjtJNIGrQg5iC0OVLWFuvPJs0t3z62A1ckCQQDPq2JZuwTwu5Pl4DJ0r9O1FdqN\n"
337 "JgqPZyMptokCDQ3khLLGakIu+TqB9YtrzI69rJMSG2Egb+6McaDX+dh3XmR/AkB9t\n"
338 "xJf6qDnmA2td/tMtTc0NOk8Qdg/fD8xbZ/YfYMnVoYYs9pQoilBaWRePDRNURMLYZ\n"
339 "vHAI0Llmw7tj7jv17pAkEAz44uXRpjRKtllUIvi5pUENAHwDz+HvdpGH68jpU3hmb\n"
340 "uOwrmnQYxaMReFV68Z2w9DcLZn07f7/R9Wn72z89CxwJAFsDoNaDes4h48bX7plct\n"
341 "s9ACjmTwcCigZjN2K7AGv7ntCLF3DnV5dK0dTHNaAdD3SbY3jl29Rk2CwiURSX6Ee\n"
343 "-----END PRIVATE KEY-----\n";
345 TEST_F(FileUtilTest
, FindPrivateKeyFiles
) {
346 base::ScopedTempDir temp
;
347 ASSERT_TRUE(temp
.CreateUniqueTempDir());
349 base::FilePath src_path
= temp
.path().AppendASCII("some_dir");
350 ASSERT_TRUE(base::CreateDirectory(src_path
));
352 ASSERT_TRUE(base::WriteFile(
353 src_path
.AppendASCII("a_key.pem"), private_key
, arraysize(private_key
)));
354 ASSERT_TRUE(base::WriteFile(src_path
.AppendASCII("second_key.pem"),
356 arraysize(private_key
)));
357 // Shouldn't find a key with a different extension.
358 ASSERT_TRUE(base::WriteFile(src_path
.AppendASCII("key.diff_ext"),
360 arraysize(private_key
)));
361 // Shouldn't find a key that isn't parsable.
362 ASSERT_TRUE(base::WriteFile(src_path
.AppendASCII("unparsable_key.pem"),
364 arraysize(private_key
) - 30));
365 std::vector
<base::FilePath
> private_keys
=
366 file_util::FindPrivateKeyFiles(temp
.path());
367 EXPECT_EQ(2U, private_keys
.size());
368 EXPECT_THAT(private_keys
,
369 testing::Contains(src_path
.AppendASCII("a_key.pem")));
370 EXPECT_THAT(private_keys
,
371 testing::Contains(src_path
.AppendASCII("second_key.pem")));
374 TEST_F(FileUtilTest
, WarnOnPrivateKey
) {
375 base::ScopedTempDir temp
;
376 ASSERT_TRUE(temp
.CreateUniqueTempDir());
378 base::FilePath ext_path
= temp
.path().AppendASCII("ext_root");
379 ASSERT_TRUE(base::CreateDirectory(ext_path
));
381 const char manifest
[] =
383 " \"name\": \"Test Extension\",\n"
384 " \"version\": \"1.0\",\n"
385 " \"manifest_version\": 2,\n"
386 " \"description\": \"The first extension that I made.\"\n"
388 ASSERT_TRUE(base::WriteFile(
389 ext_path
.AppendASCII("manifest.json"), manifest
, strlen(manifest
)));
390 ASSERT_TRUE(base::WriteFile(
391 ext_path
.AppendASCII("a_key.pem"), private_key
, strlen(private_key
)));
394 scoped_refptr
<Extension
> extension(
395 file_util::LoadExtension(ext_path
,
397 Manifest::EXTERNAL_PREF
,
400 ASSERT_TRUE(extension
.get()) << error
;
401 ASSERT_EQ(1u, extension
->install_warnings().size());
402 EXPECT_THAT(extension
->install_warnings(),
403 testing::ElementsAre(testing::Field(
404 &extensions::InstallWarning::message
,
405 testing::ContainsRegex(
406 "extension includes the key file.*ext_root.a_key.pem"))));
408 // Turn the warning into an error with ERROR_ON_PRIVATE_KEY.
409 extension
= file_util::LoadExtension(ext_path
,
411 Manifest::EXTERNAL_PREF
,
412 Extension::ERROR_ON_PRIVATE_KEY
,
414 EXPECT_FALSE(extension
.get());
416 testing::ContainsRegex(
417 "extension includes the key file.*ext_root.a_key.pem"));
420 TEST_F(FileUtilTest
, CheckZeroLengthIconFile
) {
421 base::FilePath install_dir
;
422 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &install_dir
));
424 // Try to install an extension with a zero-length icon file.
425 base::FilePath ext_dir
=
426 install_dir
.AppendASCII("file_util").AppendASCII("bad_icon");
429 scoped_refptr
<Extension
> extension(file_util::LoadExtension(
430 ext_dir
, Manifest::UNPACKED
, Extension::NO_FLAGS
, &error
));
431 EXPECT_TRUE(extension
.get() == NULL
);
432 EXPECT_STREQ("Could not load extension icon 'icon.png'.", error
.c_str());
435 TEST_F(FileUtilTest
, ExtensionURLToRelativeFilePath
) {
436 #define URL_PREFIX "chrome-extension://extension-id/"
439 const char* expected_relative_path
;
441 { URL_PREFIX
"simple.html",
443 { URL_PREFIX
"directory/to/file.html",
444 "directory/to/file.html" },
445 { URL_PREFIX
"escape%20spaces.html",
446 "escape spaces.html" },
447 { URL_PREFIX
"%C3%9Cber.html",
448 "\xC3\x9C" "ber.html" },
450 { URL_PREFIX
"C%3A/simple.html",
453 { URL_PREFIX
"////simple.html",
455 { URL_PREFIX
"/simple.html",
457 { URL_PREFIX
"\\simple.html",
459 { URL_PREFIX
"\\\\foo\\simple.html",
464 for (size_t i
= 0; i
< arraysize(test_cases
); ++i
) {
465 GURL
url(test_cases
[i
].url
);
466 base::FilePath expected_path
=
467 base::FilePath::FromUTF8Unsafe(test_cases
[i
].expected_relative_path
);
468 base::FilePath actual_path
=
469 extensions::file_util::ExtensionURLToRelativeFilePath(url
);
470 EXPECT_FALSE(actual_path
.IsAbsolute()) <<
471 " For the path " << actual_path
.value();
472 EXPECT_EQ(expected_path
.value(), actual_path
.value()) <<
473 " For the path " << url
;
477 TEST_F(FileUtilTest
, ExtensionResourceURLToFilePath
) {
478 // Setup filesystem for testing.
479 base::FilePath root_path
;
480 ASSERT_TRUE(base::CreateNewTempDirectory(
481 base::FilePath::StringType(), &root_path
));
482 root_path
= base::MakeAbsoluteFilePath(root_path
);
483 ASSERT_FALSE(root_path
.empty());
485 base::FilePath api_path
= root_path
.Append(FILE_PATH_LITERAL("apiname"));
486 ASSERT_TRUE(base::CreateDirectory(api_path
));
488 const char data
[] = "Test Data";
489 base::FilePath resource_path
= api_path
.Append(FILE_PATH_LITERAL("test.js"));
490 ASSERT_TRUE(base::WriteFile(resource_path
, data
, sizeof(data
)));
491 resource_path
= api_path
.Append(FILE_PATH_LITERAL("escape spaces.js"));
492 ASSERT_TRUE(base::WriteFile(resource_path
, data
, sizeof(data
)));
494 #ifdef FILE_PATH_USES_WIN_SEPARATORS
499 #define URL_PREFIX "chrome-extension-resource://"
502 const base::FilePath::CharType
* expected_path
;
504 { URL_PREFIX
"apiname/test.js",
505 FILE_PATH_LITERAL("test.js") },
506 { URL_PREFIX
"/apiname/test.js",
507 FILE_PATH_LITERAL("test.js") },
509 { URL_PREFIX
"apiname/%74%65st.js",
510 FILE_PATH_LITERAL("test.js") },
511 { URL_PREFIX
"apiname/escape%20spaces.js",
512 FILE_PATH_LITERAL("escape spaces.js") },
513 // Test file does not exist.
514 { URL_PREFIX
"apiname/directory/to/file.js",
516 // Test apiname/../../test.js
517 { URL_PREFIX
"apiname/../../test.js",
518 FILE_PATH_LITERAL("test.js") },
519 { URL_PREFIX
"apiname/..%2F../test.js",
521 { URL_PREFIX
"apiname/f/../../../test.js",
522 FILE_PATH_LITERAL("test.js") },
523 { URL_PREFIX
"apiname/f%2F..%2F..%2F../test.js",
529 for (size_t i
= 0; i
< arraysize(test_cases
); ++i
) {
530 GURL
url(test_cases
[i
].url
);
531 base::FilePath expected_path
;
532 if (test_cases
[i
].expected_path
)
533 expected_path
= root_path
.Append(FILE_PATH_LITERAL("apiname")).Append(
534 test_cases
[i
].expected_path
);
535 base::FilePath actual_path
=
536 extensions::file_util::ExtensionResourceURLToFilePath(url
, root_path
);
537 EXPECT_EQ(expected_path
.value(), actual_path
.value()) <<
538 " For the path " << url
;
540 // Remove temp files.
541 ASSERT_TRUE(base::DeleteFile(root_path
, true));
544 } // namespace extensions