Add CertificateRequest

Change-Id: I3e2b5f306b58ce0de31db04a90d69b4182a0ac3b
diff --git a/src/certificate-request.cpp b/src/certificate-request.cpp
new file mode 100644
index 0000000..80b5a45
--- /dev/null
+++ b/src/certificate-request.cpp
@@ -0,0 +1,104 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation, either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * ndncert 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 General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "certificate-request.hpp"
+#include <ndn-cxx/util/indented-stream.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+CertificateRequest::CertificateRequest(const Name& caName,
+                                       const std::string& requestId,
+                                       const security::v2::Certificate& cert)
+  : m_caName(caName)
+  , m_requestId(requestId)
+  , m_status(Pending)
+  , m_cert(static_cast<const Data&>(cert))
+{
+}
+
+CertificateRequest::CertificateRequest(const Name& caName,
+                                       const std::string& requestId,
+                                       const ApplicationStatus& status,
+                                       const std::string& challengeType,
+                                       const std::string& challengeStatus,
+                                       const std::string& challengeDefinedField,
+                                       const security::v2::Certificate& cert)
+  : m_caName(caName)
+  , m_requestId(requestId)
+  , m_status(status)
+  , m_challengeType(challengeType)
+  , m_challengeStatus(challengeStatus)
+  , m_challengeDefinedField(challengeDefinedField)
+  , m_cert(static_cast<const Data&>(cert))
+{
+}
+
+std::ostream&
+operator<<(std::ostream& os, CertificateRequest::ApplicationStatus status)
+{
+  std::string statusString;
+  switch (status) {
+    case CertificateRequest::Pending: {
+      statusString = "pending";
+      break;
+    }
+    case CertificateRequest::Verifying: {
+      statusString = "verifying";
+      break;
+    }
+    case CertificateRequest::Success: {
+      statusString = "success";
+      break;
+    }
+    case CertificateRequest::Failure: {
+      statusString = "failure";
+      break;
+    }
+  }
+  os << statusString;
+  return os;
+}
+
+std::ostream&
+operator<<(std::ostream& os, const CertificateRequest& request)
+{
+  os << "Request CA name:\n";
+  os << "  " << request.getCaName() << "\n";
+  os << "Request ID:\n";
+  os << "  " << request.getRequestId() << "\n";
+  os << "Request Status:\n";
+  os << "  " << request.getStatus() << "\n";
+  if (request.getChallengeType() != "") {
+    os << "Request Challenge Type:\n";
+    os << "  " << request.getChallengeType() << "\n";
+  }
+  if (request.getChallengeStatus() != "") {
+    os << "Request Challenge Status:\n";
+    os << "  " << request.getChallengeStatus() << "\n";
+  }
+  os << "Certificate:\n";
+  util::IndentedStream os2(os, "  ");
+  os2 << request.getCert();
+  return os;
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/certificate-request.hpp b/src/certificate-request.hpp
new file mode 100644
index 0000000..b8d1ccd
--- /dev/null
+++ b/src/certificate-request.hpp
@@ -0,0 +1,177 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation, either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * ndncert 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 General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_CERTFICATE_REQUEST_HPP
+#define NDNCERT_CERTFICATE_REQUEST_HPP
+
+#include "ndncert-common.hpp"
+#include <ndn-cxx/security/v2/certificate.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+/**
+ * @brief Represents a certificate request instance.
+ *
+ * ChallengeModule should take use of m_challengeStatus, m_challengeInstruction and
+ * m_challengeDefinedField to finish verification.
+ *
+ */
+class CertificateRequest
+{
+public:
+  enum ApplicationStatus {
+    Pending = 0,
+    Verifying = 1,
+    Success = 2,
+    Failure = 3
+  };
+
+public:
+  CertificateRequest(const Name& caName, const std::string& requestId,
+                     const security::v2::Certificate& cert);
+
+  CertificateRequest(const Name& caName, const std::string& requestId,
+                     const ApplicationStatus& status, const std::string& challengeType,
+                     const std::string& challengeStatus, const std::string& challengeDefinedField,
+                     const security::v2::Certificate& certBlock);
+
+  const Name&
+  getCaName() const
+  {
+    return m_caName;
+  }
+
+  const std::string&
+  getRequestId() const
+  {
+    return m_requestId;
+  }
+
+  const ApplicationStatus&
+  getStatus() const
+  {
+    return m_status;
+  }
+
+  const std::string&
+  getChallengeType() const
+  {
+    return m_challengeType;
+  }
+
+  const std::string&
+  getChallengeDefinedField() const
+  {
+    return m_challengeDefinedField;
+  }
+
+  const std::string&
+  getChallengeInstruction() const
+  {
+    return m_challengeInstruction;
+  }
+
+  const std::string&
+  getChallengeStatus() const
+  {
+    return m_challengeStatus;
+  }
+
+  const security::v2::Certificate&
+  getCert() const
+  {
+    return m_cert;
+  }
+
+  /**
+   * These setters should only be invoked by ChallengeModule
+   */
+  void
+  setStatus(const ApplicationStatus& status)
+  {
+    m_status = status;
+  }
+
+  void
+  setChallengeType(const std::string& challengeType)
+  {
+    m_challengeType = challengeType;
+  }
+
+  void
+  setChallengeStatus(const std::string& challengeStatus)
+  {
+    m_challengeStatus = challengeStatus;
+  }
+
+  void
+  setChallengeDefinedField(const std::string& challengeDefinedField)
+  {
+    m_challengeDefinedField = challengeDefinedField;
+  }
+
+  void
+  setChallengeInstruction(const std::string& challengeInstruction)
+  {
+    m_challengeInstruction = challengeInstruction;
+  }
+
+private:
+  Name m_caName;
+  std::string m_requestId;
+  ApplicationStatus m_status;
+  std::string m_challengeType;
+
+  /**
+   * @brief Defined by ChallengeModule to indicate the verification status.
+   *
+   * This field will be stored by CA.
+   */
+  std::string m_challengeStatus;
+
+  /**
+   * @brief Defined by ChallengeModule to store secret information.
+   *
+   * This field will be stored by CA.
+   */
+  std::string m_challengeDefinedField;
+
+  /**
+   * @brief Defined by ChallengeModule to indicate end entity the next step.
+   *
+   * This field will be presented to end entity.
+   * This field will NOT be stored by CA.
+   */
+  std::string m_challengeInstruction;
+
+  security::v2::Certificate m_cert;
+};
+
+std::ostream&
+operator<<(std::ostream& os, CertificateRequest::ApplicationStatus status);
+
+std::ostream&
+operator<<(std::ostream& os, const CertificateRequest& request);
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_CERTFICATE_REQUEST_HPP
diff --git a/tests/identity-management-fixture.cpp b/tests/identity-management-fixture.cpp
index b9d6d41..30d00d8 100644
--- a/tests/identity-management-fixture.cpp
+++ b/tests/identity-management-fixture.cpp
@@ -90,6 +90,95 @@
   }
 }
 
