scoped_test_nss_db.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. #include "crypto/scoped_test_nss_db.h"
  5. #include <cert.h>
  6. #include "base/logging.h"
  7. #include "base/threading/thread_restrictions.h"
  8. #include "crypto/nss_util.h"
  9. #include "crypto/nss_util_internal.h"
  10. namespace crypto {
  11. ScopedTestNSSDB::ScopedTestNSSDB() {
  12. EnsureNSSInit();
  13. // NSS is allowed to do IO on the current thread since dispatching
  14. // to a dedicated thread would still have the affect of blocking
  15. // the current thread, due to NSS's internal locking requirements
  16. base::ScopedAllowBlockingForTesting allow_blocking;
  17. if (!temp_dir_.CreateUniqueTempDir())
  18. return;
  19. const char kTestDescription[] = "Test DB";
  20. slot_ = OpenSoftwareNSSDB(temp_dir_.GetPath(), kTestDescription);
  21. }
  22. ScopedTestNSSDB::~ScopedTestNSSDB() {
  23. // Remove trust from any certs in the test DB before closing it. Otherwise NSS
  24. // may cache verification results even after the test DB is gone.
  25. RemoveTrustFromAllCerts();
  26. // NSS is allowed to do IO on the current thread since dispatching
  27. // to a dedicated thread would still have the affect of blocking
  28. // the current thread, due to NSS's internal locking requirements
  29. base::ScopedAllowBlockingForTesting allow_blocking;
  30. if (slot_) {
  31. SECStatus status = CloseSoftwareNSSDB(slot_.get());
  32. if (status != SECSuccess)
  33. PLOG(ERROR) << "CloseSoftwareNSSDB failed: " << PORT_GetError();
  34. }
  35. if (!temp_dir_.Delete())
  36. LOG(ERROR) << "Could not delete temporary directory.";
  37. }
  38. void ScopedTestNSSDB::RemoveTrustFromAllCerts() {
  39. if (!slot_)
  40. return;
  41. CERTCertList* cert_list = PK11_ListCertsInSlot(slot_.get());
  42. if (!cert_list)
  43. return;
  44. for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
  45. !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) {
  46. CERTCertTrust trust = {0};
  47. if (CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), node->cert, &trust) !=
  48. SECSuccess) {
  49. LOG(ERROR) << "CERT_ChangeCertTrust failed: " << PORT_GetError();
  50. }
  51. }
  52. CERT_DestroyCertList(cert_list);
  53. }
  54. } // namespace crypto