security: Add trust anchor container

Change-Id: Ia527eee08b9e154eb2d3168182905ec082bd8441
Refs: #3292
diff --git a/src/security/v2/trust-anchor-container.cpp b/src/security/v2/trust-anchor-container.cpp
new file mode 100644
index 0000000..efb272f
--- /dev/null
+++ b/src/security/v2/trust-anchor-container.cpp
@@ -0,0 +1,119 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "trust-anchor-container.hpp"
+
+#include <boost/filesystem.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+
+void
+TrustAnchorContainer::AnchorContainer::add(Certificate&& cert)
+{
+  AnchorContainerBase::insert(std::move(cert));
+}
+
+void
+TrustAnchorContainer::AnchorContainer::remove(const Name& certName)
+{
+  AnchorContainerBase::erase(certName);
+}
+
+void
+TrustAnchorContainer::insert(const std::string& groupId, Certificate&& cert)
+{
+  auto group = m_groups.find(groupId);
+  if (group == m_groups.end()) {
+    std::tie(group, std::ignore) = m_groups.insert(make_shared<StaticTrustAnchorGroup>(m_anchors, groupId));
+  }
+  auto* staticGroup = dynamic_cast<StaticTrustAnchorGroup*>(&**group);
+  if (staticGroup == nullptr) {
+    BOOST_THROW_EXCEPTION(Error("Cannot add static anchor to a non-static anchor group " + groupId));
+  }
+  staticGroup->add(std::move(cert));
+}
+
+void
+TrustAnchorContainer::insert(const std::string& groupId, const boost::filesystem::path& path,
+                             time::nanoseconds refreshPeriod, bool isDir)
+{
+  if (m_groups.count(groupId) != 0) {
+    BOOST_THROW_EXCEPTION(Error("Cannot create dynamic group, because group " + groupId + " already exists"));
+  }
+
+  m_groups.insert(make_shared<DynamicTrustAnchorGroup>(m_anchors, groupId, path, refreshPeriod, isDir));
+}
+
+const Certificate*
+TrustAnchorContainer::find(const Name& keyName) const
+{
+  const_cast<TrustAnchorContainer*>(this)->refresh();
+
+  auto cert = m_anchors.lower_bound(keyName);
+  if (cert == m_anchors.end() || !keyName.isPrefixOf(cert->getName()))
+    return nullptr;
+  return &*cert;
+}
+
+const Certificate*
+TrustAnchorContainer::find(const Interest& interest) const
+{
+  const_cast<TrustAnchorContainer*>(this)->refresh();
+
+  for (auto cert = m_anchors.lower_bound(interest.getName());
+       cert != m_anchors.end() && interest.getName().isPrefixOf(cert->getName());
+       ++cert) {
+    if (interest.matchesData(*cert)) {
+      return &*cert;
+    }
+  }
+  return nullptr;
+}
+
+TrustAnchorGroup&
+TrustAnchorContainer::getGroup(const std::string& groupId) const
+{
+  auto group = m_groups.find(groupId);
+  if (group == m_groups.end()) {
+    BOOST_THROW_EXCEPTION(Error("Trust anchor group " + groupId + " does not exist"));
+  }
+  return **group;
+}
+
+size_t
+TrustAnchorContainer::size() const
+{
+  return m_anchors.size();
+}
+
+void
+TrustAnchorContainer::refresh()
+{
+  for (auto it = m_groups.begin(); it != m_groups.end(); ++it) {
+    m_groups.modify(it, [] (shared_ptr<TrustAnchorGroup>& group) { group->refresh(); });
+  }
+}
+
+} // namespace v2
+} // namespace security
+} // namespace ndn
diff --git a/src/security/v2/trust-anchor-container.hpp b/src/security/v2/trust-anchor-container.hpp
new file mode 100644
index 0000000..49e4999
--- /dev/null
+++ b/src/security/v2/trust-anchor-container.hpp
@@ -0,0 +1,177 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP
+#define NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP
+
+#include "trust-anchor-group.hpp"
+#include "certificate.hpp"
+#include "../../interest.hpp"
+
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/hashed_index.hpp>
+#include <boost/multi_index/ordered_index.hpp>
+#include <boost/multi_index/mem_fun.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+
+/**
+ * @brief represents a container for trust anchors.
+ *
+ * There are two kinds of anchors:
+ * - static anchors that are permanent for the lifetime of the container
+ * - dynamic anchors that are periodically updated.
+ *
+ * Trust anchors are organized in groups. Each group has a unique group id.  The same anchor
+ * certificate (same name without considering the implicit digest) can be inserted into
+ * multiple groups, but no more than once into each.
+ *
+ * Dynamic groups are created using the appropriate TrustAnchorContainer::insert method. Once
+ * created, the dynamic anchor group cannot be updated.
+ *
+ * The returned pointer to Certificate from `find` methods is only guaranteed to be valid until
+ * the next invocation of `find` and may be invalidated afterwards.
+ */
+class TrustAnchorContainer : noncopyable
+{
+public:
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+    }
+  };
+
+  /**
+   * @brief Insert a static trust anchor.
+   *
+   * @param groupId  Certificate group id.
+   * @param cert     Certificate to insert.
+   *
+   * If @p cert (same name without considering implicit digest) already exists in the group @p
+   * groupId, this method has no effect.
+   *
+   * @throw Error @p groupId is a dynamic anchor group .
+   */
+  void
+  insert(const std::string& groupId, Certificate&& cert);
+
+  /**
+   * @brief Insert dynamic trust anchors from path.
+   *
+   * @param groupId        Certificate group id, must not be empty.
+   * @param path           Specifies the path to load the trust anchors.
+   * @param refreshPeriod  Refresh period for the trust anchors, must be positive.
+   *                       Relevant trust anchors will only be updated when find is called
+   * @param isDir          Tells whether the path is a directory or a single file.
+   *
+   * @throw std::invalid_argument @p refreshPeriod is not positive
+   * @throw Error a group with @p groupId already exists
+   */
+  void
+  insert(const std::string& groupId, const boost::filesystem::path& path,
+         time::nanoseconds refreshPeriod, bool isDir = false);
+
+  /**
+   * @brief Search for certificate across all groups (longest prefix match)
+   * @param keyName  Key name prefix for searching the certificate.
+   * @return The found certificate, nullptr if not found.
+   *
+   * @note The returned value may be invalidated after next call to one of `find` methods.
+   */
+  const Certificate*
+  find(const Name& keyName) const;
+
+  /**
+   * @brief Find certificate given interest
+   * @param interest  The input interest packet.
+   * @return The found certificate, nullptr if not found.
+   *
+   * @note The returned value may be invalidated after next call to one of `find` methods.
+   *
+   * @note Interest with implicit digest is not supported.
+   *
+   * @note ChildSelector is not supported.
+   */
+  const Certificate*
+  find(const Interest& interest) const;
+
+  /**
+   * @brief Get trusted anchor group
+   * @throw Error @p groupId does not exist
+   */
+  TrustAnchorGroup&
+  getGroup(const std::string& groupId) const;
+
+  /**
+   * @brief Get number of trust anchors across all groups
+   */
+  size_t
+  size() const;
+
+private:
+  void
+  refresh();
+
+private:
+  using AnchorContainerBase = boost::multi_index::multi_index_container<
+    Certificate,
+    boost::multi_index::indexed_by<
+      boost::multi_index::ordered_unique<
+        boost::multi_index::const_mem_fun<Data, const Name&, &Data::getName>
+      >
+    >
+  >;
+
+  class AnchorContainer : public CertContainerInterface,
+                          public AnchorContainerBase
+  {
+  public:
+    void
+    add(Certificate&& cert) final;
+
+    void
+    remove(const Name& certName) final;
+  };
+
+  using GroupContainer = boost::multi_index::multi_index_container<
+    shared_ptr<TrustAnchorGroup>,
+    boost::multi_index::indexed_by<
+      boost::multi_index::hashed_unique<
+        boost::multi_index::const_mem_fun<TrustAnchorGroup, const std::string&, &TrustAnchorGroup::getId>
+      >
+    >
+  >;
+
+  GroupContainer m_groups;
+  AnchorContainer m_anchors;
+};
+
+} // namespace v2
+} // namespace security
+} // namespace ndn
+
+#endif // NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP
diff --git a/src/security/v2/trust-anchor-group.cpp b/src/security/v2/trust-anchor-group.cpp
new file mode 100644
index 0000000..6b94951
--- /dev/null
+++ b/src/security/v2/trust-anchor-group.cpp
@@ -0,0 +1,143 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "trust-anchor-group.hpp"
+
+#include "util/io.hpp"
+#include "util/logger.hpp"
+
+#include <set>
+#include <boost/filesystem.hpp>
+#include <boost/range/adaptor/map.hpp>
+#include <boost/range/algorithm/copy.hpp>
+#include <boost/range/iterator_range.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+
+NDN_LOG_INIT(ndn.security.v2.TrustAnchorGroup);
+
+namespace fs = boost::filesystem;
+
+TrustAnchorGroup::TrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id)
+  : m_certs(certContainer)
+  , m_id(id)
+{
+}
+
+size_t
+TrustAnchorGroup::size() const
+{
+  return m_anchorNames.size();
+}
+
+void
+TrustAnchorGroup::refresh()
+{
+  // base method does nothing
+}
+
+//////////////
+
+StaticTrustAnchorGroup::StaticTrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id)
+  : TrustAnchorGroup(certContainer, id)
+{
+}
+
+void
+StaticTrustAnchorGroup::add(Certificate&& cert)
+{
+  if (m_anchorNames.count(cert.getName()) != 0) {
+    return;
+  }
+
+  m_anchorNames.insert(cert.getName());
+  m_certs.add(std::move(cert));
+}
+
+void
+StaticTrustAnchorGroup::remove(const Name& certName)
+{
+  m_anchorNames.erase(certName);
+  m_certs.remove(certName);
+}
+
+/////////////
+
+DynamicTrustAnchorGroup::DynamicTrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id,
+                                                 const boost::filesystem::path& path,
+                                                 time::nanoseconds refreshPeriod, bool isDir)
+  : TrustAnchorGroup(certContainer, id)
+  , m_isDir(isDir)
+  , m_path(path)
+  , m_refreshPeriod(refreshPeriod)
+{
+  if (refreshPeriod <= time::nanoseconds::zero()) {
+    BOOST_THROW_EXCEPTION(std::runtime_error("Refresh period for the dynamic group must be positive"));
+  }
+
+  refresh();
+}
+
+void
+DynamicTrustAnchorGroup::refresh()
+{
+  if (m_expireTime > time::steady_clock::now()) {
+    return;
+  }
+  m_expireTime = time::steady_clock::now() + m_refreshPeriod;
+  NDN_LOG_TRACE("Reloading dynamic trust anchor group");
+
+  std::set<Name> oldAnchorNames = m_anchorNames;
+
+  auto loadCert = [this, &oldAnchorNames] (const fs::path& file) {
+    auto cert = io::load<Certificate>(file.string());
+    if (cert != nullptr) {
+      if (m_anchorNames.count(cert->getName()) == 0) {
+        m_anchorNames.insert(cert->getName());
+        m_certs.add(std::move(*cert));
+      }
+      else {
+        oldAnchorNames.erase(cert->getName());
+      }
+    }
+  };
+
+  if (!m_isDir) {
+    loadCert(m_path);
+  }
+  else {
+    if (fs::exists(m_path)) {
+      std::for_each(fs::directory_iterator(m_path), fs::directory_iterator(), loadCert);
+    }
+  }
+
+  // remove old certs
+  for (const auto& oldAnchorName : oldAnchorNames) {
+    m_anchorNames.erase(oldAnchorName);
+    m_certs.remove(oldAnchorName);
+  }
+}
+
+} // namespace v2
+} // namespace security
+} // namespace ndn
diff --git a/src/security/v2/trust-anchor-group.hpp b/src/security/v2/trust-anchor-group.hpp
new file mode 100644
index 0000000..356a2a3
--- /dev/null
+++ b/src/security/v2/trust-anchor-group.hpp
@@ -0,0 +1,164 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_SECURITY_V2_TRUST_ANCHOR_GROUP_HPP
+#define NDN_SECURITY_V2_TRUST_ANCHOR_GROUP_HPP
+
+#include "../../data.hpp"
+#include "certificate.hpp"
+
+#include <set>
+#include <boost/filesystem/path.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+
+class CertContainerInterface
+{
+public:
+  virtual void
+  add(Certificate&& cert) = 0;
+
+  virtual void
+  remove(const Name& certName) = 0;
+};
+
+/**
+ * @brief A group of trust anchors
+ */
+class TrustAnchorGroup : noncopyable
+{
+public:
+  /**
+   * @brief Create an anchor group
+   */
+  explicit
+  TrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id);
+
+  /**
+   * @return group id
+   */
+  const std::string&
+  getId() const
+  {
+    return m_id;
+  }
+
+  /**
+   * @return number of certificates in the group
+   */
+  size_t
+  size() const;
+
+  /**
+   * @brief Request certificate refresh
+   */
+  virtual void
+  refresh();
+
+protected:
+  CertContainerInterface& m_certs;
+  std::set<Name> m_anchorNames;
+
+private:
+  std::string m_id;
+};
+
+/**
+ * @brief Static trust anchor group
+ */
+class StaticTrustAnchorGroup : public TrustAnchorGroup
+{
+public:
+  /**
+   * @brief Create a static trust anchor group
+   * @param certContainer  Reference to CertContainerInterface instance
+   * @param id             Group id
+   */
+  StaticTrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id);
+
+  /**
+   * @brief Load static anchor @p cert
+   */
+  void
+  add(Certificate&& cert);
+
+  /**
+   * @brief Remove static anchor @p certName
+   */
+  void
+  remove(const Name& certName);
+};
+
+/**
+ * @brief Dynamic trust anchor group
+ */
+class DynamicTrustAnchorGroup : public TrustAnchorGroup
+{
+public:
+  /**
+   * @brief Create a dynamic trust anchor group
+   *
+   * This contructor would load all the certificates from @p path and will be refreshing
+   * certificates every @p refreshPeriod time period.
+   *
+   * Note that refresh is not scheduled, but is performed upon "find" operations.
+   *
+   * When @p isDir is false and @p path doesn't point to a valid certificate (file doesn't
+   * exist or content is not a valid certificate), the dynamic anchor group will be empty until
+   * file gets created.  If file disappears or gets corrupted, the anchor group becomes empty.
+   *
+   * When @p idDir is true and @p path does't point to a valid folder, folder is empty, or
+   * doesn't contain valid certificates, the group will be empty until certificate files are
+   * placed in the folder.  If folder is removed, becomes empty, or no longer contains valid
+   * certificates, the anchor group becomes empty.
+   *
+   * Upon refresh, the existing certificates are not changed.
+   *
+   * @param certContainer  A certificate container into which trust anchors from the group will
+   *                       be added
+   * @param id             Group id
+   * @param path           File path for trust anchor(s), could be directory or file. If it is a
+   *                       directory, all the certificates in the directory will be loaded.
+   * @param refreshPeriod  Refresh time for the anchors under @p path, must be positive.
+   * @param isDir          Tells whether the path is a directory or a single file.
+   *
+   * @throw std::invalid_argument @p refreshPeriod is negative
+   */
+  DynamicTrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id,
+                          const boost::filesystem::path& path, time::nanoseconds refreshPeriod, bool isDir = false);
+
+  void
+  refresh() override;
+
+private:
+  bool m_isDir;
+  boost::filesystem::path m_path;
+  time::nanoseconds m_refreshPeriod;
+  time::steady_clock::TimePoint m_expireTime;
+};
+
+} // namespace v2
+} // namespace security
+} // namespace ndn
+
+#endif // NDN_SECURITY_V2_TRUST_ANCHOR_GROUP_HPP
diff --git a/tests/identity-management-fixture.cpp b/tests/identity-management-fixture.cpp
index cb2a6de..b924024 100644
--- a/tests/identity-management-fixture.cpp
+++ b/tests/identity-management-fixture.cpp
@@ -150,13 +150,38 @@
   description.set("type", "sub-certificate");
   info.appendTypeSpecificTlv(description.wireEncode());
 