+IdentityManagementV2Fixture::IdentityManagementV2Fixture()
+  : m_keyChain("pib-memory:", "tpm-memory:")
+{
+}
+
+security::Identity
+IdentityManagementV2Fixture::addIdentity(const Name& identityName, const KeyParams& params)
+{
+  auto identity = m_keyChain.createIdentity(identityName, params);
+  m_identities.insert(identityName);
+  return identity;
+}
+
+bool
+IdentityManagementV2Fixture::saveIdentityCertificate(const security::Identity& identity,
+                                                     const std::string& filename)
+{
+  try {
+    auto cert = identity.getDefaultKey().getDefaultCertificate();
+    return saveCertToFile(cert, filename);
+  }
+  catch (const security::Pib::Error&) {
+    return false;
+  }
+}
+
+security::Identity
+IdentityManagementV2Fixture::addSubCertificate(const Name& subIdentityName,
+                                               const security::Identity& issuer, const KeyParams& params)
+{
+  auto subIdentity = addIdentity(subIdentityName, params);
+
+  security::v2::Certificate request = subIdentity.getDefaultKey().getDefaultCertificate();
+
+  request.setName(request.getKeyName().append("parent").appendVersion());
+
+  SignatureInfo info;
+  info.setValidityPeriod(security::ValidityPeriod(time::system_clock::now(),
+                                                  time::system_clock::now() + time::days(7300)));
+
+  security::v2::AdditionalDescription description;
+  description.set("type", "sub-certificate");
+  info.appendTypeSpecificTlv(description.wireEncode());
+
+  m_keyChain.sign(request, signingByIdentity(issuer).setSignatureInfo(info));
+  m_keyChain.setDefaultCertificate(subIdentity.getDefaultKey(), request);
+
+  return subIdentity;
+}
+
+security::v2::Certificate
+IdentityManagementV2Fixture::addCertificate(const security::Key& key, const std::string& issuer)
+{
+  Name certificateName = key.getName();
+  certificateName
+    .append(issuer)
+    .appendVersion();
+  security::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;
+}
+
+bool
+IdentityManagementV2Fixture::saveCertToFile(const Data& obj, const std::string& filename)
+{
+  m_certFiles.insert(filename);
+  try {
+    io::save(obj, filename);
+    return true;
+  }
+  catch (const io::Error&) {
+    return false;
+  }
+}
+
 } // namespace tests
 } // namespace ndncert
 } // namespace ndn
