Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chromeos / cert_loader_unittest.cc
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 "chromeos/cert_loader.h"
6
7 #include "base/bind.h"
8 #include "base/file_util.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/run_loop.h"
12 #include "crypto/nss_util.h"
13 #include "crypto/nss_util_internal.h"
14 #include "net/base/net_errors.h"
15 #include "net/base/test_data_directory.h"
16 #include "net/cert/nss_cert_database_chromeos.h"
17 #include "net/cert/x509_certificate.h"
18 #include "net/test/cert_test_util.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20
21 namespace chromeos {
22 namespace {
23
24 bool IsCertInCertificateList(const net::X509Certificate* cert,
25                              const net::CertificateList& cert_list) {
26   for (net::CertificateList::const_iterator it = cert_list.begin();
27        it != cert_list.end();
28        ++it) {
29     if (net::X509Certificate::IsSameOSCert((*it)->os_cert_handle(),
30                                             cert->os_cert_handle())) {
31       return true;
32     }
33   }
34   return false;
35 }
36
37 void FailOnPrivateSlotCallback(crypto::ScopedPK11Slot slot) {
38   EXPECT_FALSE(true) << "GetPrivateSlotForChromeOSUser callback called even "
39                      << "though the private slot had been initialized.";
40 }
41
42 class CertLoaderTest : public testing::Test,
43                        public CertLoader::Observer {
44  public:
45   CertLoaderTest() : cert_loader_(NULL),
46                      primary_user_("primary"),
47                      certificates_loaded_events_count_(0U) {
48   }
49
50   virtual ~CertLoaderTest() {}
51
52   virtual void SetUp() OVERRIDE {
53     ASSERT_TRUE(primary_user_.constructed_successfully());
54     ASSERT_TRUE(
55         crypto::GetPublicSlotForChromeOSUser(primary_user_.username_hash()));
56
57     CertLoader::Initialize();
58     cert_loader_ = CertLoader::Get();
59     cert_loader_->AddObserver(this);
60   }
61
62   virtual void TearDown() {
63     cert_loader_->RemoveObserver(this);
64     CertLoader::Shutdown();
65   }
66
67  protected:
68   void StartCertLoaderWithPrimaryUser() {
69     FinishUserInitAndGetDatabase(&primary_user_, &primary_db_);
70     cert_loader_->StartWithNSSDB(primary_db_.get());
71
72     base::RunLoop().RunUntilIdle();
73     GetAndResetCertificatesLoadedEventsCount();
74   }
75
76   // CertLoader::Observer:
77   // The test keeps count of times the observer method was called.
78   virtual void OnCertificatesLoaded(const net::CertificateList& cert_list,
79                                     bool initial_load) OVERRIDE {
80     EXPECT_TRUE(certificates_loaded_events_count_ == 0 || !initial_load);
81     certificates_loaded_events_count_++;
82   }
83
84   // Returns the number of |OnCertificatesLoaded| calls observed since the
85   // last call to this method equals |value|.
86   size_t GetAndResetCertificatesLoadedEventsCount() {
87     size_t result = certificates_loaded_events_count_;
88     certificates_loaded_events_count_ = 0;
89     return result;
90   }
91
92   // Finishes initialization for the |user| and returns a user's NSS database
93   // instance.
94   void FinishUserInitAndGetDatabase(
95       crypto::ScopedTestNSSChromeOSUser* user,
96       scoped_ptr<net::NSSCertDatabaseChromeOS>* database) {
97     ASSERT_TRUE(user->constructed_successfully());
98
99     user->FinishInit();
100
101     crypto::ScopedPK11Slot private_slot(
102         crypto::GetPrivateSlotForChromeOSUser(
103             user->username_hash(),
104             base::Bind(&FailOnPrivateSlotCallback)));
105     ASSERT_TRUE(private_slot);
106
107     database->reset(new net::NSSCertDatabaseChromeOS(
108         crypto::GetPublicSlotForChromeOSUser(user->username_hash()),
109         private_slot.Pass()));
110     (*database)->SetSlowTaskRunnerForTest(message_loop_.message_loop_proxy());
111   }
112
113   int GetDbPrivateSlotId(net::NSSCertDatabase* db) {
114     return static_cast<int>(PK11_GetSlotID(db->GetPrivateSlot().get()));
115   }
116
117   void ImportCACert(const std::string& cert_file,
118                     net::NSSCertDatabase* database,
119                     net::CertificateList* imported_certs) {
120     ASSERT_TRUE(database);
121     ASSERT_TRUE(imported_certs);
122
123     // Add a certificate to the user's db.
124     *imported_certs = net::CreateCertificateListFromFile(
125         net::GetTestCertsDirectory(),
126         cert_file,
127         net::X509Certificate::FORMAT_AUTO);
128     ASSERT_EQ(1U, imported_certs->size());
129
130     net::NSSCertDatabase::ImportCertFailureList failed;
131     ASSERT_TRUE(database->ImportCACerts(*imported_certs,
132                                         net::NSSCertDatabase::TRUST_DEFAULT,
133                                         &failed));
134     ASSERT_TRUE(failed.empty());
135   }
136
137   void ImportClientCertAndKey(const std::string& pkcs12_file,
138                               net::NSSCertDatabase* database,
139                               net::CertificateList* imported_certs) {
140     ASSERT_TRUE(database);
141     ASSERT_TRUE(imported_certs);
142
143     std::string pkcs12_data;
144     base::FilePath pkcs12_file_path =
145         net::GetTestCertsDirectory().Append(pkcs12_file);
146     ASSERT_TRUE(base::ReadFileToString(pkcs12_file_path, &pkcs12_data));
147
148     net::CertificateList client_cert_list;
149     scoped_refptr<net::CryptoModule> module(net::CryptoModule::CreateFromHandle(
150         database->GetPrivateSlot().get()));
151     ASSERT_EQ(
152         net::OK,
153         database->ImportFromPKCS12(module, pkcs12_data, base::string16(), false,
154                                    imported_certs));
155     ASSERT_EQ(1U, imported_certs->size());
156   }
157
158   CertLoader* cert_loader_;
159
160   // The user is primary as the one whose certificates CertLoader handles, it
161   // has nothing to do with crypto::InitializeNSSForChromeOSUser is_primary_user
162   // parameter (which is irrelevant for these tests).
163   crypto::ScopedTestNSSChromeOSUser primary_user_;
164   scoped_ptr<net::NSSCertDatabaseChromeOS> primary_db_;
165
166   base::MessageLoop message_loop_;
167
168  private:
169   size_t certificates_loaded_events_count_;
170 };
171
172 TEST_F(CertLoaderTest, Basic) {
173   EXPECT_FALSE(cert_loader_->CertificatesLoading());
174   EXPECT_FALSE(cert_loader_->certificates_loaded());
175   EXPECT_FALSE(cert_loader_->IsHardwareBacked());
176
177   FinishUserInitAndGetDatabase(&primary_user_, &primary_db_);
178
179   cert_loader_->StartWithNSSDB(primary_db_.get());
180
181   EXPECT_FALSE(cert_loader_->certificates_loaded());
182   EXPECT_TRUE(cert_loader_->CertificatesLoading());
183   EXPECT_TRUE(cert_loader_->cert_list().empty());
184
185   ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount());
186   base::RunLoop().RunUntilIdle();
187   EXPECT_EQ(1U, GetAndResetCertificatesLoadedEventsCount());
188
189   EXPECT_TRUE(cert_loader_->certificates_loaded());
190   EXPECT_FALSE(cert_loader_->CertificatesLoading());
191   EXPECT_EQ(GetDbPrivateSlotId(primary_db_.get()),
192             cert_loader_->TPMTokenSlotID());
193
194   // Default CA cert roots should get loaded.
195   EXPECT_FALSE(cert_loader_->cert_list().empty());
196 }
197
198 TEST_F(CertLoaderTest, CertLoaderUpdatesCertListOnNewCert) {
199   StartCertLoaderWithPrimaryUser();
200
201   net::CertificateList certs;
202   ImportCACert("root_ca_cert.pem", primary_db_.get(), &certs);
203
204   // Certs are loaded asynchronously, so the new cert should not yet be in the
205   // cert list.
206   EXPECT_FALSE(IsCertInCertificateList(certs[0], cert_loader_->cert_list()));
207
208   ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount());
209   base::RunLoop().RunUntilIdle();
210   EXPECT_EQ(1U, GetAndResetCertificatesLoadedEventsCount());
211
212   // The certificate list should be updated now, as the message loop's been run.
213   EXPECT_TRUE(IsCertInCertificateList(certs[0], cert_loader_->cert_list()));
214 }
215
216 TEST_F(CertLoaderTest, CertLoaderNoUpdateOnSecondaryDbChanges) {
217   crypto::ScopedTestNSSChromeOSUser secondary_user("secondary");
218   scoped_ptr<net::NSSCertDatabaseChromeOS> secondary_db;
219
220   StartCertLoaderWithPrimaryUser();
221   FinishUserInitAndGetDatabase(&secondary_user, &secondary_db);
222
223   net::CertificateList certs;
224   ImportCACert("root_ca_cert.pem", secondary_db.get(), &certs);
225
226   base::RunLoop().RunUntilIdle();
227
228   EXPECT_FALSE(IsCertInCertificateList(certs[0], cert_loader_->cert_list()));
229 }
230
231 TEST_F(CertLoaderTest, ClientLoaderUpdateOnNewClientCert) {
232   StartCertLoaderWithPrimaryUser();
233
234   net::CertificateList certs;
235   ImportClientCertAndKey("websocket_client_cert.p12",
236                          primary_db_.get(),
237                          &certs);
238
239   ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount());
240   base::RunLoop().RunUntilIdle();
241   EXPECT_EQ(1U, GetAndResetCertificatesLoadedEventsCount());
242
243   EXPECT_TRUE(IsCertInCertificateList(certs[0], cert_loader_->cert_list()));
244 }
245
246 TEST_F(CertLoaderTest, CertLoaderNoUpdateOnNewClientCertInSecondaryDb) {
247   crypto::ScopedTestNSSChromeOSUser secondary_user("secondary");
248   scoped_ptr<net::NSSCertDatabaseChromeOS> secondary_db;
249
250   StartCertLoaderWithPrimaryUser();
251   FinishUserInitAndGetDatabase(&secondary_user, &secondary_db);
252
253   net::CertificateList certs;
254   ImportClientCertAndKey("websocket_client_cert.p12",
255                          secondary_db.get(),
256                          &certs);
257
258   base::RunLoop().RunUntilIdle();
259
260   EXPECT_FALSE(IsCertInCertificateList(certs[0], cert_loader_->cert_list()));
261 }
262
263 TEST_F(CertLoaderTest, UpdatedOnCertRemoval) {
264   StartCertLoaderWithPrimaryUser();
265
266   net::CertificateList certs;
267   ImportClientCertAndKey("websocket_client_cert.p12",
268                          primary_db_.get(),
269                          &certs);
270
271   base::RunLoop().RunUntilIdle();
272
273   ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount());
274   ASSERT_TRUE(IsCertInCertificateList(certs[0], cert_loader_->cert_list()));
275
276   primary_db_->DeleteCertAndKey(certs[0]);
277
278   ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount());
279   base::RunLoop().RunUntilIdle();
280   EXPECT_EQ(1U, GetAndResetCertificatesLoadedEventsCount());
281
282   ASSERT_FALSE(IsCertInCertificateList(certs[0], cert_loader_->cert_list()));
283 }
284
285 TEST_F(CertLoaderTest, UpdatedOnCACertTrustChange) {
286   StartCertLoaderWithPrimaryUser();
287
288   net::CertificateList certs;
289   ImportCACert("root_ca_cert.pem", primary_db_.get(), &certs);
290
291   base::RunLoop().RunUntilIdle();
292   ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount());
293   ASSERT_TRUE(IsCertInCertificateList(certs[0], cert_loader_->cert_list()));
294
295   // The value that should have been set by |ImportCACert|.
296   ASSERT_EQ(net::NSSCertDatabase::TRUST_DEFAULT,
297             primary_db_->GetCertTrust(certs[0], net::CA_CERT));
298   ASSERT_TRUE(primary_db_->SetCertTrust(
299       certs[0], net::CA_CERT, net::NSSCertDatabase::TRUSTED_SSL));
300
301   // Cert trust change should trigger certificate reload in cert_loader_.
302   ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount());
303   base::RunLoop().RunUntilIdle();
304   EXPECT_EQ(1U, GetAndResetCertificatesLoadedEventsCount());
305 }
306
307 }  // namespace
308 }  // namespace chromeos