test_root_certs.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright (c) 2012 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 "net/cert/test_root_certs.h"
  5. #include <string>
  6. #include <utility>
  7. #include "net/cert/pki/cert_errors.h"
  8. #include "net/cert/x509_certificate.h"
  9. #include "net/cert/x509_util.h"
  10. #include "third_party/boringssl/src/include/openssl/pool.h"
  11. namespace net {
  12. namespace {
  13. bool g_has_instance = false;
  14. base::LazyInstance<TestRootCerts>::Leaky
  15. g_test_root_certs = LAZY_INSTANCE_INITIALIZER;
  16. } // namespace
  17. // static
  18. TestRootCerts* TestRootCerts::GetInstance() {
  19. return g_test_root_certs.Pointer();
  20. }
  21. bool TestRootCerts::HasInstance() {
  22. return g_has_instance;
  23. }
  24. bool TestRootCerts::Add(X509Certificate* certificate) {
  25. CertErrors errors;
  26. scoped_refptr<ParsedCertificate> parsed = ParsedCertificate::Create(
  27. bssl::UpRef(certificate->cert_buffer()),
  28. x509_util::DefaultParseCertificateOptions(), &errors);
  29. if (!parsed) {
  30. return false;
  31. }
  32. test_trust_store_.AddTrustAnchor(std::move(parsed));
  33. return AddImpl(certificate);
  34. }
  35. void TestRootCerts::Clear() {
  36. ClearImpl();
  37. test_trust_store_.Clear();
  38. }
  39. bool TestRootCerts::IsEmpty() const {
  40. return test_trust_store_.IsEmpty();
  41. }
  42. TestRootCerts::TestRootCerts() {
  43. Init();
  44. g_has_instance = true;
  45. }
  46. ScopedTestRoot::ScopedTestRoot() = default;
  47. ScopedTestRoot::ScopedTestRoot(X509Certificate* cert) {
  48. Reset({cert});
  49. }
  50. ScopedTestRoot::ScopedTestRoot(CertificateList certs) {
  51. Reset(std::move(certs));
  52. }
  53. ScopedTestRoot::ScopedTestRoot(ScopedTestRoot&& other) {
  54. *this = std::move(other);
  55. }
  56. ScopedTestRoot& ScopedTestRoot::operator=(ScopedTestRoot&& other) {
  57. CertificateList tmp_certs;
  58. tmp_certs.swap(other.certs_);
  59. Reset(std::move(tmp_certs));
  60. return *this;
  61. }
  62. ScopedTestRoot::~ScopedTestRoot() {
  63. Reset({});
  64. }
  65. void ScopedTestRoot::Reset(CertificateList certs) {
  66. if (!certs_.empty())
  67. TestRootCerts::GetInstance()->Clear();
  68. for (const auto& cert : certs)
  69. TestRootCerts::GetInstance()->Add(cert.get());
  70. certs_ = certs;
  71. }
  72. } // namespace net