diff --git a/tests/identity-management-fixture.hpp b/tests/identity-management-fixture.hpp
index 29eeede..9c9a4b5 100644
--- a/tests/identity-management-fixture.hpp
+++ b/tests/identity-management-fixture.hpp
@@ -29,8 +29,10 @@
 #define NDNCERT_TESTS_IDENTITY_MANAGEMENT_FIXTURE_HPP
 
 #include "test-common.hpp"
-
 #include <ndn-cxx/security/key-chain.hpp>
+#include <ndn-cxx/security/v2/key-chain.hpp>
+#include <ndn-cxx/security/v2/additional-description.hpp>
+#include <ndn-cxx/security/signing-helpers.hpp>
 
 namespace ndn {
 namespace ndncert {
@@ -71,6 +73,61 @@
   std::vector<std::string> m_certFiles;
 };
 
+/**
+ * @brief A test suite level fixture to help with identity management
+ *
+ * Test cases in the suite can use this fixture to create identities.  Identities,
+ * certificates, and saved certificates are automatically removed during test teardown.
+ */
+class IdentityManagementV2Fixture
+{
+public:
+  IdentityManagementV2Fixture();
+
+  /**
+   * @brief Add identity @p identityName
+   * @return name of the created self-signed certificate
+   */
+  security::Identity
+  addIdentity(const Name& identityName, const KeyParams& params = security::v2::KeyChain::getDefaultKeyParams());
+
+  /**
+   *  @brief Save identity certificate to a file
+   *  @param identity identity
+   *  @param filename file name, should be writable
+   *  @return whether successful
+   */
+  bool
+  saveIdentityCertificate(const security::Identity& identity, const std::string& filename);
+
+  /**
+   * @brief Issue a certificate for \p subIdentityName signed by \p issuer
+   *
+   *  If identity does not exist, it is created.
+   *  A new key is generated as the default key for identity.
+   *  A default certificate for the key is signed by the issuer using its default certificate.
+   *
+   *  @return the sub identity
+   */
+  security::Identity
+  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);
+
+  bool
+  saveCertToFile(const Data& obj, const std::string& filename);
+
+protected:
+  std::set<Name> m_identities;
+  std::set<std::string> m_certFiles;
+  security::v2::KeyChain m_keyChain;
+};
+
 /** \brief convenience base class for inheriting from both UnitTestTimeFixture
  *         and IdentityManagementFixture
  */