-  request.setSignature(Signature(info));
-
-  m_keyChain.sign(request, signingByIdentity(issuer));
+  m_keyChain.sign(request, signingByIdentity(issuer).setSignatureInfo(info));
   m_keyChain.setDefaultCertificate(subIdentity.getDefaultKey(), request);
 
   return subIdentity;
 }
 
+v2::Certificate
+IdentityManagementV2Fixture::addCertificate(const security::Key& key, const std::string& issuer)
+{
+  Name certificateName = key.getName();
+  certificateName
+    .append(issuer)
+    .appendVersion();
+  v2::Certificate certificate;
+  certificate.setName(certificateName);
+
+  // set metainfo
+  certificate.setContentType(tlv::ContentType_Key);
+  certificate.setFreshnessPeriod(time::hours(1));
+
+  // set content
+  certificate.setContent(key.getPublicKey().buf(), key.getPublicKey().size());
+
+  // set signature-info
+  SignatureInfo info;
+  info.setValidityPeriod(security::ValidityPeriod(time::system_clock::now(),
+                                                  time::system_clock::now() + time::days(10)));
+
+  m_keyChain.sign(certificate, signingByKey(key).setSignatureInfo(info));
+  return certificate;
+}
+
+
 } // namespace tests
 } // namespace ndn
