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 const 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 *base::DictionaryValue::From(result
.Pass()).get(), manifest_dir
, location
,
58 typedef testing::Test FileUtilTest
;
60 TEST_F(FileUtilTest
, InstallUninstallGarbageCollect
) {
61 base::ScopedTempDir temp
;
62 ASSERT_TRUE(temp
.CreateUniqueTempDir());
64 // Create a source extension.
65 std::string
extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
66 std::string
version("1.0");
67 base::FilePath src
= temp
.path().AppendASCII(extension_id
);
68 ASSERT_TRUE(base::CreateDirectory(src
));
70 base::FilePath extension_content
;
71 base::CreateTemporaryFileInDir(src
, &extension_content
);
72 ASSERT_TRUE(base::PathExists(extension_content
));
74 // Create a extensions tree.
75 base::FilePath all_extensions
= temp
.path().AppendASCII("extensions");
76 ASSERT_TRUE(base::CreateDirectory(all_extensions
));
78 // Install in empty directory. Should create parent directories as needed.
79 base::FilePath version_1
=
80 file_util::InstallExtension(src
, extension_id
, version
, all_extensions
);
83 all_extensions
.AppendASCII(extension_id
).AppendASCII("1.0_0").value());
84 ASSERT_TRUE(base::DirectoryExists(version_1
));
85 ASSERT_TRUE(base::PathExists(version_1
.Append(extension_content
.BaseName())));
87 // Should have moved the source.
88 ASSERT_FALSE(base::DirectoryExists(src
));
90 // Install again. Should create a new one with different name.
91 ASSERT_TRUE(base::CreateDirectory(src
));
92 base::FilePath version_2
=
93 file_util::InstallExtension(src
, extension_id
, version
, all_extensions
);
96 all_extensions
.AppendASCII(extension_id
).AppendASCII("1.0_1").value());
97 ASSERT_TRUE(base::DirectoryExists(version_2
));
99 // Should have moved the source.
100 ASSERT_FALSE(base::DirectoryExists(src
));
102 // Install yet again. Should create a new one with a different name.
103 ASSERT_TRUE(base::CreateDirectory(src
));
104 base::FilePath version_3
=
105 file_util::InstallExtension(src
, extension_id
, version
, all_extensions
);
108 all_extensions
.AppendASCII(extension_id
).AppendASCII("1.0_2").value());
109 ASSERT_TRUE(base::DirectoryExists(version_3
));
111 // Uninstall. Should remove entire extension subtree.
112 file_util::UninstallExtension(all_extensions
, extension_id
);
113 ASSERT_FALSE(base::DirectoryExists(version_1
.DirName()));
114 ASSERT_FALSE(base::DirectoryExists(version_2
.DirName()));
115 ASSERT_FALSE(base::DirectoryExists(version_3
.DirName()));
116 ASSERT_TRUE(base::DirectoryExists(all_extensions
));
119 TEST_F(FileUtilTest
, LoadExtensionWithValidLocales
) {
120 base::FilePath install_dir
;
121 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &install_dir
));
122 install_dir
= install_dir
.AppendASCII("extension_with_locales");
125 scoped_refptr
<Extension
> extension(file_util::LoadExtension(
126 install_dir
, Manifest::UNPACKED
, Extension::NO_FLAGS
, &error
));
127 ASSERT_TRUE(extension
.get() != NULL
);
128 EXPECT_EQ("The first extension that I made.", extension
->description());
131 TEST_F(FileUtilTest
, LoadExtensionWithoutLocalesFolder
) {
132 base::FilePath install_dir
;
133 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &install_dir
));
134 install_dir
= install_dir
.AppendASCII("extension_without_locales");
137 scoped_refptr
<Extension
> extension(file_util::LoadExtension(
138 install_dir
, Manifest::UNPACKED
, Extension::NO_FLAGS
, &error
));
139 ASSERT_FALSE(extension
.get() == NULL
);
140 EXPECT_TRUE(error
.empty());
143 TEST_F(FileUtilTest
, CheckIllegalFilenamesNoUnderscores
) {
144 base::ScopedTempDir temp
;
145 ASSERT_TRUE(temp
.CreateUniqueTempDir());
147 base::FilePath src_path
= temp
.path().AppendASCII("some_dir");
148 ASSERT_TRUE(base::CreateDirectory(src_path
));
150 std::string data
= "{ \"name\": { \"message\": \"foobar\" } }";
151 ASSERT_TRUE(base::WriteFile(
152 src_path
.AppendASCII("some_file.txt"), data
.c_str(), data
.length()));
154 EXPECT_TRUE(file_util::CheckForIllegalFilenames(temp
.path(), &error
));
157 TEST_F(FileUtilTest
, CheckIllegalFilenamesOnlyReserved
) {
158 base::ScopedTempDir temp
;
159 ASSERT_TRUE(temp
.CreateUniqueTempDir());
161 const base::FilePath::CharType
* folders
[] = {
162 extensions::kLocaleFolder
, extensions::kPlatformSpecificFolder
};
164 for (size_t i
= 0; i
< arraysize(folders
); i
++) {
165 base::FilePath src_path
= temp
.path().Append(folders
[i
]);
166 ASSERT_TRUE(base::CreateDirectory(src_path
));
170 EXPECT_TRUE(file_util::CheckForIllegalFilenames(temp
.path(), &error
));
173 TEST_F(FileUtilTest
, CheckIllegalFilenamesReservedAndIllegal
) {
174 base::ScopedTempDir temp
;
175 ASSERT_TRUE(temp
.CreateUniqueTempDir());
177 base::FilePath src_path
= temp
.path().Append(extensions::kLocaleFolder
);
178 ASSERT_TRUE(base::CreateDirectory(src_path
));
180 src_path
= temp
.path().AppendASCII("_some_dir");
181 ASSERT_TRUE(base::CreateDirectory(src_path
));
184 EXPECT_FALSE(file_util::CheckForIllegalFilenames(temp
.path(), &error
));
187 // These tests do not work on Windows, because it is illegal to create a
188 // file/directory with a Windows reserved name. Because we cannot create a
189 // file that will cause the test to fail, let's skip the test.
191 TEST_F(FileUtilTest
, CheckIllegalFilenamesDirectoryWindowsReserved
) {
192 base::ScopedTempDir temp
;
193 ASSERT_TRUE(temp
.CreateUniqueTempDir());
195 base::FilePath src_path
= temp
.path().AppendASCII("aux");
196 ASSERT_TRUE(base::CreateDirectory(src_path
));
200 file_util::CheckForWindowsReservedFilenames(temp
.path(), &error
));
204 CheckIllegalFilenamesWindowsReservedFilenameWithExtension
) {
205 base::ScopedTempDir temp
;
206 ASSERT_TRUE(temp
.CreateUniqueTempDir());
208 base::FilePath src_path
= temp
.path().AppendASCII("some_dir");
209 ASSERT_TRUE(base::CreateDirectory(src_path
));
211 std::string data
= "{ \"name\": { \"message\": \"foobar\" } }";
212 ASSERT_TRUE(base::WriteFile(src_path
.AppendASCII("lpt1.txt"), data
.c_str(),
217 file_util::CheckForWindowsReservedFilenames(temp
.path(), &error
));
221 TEST_F(FileUtilTest
, LoadExtensionGivesHelpfullErrorOnMissingManifest
) {
222 base::FilePath install_dir
;
223 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &install_dir
));
225 install_dir
.AppendASCII("file_util").AppendASCII("missing_manifest");
228 scoped_refptr
<Extension
> extension(file_util::LoadExtension(
229 install_dir
, Manifest::UNPACKED
, Extension::NO_FLAGS
, &error
));
230 ASSERT_TRUE(extension
.get() == NULL
);
231 ASSERT_FALSE(error
.empty());
232 ASSERT_STREQ("Manifest file is missing or unreadable.", error
.c_str());
235 TEST_F(FileUtilTest
, LoadExtensionGivesHelpfullErrorOnBadManifest
) {
236 base::FilePath install_dir
;
237 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &install_dir
));
239 install_dir
.AppendASCII("file_util").AppendASCII("bad_manifest");
242 scoped_refptr
<Extension
> extension(file_util::LoadExtension(
243 install_dir
, Manifest::UNPACKED
, Extension::NO_FLAGS
, &error
));
244 ASSERT_TRUE(extension
.get() == NULL
);
245 ASSERT_FALSE(error
.empty());
247 "Manifest is not valid JSON. "
248 "Line: 2, column: 16, Syntax error.",
252 TEST_F(FileUtilTest
, ValidateThemeUTF8
) {
253 base::ScopedTempDir temp
;
254 ASSERT_TRUE(temp
.CreateUniqueTempDir());
256 // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
257 std::string non_ascii_file
= "\xC3\xA0\xC3\xA8\xC3\xB2.png";
258 base::FilePath non_ascii_path
=
259 temp
.path().Append(base::FilePath::FromUTF8Unsafe(non_ascii_file
));
260 base::WriteFile(non_ascii_path
, "", 0);
262 std::string kManifest
= base::StringPrintf(
263 "{ \"name\": \"Test\", \"version\": \"1.0\", "
264 " \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }"
266 non_ascii_file
.c_str());
268 scoped_refptr
<Extension
> extension
= LoadExtensionManifest(
269 kManifest
, temp
.path(), Manifest::UNPACKED
, 0, &error
);
270 ASSERT_TRUE(extension
.get()) << error
;
272 std::vector
<extensions::InstallWarning
> warnings
;
273 EXPECT_TRUE(file_util::ValidateExtension(extension
.get(), &error
, &warnings
))
275 EXPECT_EQ(0U, warnings
.size());
278 TEST_F(FileUtilTest
, BackgroundScriptsMustExist
) {
279 base::ScopedTempDir temp
;
280 ASSERT_TRUE(temp
.CreateUniqueTempDir());
282 scoped_ptr
<base::DictionaryValue
> value(new base::DictionaryValue());
283 value
->SetString("name", "test");
284 value
->SetString("version", "1");
285 value
->SetInteger("manifest_version", 1);
287 base::ListValue
* scripts
= new base::ListValue();
288 scripts
->Append(new base::StringValue("foo.js"));
289 value
->Set("background.scripts", scripts
);
292 std::vector
<extensions::InstallWarning
> warnings
;
293 scoped_refptr
<Extension
> extension
= LoadExtensionManifest(
294 *value
.get(), temp
.path(), Manifest::UNPACKED
, 0, &error
);
295 ASSERT_TRUE(extension
.get()) << error
;
298 file_util::ValidateExtension(extension
.get(), &error
, &warnings
));
300 l10n_util::GetStringFUTF8(IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED
,
301 base::ASCIIToUTF16("foo.js")),
303 EXPECT_EQ(0U, warnings
.size());
306 scripts
->Append(new base::StringValue("http://google.com/foo.js"));
308 extension
= LoadExtensionManifest(*value
.get(), temp
.path(),
309 Manifest::UNPACKED
, 0, &error
);
310 ASSERT_TRUE(extension
.get()) << error
;
314 file_util::ValidateExtension(extension
.get(), &error
, &warnings
));
316 l10n_util::GetStringFUTF8(IDS_EXTENSION_LOAD_BACKGROUND_SCRIPT_FAILED
,
317 base::ASCIIToUTF16("http://google.com/foo.js")),
319 EXPECT_EQ(0U, warnings
.size());
322 // Private key, generated by Chrome specifically for this test, and
323 // never used elsewhere.
324 const char private_key
[] =
325 "-----BEGIN PRIVATE KEY-----\n"
326 "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKt02SR0FYaYy6fpW\n"
327 "MAA+kU1BgK3d+OmmWfdr+JATIjhRkyeSF4lTd/71JQsyKqPzYkQPi3EeROWM+goTv\n"
328 "EhJqq07q63BolpsFmlV+S4ny+sBA2B4aWwRYXlBWikdrQSA0mJMzvEHc6nKzBgXik\n"
329 "QSVbyyBNAsxlDB9WaCxRVOpK3AgMBAAECgYBGvSPlrVtAOAQ2V8j9FqorKZA8SLPX\n"
330 "IeJC/yzU3RB2nPMjI17aMOvrUHxJUhzMeh4jwabVvSzzDtKFozPGupW3xaI8sQdi2\n"
331 "WWMTQIk/Q9HHDWoQ9qA6SwX2qWCc5SyjCKqVp78ye+000kqTJYjBsDgXeAlzKcx2B\n"
332 "4GAAeWonDdkQJBANNb8wrqNWFn7DqyQTfELzcRTRnqQ/r1pdeJo6obzbnwGnlqe3t\n"
333 "KhLjtJNIGrQg5iC0OVLWFuvPJs0t3z62A1ckCQQDPq2JZuwTwu5Pl4DJ0r9O1FdqN\n"
334 "JgqPZyMptokCDQ3khLLGakIu+TqB9YtrzI69rJMSG2Egb+6McaDX+dh3XmR/AkB9t\n"
335 "xJf6qDnmA2td/tMtTc0NOk8Qdg/fD8xbZ/YfYMnVoYYs9pQoilBaWRePDRNURMLYZ\n"
336 "vHAI0Llmw7tj7jv17pAkEAz44uXRpjRKtllUIvi5pUENAHwDz+HvdpGH68jpU3hmb\n"
337 "uOwrmnQYxaMReFV68Z2w9DcLZn07f7/R9Wn72z89CxwJAFsDoNaDes4h48bX7plct\n"
338 "s9ACjmTwcCigZjN2K7AGv7ntCLF3DnV5dK0dTHNaAdD3SbY3jl29Rk2CwiURSX6Ee\n"
340 "-----END PRIVATE KEY-----\n";
342 TEST_F(FileUtilTest
, FindPrivateKeyFiles
) {
343 base::ScopedTempDir temp
;
344 ASSERT_TRUE(temp
.CreateUniqueTempDir());
346 base::FilePath src_path
= temp
.path().AppendASCII("some_dir");
347 ASSERT_TRUE(base::CreateDirectory(src_path
));
349 ASSERT_TRUE(base::WriteFile(
350 src_path
.AppendASCII("a_key.pem"), private_key
, arraysize(private_key
)));
351 ASSERT_TRUE(base::WriteFile(src_path
.AppendASCII("second_key.pem"),
353 arraysize(private_key
)));
354 // Shouldn't find a key with a different extension.
355 ASSERT_TRUE(base::WriteFile(src_path
.AppendASCII("key.diff_ext"),
357 arraysize(private_key
)));
358 // Shouldn't find a key that isn't parsable.
359 ASSERT_TRUE(base::WriteFile(src_path
.AppendASCII("unparsable_key.pem"),
361 arraysize(private_key
) - 30));
362 std::vector
<base::FilePath
> private_keys
=
363 file_util::FindPrivateKeyFiles(temp
.path());
364 EXPECT_EQ(2U, private_keys
.size());
365 EXPECT_THAT(private_keys
,
366 testing::Contains(src_path
.AppendASCII("a_key.pem")));
367 EXPECT_THAT(private_keys
,
368 testing::Contains(src_path
.AppendASCII("second_key.pem")));
371 TEST_F(FileUtilTest
, WarnOnPrivateKey
) {
372 base::ScopedTempDir temp
;
373 ASSERT_TRUE(temp
.CreateUniqueTempDir());
375 base::FilePath ext_path
= temp
.path().AppendASCII("ext_root");
376 ASSERT_TRUE(base::CreateDirectory(ext_path
));
378 const char manifest
[] =
380 " \"name\": \"Test Extension\",\n"
381 " \"version\": \"1.0\",\n"
382 " \"manifest_version\": 2,\n"
383 " \"description\": \"The first extension that I made.\"\n"
385 ASSERT_TRUE(base::WriteFile(
386 ext_path
.AppendASCII("manifest.json"), manifest
, strlen(manifest
)));
387 ASSERT_TRUE(base::WriteFile(
388 ext_path
.AppendASCII("a_key.pem"), private_key
, strlen(private_key
)));
391 scoped_refptr
<Extension
> extension(
392 file_util::LoadExtension(ext_path
,
394 Manifest::EXTERNAL_PREF
,
397 ASSERT_TRUE(extension
.get()) << error
;
398 ASSERT_EQ(1u, extension
->install_warnings().size());
399 EXPECT_THAT(extension
->install_warnings(),
400 testing::ElementsAre(testing::Field(
401 &extensions::InstallWarning::message
,
402 testing::ContainsRegex(
403 "extension includes the key file.*ext_root.a_key.pem"))));
405 // Turn the warning into an error with ERROR_ON_PRIVATE_KEY.
406 extension
= file_util::LoadExtension(ext_path
,
408 Manifest::EXTERNAL_PREF
,
409 Extension::ERROR_ON_PRIVATE_KEY
,
411 EXPECT_FALSE(extension
.get());
413 testing::ContainsRegex(
414 "extension includes the key file.*ext_root.a_key.pem"));
417 TEST_F(FileUtilTest
, CheckZeroLengthIconFile
) {
418 base::FilePath install_dir
;
419 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &install_dir
));
421 // Try to install an extension with a zero-length icon file.
422 base::FilePath ext_dir
=
423 install_dir
.AppendASCII("file_util").AppendASCII("bad_icon");
426 scoped_refptr
<Extension
> extension(file_util::LoadExtension(
427 ext_dir
, Manifest::UNPACKED
, Extension::NO_FLAGS
, &error
));
428 EXPECT_TRUE(extension
.get() == NULL
);
429 EXPECT_STREQ("Could not load extension icon 'icon.png'.", error
.c_str());
432 TEST_F(FileUtilTest
, ExtensionURLToRelativeFilePath
) {
433 #define URL_PREFIX "chrome-extension://extension-id/"
436 const char* expected_relative_path
;
438 { URL_PREFIX
"simple.html",
440 { URL_PREFIX
"directory/to/file.html",
441 "directory/to/file.html" },
442 { URL_PREFIX
"escape%20spaces.html",
443 "escape spaces.html" },
444 { URL_PREFIX
"%C3%9Cber.html",
445 "\xC3\x9C" "ber.html" },
447 { URL_PREFIX
"C%3A/simple.html",
450 { URL_PREFIX
"////simple.html",
452 { URL_PREFIX
"/simple.html",
454 { URL_PREFIX
"\\simple.html",
456 { URL_PREFIX
"\\\\foo\\simple.html",
461 for (size_t i
= 0; i
< arraysize(test_cases
); ++i
) {
462 GURL
url(test_cases
[i
].url
);
463 base::FilePath expected_path
=
464 base::FilePath::FromUTF8Unsafe(test_cases
[i
].expected_relative_path
);
465 base::FilePath actual_path
=
466 extensions::file_util::ExtensionURLToRelativeFilePath(url
);
467 EXPECT_FALSE(actual_path
.IsAbsolute()) <<
468 " For the path " << actual_path
.value();
469 EXPECT_EQ(expected_path
.value(), actual_path
.value()) <<
470 " For the path " << url
;
474 TEST_F(FileUtilTest
, ExtensionResourceURLToFilePath
) {
475 // Setup filesystem for testing.
476 base::FilePath root_path
;
477 ASSERT_TRUE(base::CreateNewTempDirectory(
478 base::FilePath::StringType(), &root_path
));
479 root_path
= base::MakeAbsoluteFilePath(root_path
);
480 ASSERT_FALSE(root_path
.empty());
482 base::FilePath api_path
= root_path
.Append(FILE_PATH_LITERAL("apiname"));
483 ASSERT_TRUE(base::CreateDirectory(api_path
));
485 const char data
[] = "Test Data";
486 base::FilePath resource_path
= api_path
.Append(FILE_PATH_LITERAL("test.js"));
487 ASSERT_TRUE(base::WriteFile(resource_path
, data
, sizeof(data
)));
488 resource_path
= api_path
.Append(FILE_PATH_LITERAL("escape spaces.js"));
489 ASSERT_TRUE(base::WriteFile(resource_path
, data
, sizeof(data
)));
491 #ifdef FILE_PATH_USES_WIN_SEPARATORS
496 #define URL_PREFIX "chrome-extension-resource://"
499 const base::FilePath::CharType
* expected_path
;
501 { URL_PREFIX
"apiname/test.js",
502 FILE_PATH_LITERAL("test.js") },
503 { URL_PREFIX
"/apiname/test.js",
504 FILE_PATH_LITERAL("test.js") },
506 { URL_PREFIX
"apiname/%74%65st.js",
507 FILE_PATH_LITERAL("test.js") },
508 { URL_PREFIX
"apiname/escape%20spaces.js",
509 FILE_PATH_LITERAL("escape spaces.js") },
510 // Test file does not exist.
511 { URL_PREFIX
"apiname/directory/to/file.js",
513 // Test apiname/../../test.js
514 { URL_PREFIX
"apiname/../../test.js",
515 FILE_PATH_LITERAL("test.js") },
516 { URL_PREFIX
"apiname/..%2F../test.js",
518 { URL_PREFIX
"apiname/f/../../../test.js",
519 FILE_PATH_LITERAL("test.js") },
520 { URL_PREFIX
"apiname/f%2F..%2F..%2F../test.js",
526 for (size_t i
= 0; i
< arraysize(test_cases
); ++i
) {
527 GURL
url(test_cases
[i
].url
);
528 base::FilePath expected_path
;
529 if (test_cases
[i
].expected_path
)
530 expected_path
= root_path
.Append(FILE_PATH_LITERAL("apiname")).Append(
531 test_cases
[i
].expected_path
);
532 base::FilePath actual_path
=
533 extensions::file_util::ExtensionResourceURLToFilePath(url
, root_path
);
534 EXPECT_EQ(expected_path
.value(), actual_path
.value()) <<
535 " For the path " << url
;
537 // Remove temp files.
538 ASSERT_TRUE(base::DeleteFile(root_path
, true));
541 } // namespace extensions