diff --git a/tests/unit-tests/certificate-request.t.cpp b/tests/unit-tests/certificate-request.t.cpp
new file mode 100644
index 0000000..113748d
--- /dev/null
+++ b/tests/unit-tests/certificate-request.t.cpp
@@ -0,0 +1,134 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation, either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * ndncert 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 General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "identity-management-fixture.hpp"
+#include "certificate-request.hpp"
+#include <boost/lexical_cast.hpp>
+#include <ndn-cxx/util/io.hpp>
+
+namespace ndn {
+namespace ndncert {
+namespace tests {
+
+BOOST_FIXTURE_TEST_SUITE(TestCertificateRequest, IdentityManagementV2Fixture)
+
+BOOST_AUTO_TEST_CASE(Constructor)
+{
+  auto identity = addIdentity(Name("/ndn/site1"));
+  auto key = identity.getDefaultKey();
+  auto cert = key.getDefaultCertificate();
+
+  CertificateRequest request1(Name("/ndn/site1"), "123", cert);
+  BOOST_CHECK_EQUAL(request1.getCaName().toUri(), "/ndn/site1");
+  BOOST_CHECK_EQUAL(request1.getRequestId(), "123");
+  BOOST_CHECK_EQUAL(request1.getStatus(), CertificateRequest::Pending);
+  BOOST_CHECK_EQUAL(request1.getChallengeType(), "");
+  BOOST_CHECK_EQUAL(request1.getChallengeStatus(), "");
+  BOOST_CHECK_EQUAL(request1.getChallengeDefinedField(), "");
+  BOOST_CHECK_EQUAL(request1.getChallengeInstruction(), "");
+  BOOST_CHECK_EQUAL(request1.getCert(), cert);
+
+  CertificateRequest request2(Name("/ndn/site1"), "123", CertificateRequest::Verifying,
+                              "Email", "NEED_CODE", "123456", cert);
+  BOOST_CHECK_EQUAL(request2.getCaName().toUri(), "/ndn/site1");
+  BOOST_CHECK_EQUAL(request2.getRequestId(), "123");
+  BOOST_CHECK_EQUAL(request2.getStatus(), CertificateRequest::Verifying);
+  BOOST_CHECK_EQUAL(request2.getChallengeType(), "Email");
+  BOOST_CHECK_EQUAL(request2.getChallengeStatus(), "NEED_CODE");
+  BOOST_CHECK_EQUAL(request2.getChallengeDefinedField(), "123456");
+  BOOST_CHECK_EQUAL(request2.getChallengeInstruction(), "");
+  BOOST_CHECK_EQUAL(request2.getCert(), cert);
+}
+
+BOOST_AUTO_TEST_CASE(GetStatusOutput)
+{
+  CertificateRequest::ApplicationStatus status = CertificateRequest::Success;
+  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(status), "success");
+}
+
+BOOST_AUTO_TEST_CASE(GetterSetter)
+{
+  auto identity = addIdentity(Name("/ndn/site1"));
+  auto key = identity.getDefaultKey();
+  auto cert = key.getDefaultCertificate();
+
+  CertificateRequest request(Name("/ndn/site1"), "123", cert);
+  request.setStatus(CertificateRequest::Verifying);
+  request.setChallengeType("Email");
+  request.setChallengeDefinedField("456");
+  request.setChallengeStatus("NEED_EMAIL");
+  request.setChallengeInstruction("Please provide your email address");
+
+  BOOST_CHECK_EQUAL(request.getStatus(), CertificateRequest::Verifying);
+  BOOST_CHECK_EQUAL(request.getChallengeType(), "Email");
+  BOOST_CHECK_EQUAL(request.getChallengeDefinedField(), "456");
+  BOOST_CHECK_EQUAL(request.getChallengeStatus(), "NEED_EMAIL");
+  BOOST_CHECK_EQUAL(request.getChallengeInstruction(), "Please provide your email address");
+}
+
+BOOST_AUTO_TEST_CASE(GetCertificateRequestOutput)
+{
+  const std::string certString = R"_CERT_(
+Bv0BuwczCANuZG4IBXNpdGUxCANLRVkIEWtzay0xNDE2NDI1Mzc3MDk0CAQwMTIz
+CAf9AAABScmLFAkYAQIZBAA27oAVoDCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcC
+gYEAngY+R4WyNDeqhUesAySDtZyoBTokHuuJAbvpm7LDIqxo4/BsAs5opsTQpwaQ
+nKobCB2LQ5ozZ0RtIaMbiJqXXlnEFQvZLL1RB2GCrcG417+bz30kwmPzlxfr/mIl
+ultNisJ6vUOKj7jy8cVqMNNQjMia3+/tNed6Yup2fLsIJscCAREWVRsBARwmByQI
+A25kbggFc2l0ZTEIA0tFWQgRa3NrLTI1MTY0MjUzNzcwOTT9AP0m/QD+DzIwMTUw
+ODE0VDIyMzczOf0A/w8yMDE1MDgxOFQyMjM3MzgXgP//////////////////////
+////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////
+////////////////////)_CERT_";
+
+  const std::string expectedString = R"_REQUEST_(Request CA name:
+  /ndn/site1
+Request ID:
+  123
+Request Status:
+  pending
+Certificate:
+  Certificate name:
+    /ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B
+  Validity:
+    NotBefore: 20150814T223739
+    NotAfter: 20150818T223738
+  Public key bits:
+    MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCeBj5HhbI0N6qFR6wDJIO1nKgF
+    OiQe64kBu+mbssMirGjj8GwCzmimxNCnBpCcqhsIHYtDmjNnRG0hoxuImpdeWcQV
+    C9ksvVEHYYKtwbjXv5vPfSTCY/OXF+v+YiW6W02Kwnq9Q4qPuPLxxWow01CMyJrf
+    7+0153pi6nZ8uwgmxwIBEQ==
+  Signature Information:
+    Signature Type: SignatureSha256WithRsa
+    Key Locator: Name=/ndn/site1/KEY/ksk-2516425377094
+)_REQUEST_";
+
+  std::stringstream ss;
+  ss << certString;
+  auto cert = io::load<security::v2::Certificate>(ss);
+  CertificateRequest request(Name("/ndn/site1"), "123", *cert);
+
+  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(request), expectedString);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+} // namespace tests
+} // namespace ndncert
+} // namespace ndn