diff --git a/tests/identity-management-fixture.hpp b/tests/identity-management-fixture.hpp
index 5c55073..a6b348f 100644
--- a/tests/identity-management-fixture.hpp
+++ b/tests/identity-management-fixture.hpp
@@ -132,6 +132,12 @@
   addSubCertificate(const Name& subIdentityName, const security::Identity& issuer,
                     const KeyParams& params = security::v2::KeyChain::getDefaultKeyParams());
 
+  /**
+   * @brief Add a self-signed certificate to @p key with issuer ID @p issuer
+   */
+  security::v2::Certificate
+  addCertificate(const security::Key& key, const std::string& issuer);
+
 protected:
   security::v2::KeyChain m_keyChain;
 };
diff --git a/tests/unit-tests/security/v2/trust-anchor-container.t.cpp b/tests/unit-tests/security/v2/trust-anchor-container.t.cpp
new file mode 100644
index 0000000..0efecdc
--- /dev/null
+++ b/tests/unit-tests/security/v2/trust-anchor-container.t.cpp
@@ -0,0 +1,198 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "security/v2/trust-anchor-container.hpp"
+
+#include "../../identity-management-time-fixture.hpp"
+#include "util/io.hpp"
+#include "boost-test.hpp"
+#include <boost/filesystem.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+namespace tests {
+
+using namespace ndn::tests;
+
+BOOST_AUTO_TEST_SUITE(Security)
+BOOST_AUTO_TEST_SUITE(V2)
+
+/**
+ * This fixture creates a directory and prepares two certificates.
+ * cert1 is written to a file under the directory, while cert2 is not.
+ */
+class AnchorContainerTestFixture : public IdentityManagementTimeFixture
+{
+public:
+  AnchorContainerTestFixture()
+  {
+    boost::filesystem::create_directory(boost::filesystem::path(UNIT_TEST_CONFIG_PATH));
+
+    certDirPath = boost::filesystem::path(UNIT_TEST_CONFIG_PATH) / std::string("test-cert-dir");
+    boost::filesystem::create_directory(certDirPath);
+
+    certPath1 = boost::filesystem::path(UNIT_TEST_CONFIG_PATH) /
+      std::string("test-cert-dir") / std::string("trust-anchor-1.cert");
+
+    certPath2 = boost::filesystem::path(UNIT_TEST_CONFIG_PATH) /
+      std::string("test-cert-dir") / std::string("trust-anchor-2.cert");
+
+    identity1 = addIdentity("/TestAnchorContainer/First");
+    cert1 = identity1.getDefaultKey().getDefaultCertificate();
+    saveCertToFile(cert1, certPath1.string());
+
+    identity2 = addIdentity("/TestAnchorContainer/Second");
+    cert2 = identity2.getDefaultKey().getDefaultCertificate();
+    saveCertToFile(cert2, certPath2.string());
+  }
+
+  ~AnchorContainerTestFixture()
+  {
+    boost::filesystem::remove_all(UNIT_TEST_CONFIG_PATH);
+  }
+
+public:
+  TrustAnchorContainer anchorContainer;
+
+  boost::filesystem::path certDirPath;
+  boost::filesystem::path certPath1;
+  boost::filesystem::path certPath2;
+
+  Identity identity1;
+  Identity identity2;
+
+  Certificate cert1;
+  Certificate cert2;
+};
+
+BOOST_FIXTURE_TEST_SUITE(TestTrustAnchorContainer, AnchorContainerTestFixture)
+
+// one static group and one dynamic group created from file
+BOOST_AUTO_TEST_CASE(Insert)
+{
+  // Static
+  anchorContainer.insert("group1", Certificate(cert1));
+  BOOST_CHECK(anchorContainer.find(cert1.getName()) != nullptr);
+  BOOST_CHECK(anchorContainer.find(identity1.getName()) != nullptr);
+  const Certificate* cert = anchorContainer.find(cert1.getName());
+  BOOST_CHECK_NO_THROW(anchorContainer.insert("group1", Certificate(cert1)));
+  BOOST_CHECK_EQUAL(cert, anchorContainer.find(cert1.getName())); // still the same instance of the certificate
+  // cannot add dynamic group when static already exists
+  BOOST_CHECK_THROW(anchorContainer.insert("group1", certPath1.string(), time::seconds(1)), TrustAnchorContainer::Error);
+  BOOST_CHECK_EQUAL(anchorContainer.getGroup("group1").size(), 1);
+  BOOST_CHECK_EQUAL(anchorContainer.size(), 1);
+
+  // From file
+  anchorContainer.insert("group2", certPath2.string(), time::seconds(1));
+  BOOST_CHECK(anchorContainer.find(cert2.getName()) != nullptr);
+  BOOST_CHECK(anchorContainer.find(identity2.getName()) != nullptr);
+  BOOST_CHECK_THROW(anchorContainer.insert("group2", Certificate(cert2)), TrustAnchorContainer::Error);
+  BOOST_CHECK_THROW(anchorContainer.insert("group2", certPath2.string(), time::seconds(1)), TrustAnchorContainer::Error);
+  BOOST_CHECK_EQUAL(anchorContainer.getGroup("group2").size(), 1);
+  BOOST_CHECK_EQUAL(anchorContainer.size(), 2);
+
+  boost::filesystem::remove(certPath2);
+  advanceClocks(time::seconds(1), 11);
+
+  BOOST_CHECK(anchorContainer.find(identity2.getName()) == nullptr);
+  BOOST_CHECK(anchorContainer.find(cert2.getName()) == nullptr);
+  BOOST_CHECK_EQUAL(anchorContainer.getGroup("group2").size(), 0);
+  BOOST_CHECK_EQUAL(anchorContainer.size(), 1);
+
+  TrustAnchorGroup& group = anchorContainer.getGroup("group1");
+  auto staticGroup = dynamic_cast<StaticTrustAnchorGroup*>(&group);
+  BOOST_REQUIRE(staticGroup != nullptr);
+  BOOST_CHECK_EQUAL(staticGroup->size(), 1);
+  staticGroup->remove(cert1.getName());
+  BOOST_CHECK_EQUAL(staticGroup->size(), 0);
+  BOOST_CHECK_EQUAL(anchorContainer.size(), 0);
+
+  BOOST_CHECK_THROW(anchorContainer.getGroup("non-existing-group"), TrustAnchorContainer::Error);
+}
+
+BOOST_AUTO_TEST_CASE(DynamicAnchorFromDir)
+{
+  boost::filesystem::remove(certPath2);
+
+  anchorContainer.insert("group", certDirPath.string(), time::seconds(1), true /* isDir */);
+
+  BOOST_CHECK(anchorContainer.find(identity1.getName()) != nullptr);
+  BOOST_CHECK(anchorContainer.find(identity2.getName()) == nullptr);
+  BOOST_CHECK_EQUAL(anchorContainer.getGroup("group").size(), 1);
+
+  saveCertToFile(cert2, certPath2.string());
+
+  advanceClocks(time::milliseconds(100), 11);
+
+  BOOST_CHECK(anchorContainer.find(identity1.getName()) != nullptr);
+  BOOST_CHECK(anchorContainer.find(identity2.getName()) != nullptr);
+  BOOST_CHECK_EQUAL(anchorContainer.getGroup("group").size(), 2);
+
+  boost::filesystem::remove_all(certDirPath);
+
+  advanceClocks(time::milliseconds(100), 11);
+
+  BOOST_CHECK(anchorContainer.find(identity1.getName()) == nullptr);
+  BOOST_CHECK(anchorContainer.find(identity2.getName()) == nullptr);
+  BOOST_CHECK_EQUAL(anchorContainer.getGroup("group").size(), 0);
+}
+
+BOOST_FIXTURE_TEST_CASE(FindByInterest, AnchorContainerTestFixture)
+{
+  anchorContainer.insert("group1", certPath1.string(), time::seconds(1));
+  Interest interest(identity1.getName());
+  BOOST_CHECK(anchorContainer.find(interest) != nullptr);
+  Interest interest1(identity1.getName().getPrefix(-1));
+  BOOST_CHECK(anchorContainer.find(interest1) != nullptr);
+  Interest interest2(Name(identity1.getName()).appendVersion());
+  BOOST_CHECK(anchorContainer.find(interest2) == nullptr);
+
+  Certificate cert3 = addCertificate(identity1.getDefaultKey(), "3");
+  Certificate cert4 = addCertificate(identity1.getDefaultKey(), "4");
+  Certificate cert5 = addCertificate(identity1.getDefaultKey(), "5");
+
+  Certificate cert3Copy = cert3;
+  anchorContainer.insert("group2", std::move(cert3Copy));
+  anchorContainer.insert("group3", std::move(cert4));
+  anchorContainer.insert("group4", std::move(cert5));
+
+  Interest interest3(cert3.getKeyName());
+  const Certificate* foundCert = anchorContainer.find(interest3);
+  BOOST_REQUIRE(foundCert != nullptr);
+  BOOST_CHECK(interest3.getName().isPrefixOf(foundCert->getName()));
+  BOOST_CHECK_EQUAL(foundCert->getName(), cert3.getName());
+
+  interest3.setExclude(Exclude().excludeOne(cert3.getName().at(Certificate::ISSUER_ID_OFFSET)));
+  foundCert = anchorContainer.find(interest3);
+  BOOST_REQUIRE(foundCert != nullptr);
+  BOOST_CHECK(interest3.getName().isPrefixOf(foundCert->getName()));
+  BOOST_CHECK_NE(foundCert->getName(), cert3.getName());
+}
+
+BOOST_AUTO_TEST_SUITE_END() // TestTrustAnchorContainer
+BOOST_AUTO_TEST_SUITE_END() // Detail
+BOOST_AUTO_TEST_SUITE_END() // Security
+
+} // namespace tests
+} // namespace v2
+} // namespace security
+} // namespace ndn