security: Add ValidityPeriod abstraction

Change-Id: I6fbe2541a2a8bb90513441f0ef8297d0c8007455
Refs: #2868
diff --git a/src/encoding/tlv.hpp b/src/encoding/tlv.hpp
index 78564d8..1c4851a 100644
--- a/src/encoding/tlv.hpp
+++ b/src/encoding/tlv.hpp
@@ -99,6 +99,16 @@
   SignatureSha256WithEcdsa = 3
 };
 
+/** @brief TLV codes for SignatureInfo features
+ *  @sa docs/tutorials/certificate-format.rst
+ */
+enum {
+  // SignatureInfo TLVs
+  ValidityPeriod = 253,
+  NotBefore = 254,
+  NotAfter = 255
+};
+
 /** @brief indicates a possible value of ContentType field
  */
 enum ContentTypeValue {
diff --git a/src/security/validity-period.cpp b/src/security/validity-period.cpp
new file mode 100644
index 0000000..008cd3c
--- /dev/null
+++ b/src/security/validity-period.cpp
@@ -0,0 +1,172 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2015 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 "validity-period.hpp"
+#include "../encoding/block-helpers.hpp"
+#include "../util/concepts.hpp"
+
+namespace ndn {
+namespace security {
+
+BOOST_CONCEPT_ASSERT((boost::EqualityComparable<ValidityPeriod>));
+BOOST_CONCEPT_ASSERT((WireEncodable<ValidityPeriod>));
+BOOST_CONCEPT_ASSERT((WireEncodableWithEncodingBuffer<ValidityPeriod>));
+BOOST_CONCEPT_ASSERT((WireDecodable<ValidityPeriod>));
+static_assert(std::is_base_of<tlv::Error, ValidityPeriod::Error>::value,
+              "ValidityPeriod::Error must inherit from tlv::Error");
+
+static const size_t ISO_DATETIME_SIZE = 15;
+static const size_t NOT_BEFORE_OFFSET = 0;
+static const size_t NOT_AFTER_OFFSET = 1;
+
+using boost::chrono::time_point_cast;
+
+ValidityPeriod::ValidityPeriod(const time::system_clock::TimePoint& notBefore,
+                               const time::system_clock::TimePoint& notAfter)
+  : m_notBefore(time_point_cast<TimePoint::duration>(notBefore + TimePoint::duration(1) -
+                                                     time::system_clock::TimePoint::duration(1)))
+  , m_notAfter(time_point_cast<TimePoint::duration>(notAfter))
+{
+}
+
+ValidityPeriod::ValidityPeriod(const Block& block)
+{
+  wireDecode(block);
+}
+
+template<encoding::Tag TAG>
+size_t
+ValidityPeriod::wireEncode(EncodingImpl<TAG>& encoder) const
+{
+  size_t totalLength = 0;
+
+  totalLength += prependStringBlock(encoder, tlv::NotAfter, time::toIsoString(m_notAfter));
+  totalLength += prependStringBlock(encoder, tlv::NotBefore, time::toIsoString(m_notBefore));
+
+  totalLength += encoder.prependVarNumber(totalLength);
+  totalLength += encoder.prependVarNumber(tlv::ValidityPeriod);
+  return totalLength;
+}
+
+template size_t
+ValidityPeriod::wireEncode<encoding::EncoderTag>(EncodingImpl<encoding::EncoderTag>& encoder) const;
+
+template size_t
+ValidityPeriod::wireEncode<encoding::EstimatorTag>(EncodingImpl<encoding::EstimatorTag>& encoder) const;
+
+const Block&
+ValidityPeriod::wireEncode() const
+{
+  if (m_wire.hasWire())
+    return m_wire;
+
+  EncodingEstimator estimator;
+  size_t estimatedSize = wireEncode(estimator);
+
+  EncodingBuffer buffer(estimatedSize, 0);
+  wireEncode(buffer);
+
+  m_wire = buffer.block();
+  m_wire.parse();
+
+  return m_wire;
+}
+
+void
+ValidityPeriod::wireDecode(const Block& wire)
+{
+  if (!wire.hasWire()) {
+    throw Error("The supplied block does not contain wire format");
+  }
+
+  m_wire = wire;
+  m_wire.parse();
+
+  if (m_wire.type() != tlv::ValidityPeriod)
+    throw Error("Unexpected TLV type when decoding ValidityPeriod");
+
+  if (m_wire.elements_size() != 2)
+    throw Error("Does not have two sub-TLVs");
+
+  if (m_wire.elements()[NOT_BEFORE_OFFSET].type() != tlv::NotBefore ||
+      m_wire.elements()[NOT_BEFORE_OFFSET].value_size() != ISO_DATETIME_SIZE ||
+      m_wire.elements()[NOT_AFTER_OFFSET].type() != tlv::NotAfter ||
+      m_wire.elements()[NOT_AFTER_OFFSET].value_size() != ISO_DATETIME_SIZE) {
+    throw Error("Invalid NotBefore or NotAfter field");
+  }
+
+  try {
+    m_notBefore = time_point_cast<TimePoint::duration>(
+                    time::fromIsoString(readString(m_wire.elements()[NOT_BEFORE_OFFSET])));
+    m_notAfter = time_point_cast<TimePoint::duration>(
+                   time::fromIsoString(readString(m_wire.elements()[NOT_AFTER_OFFSET])));
+  }
+  catch (const std::bad_cast&) {
+    throw Error("Invalid date format in NOT-BEFORE or NOT-AFTER field");
+  }
+}
+
+ValidityPeriod&
+ValidityPeriod::setPeriod(const time::system_clock::TimePoint& notBefore,
+                          const time::system_clock::TimePoint& notAfter)
+{
+  m_wire.reset();
+  m_notBefore = time_point_cast<TimePoint::duration>(notBefore + TimePoint::duration(1) -
+                                                     time::system_clock::TimePoint::duration(1));
+  m_notAfter = time_point_cast<TimePoint::duration>(notAfter);
+  return *this;
+}
+
+std::pair<time::system_clock::TimePoint, time::system_clock::TimePoint>
+ValidityPeriod::getPeriod() const
+{
+  return std::make_pair(m_notBefore, m_notAfter);
+}
+
+bool
+ValidityPeriod::isValid(const time::system_clock::TimePoint& now) const
+{
+  return m_notBefore < now && now < m_notAfter;
+}
+
+bool
+ValidityPeriod::operator==(const ValidityPeriod& other) const
+{
+  return (this->m_notBefore == other.m_notBefore &&
+          this->m_notAfter == other.m_notAfter);
+}
+
+bool
+ValidityPeriod::operator!=(const ValidityPeriod& other) const
+{
+  return !(*this == other);
+}
+
+std::ostream&
+operator<<(std::ostream& os, const ValidityPeriod& period)
+{
+  os << "(" << time::toIsoString(period.getPeriod().first)
+     << ", " << time::toIsoString(period.getPeriod().second) << ")";
+  return os;
+}
+
+} // namespace security
+} // namespace ndn
diff --git a/src/security/validity-period.hpp b/src/security/validity-period.hpp
new file mode 100644
index 0000000..ab24d68
--- /dev/null
+++ b/src/security/validity-period.hpp
@@ -0,0 +1,134 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2015 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_VALIDITY_PERIOD_HPP
+#define NDN_SECURITY_VALIDITY_PERIOD_HPP
+
+#include "../common.hpp"
+#include "../encoding/tlv.hpp"
+#include "../encoding/block.hpp"
+#include "../util/time.hpp"
+
+namespace ndn {
+namespace security {
+
+
+/** @brief Abstraction of validity period
+ *  @sa docs/tutorials/certificate-format.rst
+ */
+class ValidityPeriod
+{
+public:
+  class Error : public tlv::Error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : tlv::Error(what)
+    {
+    }
+  };
+
+public:
+  /** @brief Set validity period (UNIX epoch, UNIX epoch) that is always invalid
+   */
+  ValidityPeriod() = default;
+
+  /** @brief Create validity period from @p block
+   */
+  explicit
+  ValidityPeriod(const Block& block);
+
+  /** @brief Create validity period (@p notBefore, @p notAfter)
+   *  @param notBefore exclusive beginning of the validity period range
+   *  @param notAfter exclusive end of the validity period range
+   *
+   *  @note The supplied time points will be rounded up to the whole seconds:
+   *        - @p notBefore is rounded up the next whole second
+   *        - @p notAfter is truncated to the previous whole second
+   */
+  ValidityPeriod(const time::system_clock::TimePoint& notBefore,
+                 const time::system_clock::TimePoint& notAfter);
+
+  /** @brief Check if @p now falls within the validity period
+   *  @param now Time point to check if it falls within the period
+   *  @return periodBegin < @p now and @p now < periodEnd
+   */
+  bool
+  isValid(const time::system_clock::TimePoint& now = time::system_clock::now()) const;
+
+  /** @brief Set validity period (@p notBefore, @p notAfter)
+   *  @param notBefore exclusive beginning of the validity period range
+   *  @param notAfter exclusive end of the validity period range
+   *
+   *  @note The supplied time points will be rounded up to the whole seconds:
+   *        - @p notBefore is rounded up the next whole second
+   *        - @p notAfter is truncated to the previous whole second
+   */
+  ValidityPeriod&
+  setPeriod(const time::system_clock::TimePoint& notBefore,
+            const time::system_clock::TimePoint& notAfter);
+
+  /** @brief Get the stored validity period
+   */
+  std::pair<time::system_clock::TimePoint, time::system_clock::TimePoint>
+  getPeriod() const;
+
+  /** @brief Fast encoding or block size estimation
+   */
+  template<encoding::Tag TAG>
+  size_t
+  wireEncode(EncodingImpl<TAG>& encoder) const;
+
+  /** @brief Encode ValidityPeriod into TLV block
+   */
+  const Block&
+  wireEncode() const;
+
+  /** @brief Decode ValidityPeriod from TLV block
+   *  @throw Error when an invalid TLV block supplied
+   */
+  void
+  wireDecode(const Block& wire);
+
+public: // EqualityComparable concept
+  bool
+  operator==(const ValidityPeriod& other) const;
+
+  bool
+  operator!=(const ValidityPeriod& other) const;
+
+private:
+  typedef boost::chrono::time_point<time::system_clock, time::seconds> TimePoint;
+
+  TimePoint m_notBefore;
+  TimePoint m_notAfter;
+
+  mutable Block m_wire;
+};
+
+std::ostream&
+operator<<(std::ostream& os, const ValidityPeriod& period);
+
+} // namespace security
+} // namespace ndn
+
+#endif // NDN_SECURITY_VALIDITY_PERIOD_HPP
diff --git a/tests/unit-tests/security/validity-period.t.cpp b/tests/unit-tests/security/validity-period.t.cpp
new file mode 100644
index 0000000..be5b2e4
--- /dev/null
+++ b/tests/unit-tests/security/validity-period.t.cpp
@@ -0,0 +1,191 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2015 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/validity-period.hpp"
+
+#include "boost-test.hpp"
+#include <boost/lexical_cast.hpp>
+
+namespace ndn {
+namespace security {
+namespace test {
+
+BOOST_AUTO_TEST_SUITE(SecurityValidityPeriod)
+
+BOOST_AUTO_TEST_CASE(ConstructorSetter)
+{
+  time::system_clock::TimePoint notBefore = time::system_clock::now() - time::days(1);
+  time::system_clock::TimePoint notAfter = notBefore + time::days(2);
+
+  ValidityPeriod validity1 = ValidityPeriod(notBefore, notAfter);
+
+  auto period = validity1.getPeriod();
+  BOOST_CHECK_GE(period.first, notBefore); // fractional seconds will be removed
+  BOOST_CHECK_LT(period.first, notBefore + time::seconds(1));
+
+  BOOST_CHECK_LE(period.second, notAfter); // fractional seconds will be removed
+  BOOST_CHECK_GT(period.second, notAfter - time::seconds(1));
+  BOOST_CHECK_EQUAL(validity1.isValid(), true);
+
+  BOOST_CHECK_EQUAL(ValidityPeriod(time::system_clock::now() - time::days(2),
+                                   time::system_clock::now() - time::days(1)).isValid(),
+                    false);
+
+  BOOST_CHECK_NO_THROW((ValidityPeriod()));
+  ValidityPeriod validity2;
+  BOOST_CHECK(validity2.getPeriod() == std::make_pair(time::getUnixEpoch(), time::getUnixEpoch()));
+
+  validity2.setPeriod(notBefore, notAfter);
+  BOOST_CHECK(validity2.getPeriod() != std::make_pair(time::getUnixEpoch(), time::getUnixEpoch()));
+  BOOST_CHECK_EQUAL(validity2, validity1);
+
+  validity1.setPeriod(time::getUnixEpoch(), time::getUnixEpoch() + time::days(10 * 365));
+  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(validity1),
+                    "(19700101T000000, 19791230T000000)");
+
+  validity1.setPeriod(time::getUnixEpoch() + time::nanoseconds(1),
+                      time::getUnixEpoch() + time::days(10 * 365) + time::nanoseconds(1));
+  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(validity1),
+                    "(19700101T000001, 19791230T000000)");
+}
+
+const uint8_t VP1[] = {
+  0xfd, 0x00, 0xfd, 0x26, // ValidityPeriod
+    0xfd, 0x00, 0xfe, 0x0f, // NotBefore
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, // 19700101T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+    0xfd, 0x00, 0xff, 0x0f, // NotAfter
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x32, // 19700102T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30
+};
+
+BOOST_AUTO_TEST_CASE(EncodingDecoding)
+{
+  time::system_clock::TimePoint notBefore = time::getUnixEpoch();
+  time::system_clock::TimePoint notAfter = notBefore + time::days(1);
+
+  ValidityPeriod v1(notBefore, notAfter);
+
+  BOOST_CHECK_EQUAL_COLLECTIONS(v1.wireEncode().begin(), v1.wireEncode().end(),
+                                VP1, VP1 + sizeof(VP1));
+
+  BOOST_REQUIRE_NO_THROW(ValidityPeriod(Block(VP1, sizeof(VP1))));
+  Block block(VP1, sizeof(VP1));
+  ValidityPeriod v2(block);
+  BOOST_CHECK(v1.getPeriod() == v2.getPeriod());
+}
+
+const uint8_t VP_E1[] = {
+  0xfd, 0x00, 0xff, 0x26, // ValidityPeriod (error)
+    0xfd, 0x00, 0xfe, 0x0f, // NotBefore
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, // 19700101T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+    0xfd, 0x00, 0xff, 0x0f, // NotAfter
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x32, // 19700102T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30
+};
+
+const uint8_t VP_E2[] = {
+  0xfd, 0x00, 0xfd, 0x26, // ValidityPeriod
+    0xfd, 0x00, 0xff, 0x0f, // NotBefore (error)
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, // 19700101T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+    0xfd, 0x00, 0xff, 0x0f, // NotAfter
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x32, // 19700102T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30
+};
+
+const uint8_t VP_E3[] = {
+  0xfd, 0x00, 0xfd, 0x26, // ValidityPeriod
+    0xfd, 0x00, 0xfe, 0x0f, // NotBefore
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, // 19700101T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+    0xfd, 0x00, 0xfe, 0x0f, // NotAfter (error)
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x32, // 19700102T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30
+};
+
+const uint8_t VP_E4[] = {
+  0xfd, 0x00, 0xfd, 0x39, // ValidityPeriod
+    0xfd, 0x00, 0xfe, 0x0f, // NotBefore
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, // 19700101T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+    0xfd, 0x00, 0xff, 0x0f, // NotAfter
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x32, // 19700102T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+    0xfd, 0x00, 0xff, 0x0f, // NotAfter (error)
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x32, // 19700102T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30
+};
+
+const uint8_t VP_E5[] = {
+  0xfd, 0x00, 0xfd, 0x13, // ValidityPeriod
+    0xfd, 0x00, 0xfe, 0x0f, // NotBefore
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, // 19700101T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30
+};
+
+const uint8_t VP_E6[] = {
+  0xfd, 0x00, 0xfd, 0x26, // ValidityPeriod
+    0xfd, 0x00, 0xfe, 0x0f, // NotBefore
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, // 19700101T00000\xFF
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0xFF,
+    0xfd, 0x00, 0xff, 0x0f, // NotAfter
+      0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x32, // 19700102T000000
+      0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30
+};
+
+
+BOOST_AUTO_TEST_CASE(DecodingError)
+{
+  BOOST_CHECK_THROW(ValidityPeriod(Block(VP_E1, sizeof(VP_E1))), ValidityPeriod::Error);
+
+  BOOST_CHECK_THROW(ValidityPeriod(Block(VP_E2, sizeof(VP_E2))), ValidityPeriod::Error);
+  BOOST_CHECK_THROW(ValidityPeriod(Block(VP_E3, sizeof(VP_E3))), ValidityPeriod::Error);
+
+  BOOST_CHECK_THROW(ValidityPeriod(Block(VP_E4, sizeof(VP_E4))), ValidityPeriod::Error);
+  BOOST_CHECK_THROW(ValidityPeriod(Block(VP_E5, sizeof(VP_E5))), ValidityPeriod::Error);
+
+  Block emptyBlock;
+  BOOST_CHECK_THROW((ValidityPeriod(emptyBlock)), ValidityPeriod::Error);
+
+  BOOST_CHECK_THROW(ValidityPeriod(Block(VP_E6, sizeof(VP_E6))), ValidityPeriod::Error);
+}
+
+BOOST_AUTO_TEST_CASE(Comparison)
+{
+  time::system_clock::TimePoint notBefore = time::getUnixEpoch();
+  time::system_clock::TimePoint notAfter = notBefore + time::days(1);
+  time::system_clock::TimePoint notAfter2 = notBefore + time::days(2);
+
+  ValidityPeriod validity1(notBefore, notAfter);
+  ValidityPeriod validity2(notBefore, notAfter);
+  BOOST_CHECK(validity1 == validity2);
+
+  ValidityPeriod validity3(notBefore, notAfter2);
+  BOOST_CHECK(validity1 != validity3);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+} // namespace test
+} // namespace security
+} // namespace ndn