1 // Copyright 2014 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. 4 5 #include <string> 6 #include <vector> 7 8 #include "base/base64.h" 9 #include "base/file_util.h" 10 #include "base/files/file_path.h" 11 #include "base/path_service.h" 12 #include "base/stl_util.h" 13 #include "extensions/browser/verified_contents.h" 14 #include "extensions/common/extension.h" 15 #include "extensions/common/extension_paths.h" 16 #include "testing/gtest/include/gtest/gtest.h" 17 18 namespace extensions { 19 20 namespace { 21 22 bool Base64UrlStringEquals(std::string input, const std::string* bytes) { 23 if (!bytes) 24 return false; 25 if (!VerifiedContents::FixupBase64Encoding(&input)) 26 return false; 27 std::string decoded; 28 if (!base::Base64Decode(input, &decoded)) 29 return false; 30 if (decoded.size() != bytes->size()) 31 return false; 32 33 if (bytes->empty()) 34 return true; 35 36 return decoded == *bytes; 37 } 38 39 bool GetPublicKey(const base::FilePath& path, std::string* public_key) { 40 std::string public_key_pem; 41 if (!base::ReadFileToString(path, &public_key_pem)) 42 return false; 43 if (!Extension::ParsePEMKeyBytes(public_key_pem, public_key)) 44 return false; 45 return true; 46 } 47 48 } // namespace 49 50 TEST(VerifiedContents, Simple) { 51 // Figure out our test data directory. 52 base::FilePath path; 53 PathService::Get(DIR_TEST_DATA, &path); 54 path = path.AppendASCII("content_verifier/"); 55 56 // Initialize the VerifiedContents object. 57 std::string public_key; 58 ASSERT_TRUE(GetPublicKey(path.AppendASCII("public_key.pem"), &public_key)); 59 VerifiedContents contents(reinterpret_cast<const uint8*>(public_key.data()), 60 public_key.size()); 61 base::FilePath verified_contents_path = 62 path.AppendASCII("verified_contents.json"); 63 64 ASSERT_TRUE(contents.InitFrom(verified_contents_path, false)); 65 66 // Make sure we get expected values. 67 EXPECT_EQ(contents.block_size(), 4096); 68 EXPECT_EQ(contents.extension_id(), "abcdefghijklmnopabcdefghijklmnop"); 69 EXPECT_EQ("1.2.3", contents.version().GetString()); 70 71 EXPECT_TRUE(Base64UrlStringEquals( 72 "-vyyIIn7iSCzg7X3ICUI5wZa3tG7w7vyiCckxZdJGfs", 73 contents.GetTreeHashRoot( 74 base::FilePath::FromUTF8Unsafe("manifest.json")))); 75 EXPECT_TRUE(Base64UrlStringEquals( 76 "txHiG5KQvNoPOSH5FbQo9Zb5gJ23j3oFB0Ru9DOnziw", 77 contents.GetTreeHashRoot( 78 base::FilePath::FromUTF8Unsafe("background.js")))); 79 80 base::FilePath foo_bar_html = 81 base::FilePath(FILE_PATH_LITERAL("foo")).AppendASCII("bar.html"); 82 EXPECT_FALSE(foo_bar_html.IsAbsolute()); 83 EXPECT_TRUE( 84 Base64UrlStringEquals("L37LFbT_hmtxRL7AfGZN9YTpW6yoz_ZiQ1opLJn1NZU", 85 contents.GetTreeHashRoot(foo_bar_html))); 86 87 base::FilePath nonexistent = base::FilePath::FromUTF8Unsafe("nonexistent"); 88 EXPECT_TRUE(contents.GetTreeHashRoot(nonexistent) == NULL); 89 } 90 91 } // namespace extensions 92