>From 53036f19348c0d4232bad91fa4c6681ab399d268 Mon Sep 17 00:00:00 2001
From: Ade Lee <alee@redhat.com>
Date: Fri, 16 Aug 2013 13:14:05 -0400
Subject: [PATCH] Add TPS self tests

Added self tests analogous to the tests previously performed
inthe C subsystem.
---
 base/common/src/LogMessages.properties             |   7 +
 base/common/src/UserMessages.properties            |   2 +
 .../src/com/netscape/cmscore/cert/CertUtils.java   |  14 +-
 base/tps-tomcat/shared/conf/CS.cfg.in              |   8 +-
 .../org/dogtagpki/tps/selftests/TPSPresence.java   | 187 +++++++++++++++++++
 .../org/dogtagpki/tps/selftests/TPSValidity.java   | 197 +++++++++++++++++++++
 .../src/org/dogtagpki/tps/server/TPSSubsystem.java |  16 ++
 7 files changed, 422 insertions(+), 9 deletions(-)
 create mode 100644 base/tps-tomcat/src/org/dogtagpki/tps/selftests/TPSPresence.java
 create mode 100644 base/tps-tomcat/src/org/dogtagpki/tps/selftests/TPSValidity.java

diff --git a/base/common/src/LogMessages.properties b/base/common/src/LogMessages.properties
index 550df1b5e94002f7dc0d246900adf9b73e91f52b..67ca3695727eab64df1bba5c3a72ef6d7431e5fd 100644
--- a/base/common/src/LogMessages.properties
+++ b/base/common/src/LogMessages.properties
@@ -2464,6 +2464,13 @@ SELFTESTS_RA_IS_CORRUPT={0}:  RA public key is corrupt
 SELFTESTS_RA_IS_PRESENT={0}:  RA is present
 SELFTESTS_TKS_FAILED={0}:  TKS self test called {1} FAILED!
 SELFTESTS_TKS_SUCCEEDED={0}:  TKS self test called {1} ran SUCCESSFULLY
+SELFTESTS_TPS_IS_NOT_PRESENT={0}:  TPS is NOT present
+SELFTESTS_TPS_IS_NOT_INITIALIZED={0}:  TPS is NOT yet initialized
+SELFTESTS_TPS_IS_CORRUPT={0}:  TPS public key is corrupt
+SELFTESTS_TPS_IS_PRESENT={0}:  TPS is present
+SELFTESTS_TPS_IS_NOT_YET_VALID={0}:  TPS is not yet valid
+SELFTESTS_TPS_IS_EXPIRED={0}:  TPS is expired
+SELFTESTS_TPS_IS_VALID={0}:  TPS is valid
 SELFTESTS_RUN_ON_DEMAND_REQUEST={0}:  the passed in request parameter {1}, used to invoke running self tests on-demand, was missing
 SELFTESTS_RUN_ON_DEMAND={0}:  Running self test plugins specified to be executed on-demand:
 SELFTESTS_NOT_RUN_ON_DEMAND={0}:  There were NO self test plugins specified to be run on-demand!
diff --git a/base/common/src/UserMessages.properties b/base/common/src/UserMessages.properties
index 4bc2115ec8e9605fbe3a2ae7c96f3a4ebd267137..f2f1de51278b34dca0e4c5050d8bcf0e2d1f4501 100644
--- a/base/common/src/UserMessages.properties
+++ b/base/common/src/UserMessages.properties
@@ -1086,6 +1086,8 @@ CMS_SELFTESTS_OCSP_VALIDITY_DESCRIPTION=This self test is used to check whether
 CMS_SELFTESTS_RA_PRESENCE_DESCRIPTION=This self test is used to check whether or not the RA is present.
 CMS_SELFTESTS_KRA_PRESENCE_DESCRIPTION=This self test is used to check whether or not the KRA is present.
 CMS_SELFTESTS_TKS_PRESENCE_DESCRIPTION=This self test is used to check whether or not the TKS is present.
+CMS_SELFTESTS_TPS_PRESENCE_DESCRIPTION=This self test is used to check whether or not the TPS is present.
+CMS_SELFTESTS_TPS_VALIDITY_DESCRIPTION=This self test is used to check whether or not the TKS is valid.
 #######################################################
 # ACL
 #
diff --git a/base/common/src/com/netscape/cmscore/cert/CertUtils.java b/base/common/src/com/netscape/cmscore/cert/CertUtils.java
index 37444eff58aa046b1f971758dac8272b9e3f8e4c..6d7acd96d94ac7f39615011fd445a9f4a8b6b756 100644
--- a/base/common/src/com/netscape/cmscore/cert/CertUtils.java
+++ b/base/common/src/com/netscape/cmscore/cert/CertUtils.java
@@ -1081,18 +1081,18 @@ public class CertUtils {
     }
 
     public static String toLowerCaseSubsystemType(String s) {
-        String x = null;
         if (s.equalsIgnoreCase("CA")) {
-            x = "ca";
+            return "ca";
         } else if (s.equalsIgnoreCase("KRA")) {
-            x = "kra";
+            return "kra";
         } else if (s.equalsIgnoreCase("OCSP")) {
-            x = "ocsp";
+            return "ocsp";
         } else if (s.equalsIgnoreCase("TKS")) {
-            x = "tks";
+            return "tks";
+        } else if (s.equalsIgnoreCase("TPS")) {
+            return "tps";
         }
-
-        return x;
+        return null;
     }
 
     /**
diff --git a/base/tps-tomcat/shared/conf/CS.cfg.in b/base/tps-tomcat/shared/conf/CS.cfg.in
index 1a392a11972156d58e9bece2552679e18b231a3f..97ff61c22c2874acbfd45df41ba4afb58f1ba748 100644
--- a/base/tps-tomcat/shared/conf/CS.cfg.in
+++ b/base/tps-tomcat/shared/conf/CS.cfg.in
@@ -1380,6 +1380,8 @@ selftests._005=## tps.cert.list = <list of cert tag names deliminated by ",">
 selftests._006=## tps.cert.<cert tag name>.nickname
 selftests._007=## tps.cert.<cert tag name>.certusage
 selftests._008=##
+selftests.container.instance.TPSPresence=org.dogtagpki.tps.selftests.TPSPresence
+selftests.container.instance.TPSValidity=org.dogtagpki.tps.selftests.TPSValidity
 selftests.container.instance.SystemCertsVerification=com.netscape.cms.selftests.common.SystemCertsVerification
 selftests.container.logger.bufferSize=512
 selftests.container.logger.class=com.netscape.cms.logging.RollingLogFile
@@ -1392,8 +1394,10 @@ selftests.container.logger.maxFileSize=2000
 selftests.container.logger.register=false
 selftests.container.logger.rolloverInterval=2592000
 selftests.container.logger.type=transaction
-selftests.container.order.onDemand=SystemCertsVerification:critical
-selftests.container.order.startup=SystemCertsVerification:critical
+selftests.container.order.onDemand=TPSPresence:critical, SystemCertsVerification:critical, TPSValidity:critical
+selftests.container.order.startup=TPSPresence:critical, SystemCertsVerification:critical
+selftests.plugin.TPSPresence.TpsSubId=tps
+selftests.plugin.TPSValidity.TpsSubId=tps
 selftests.plugin.SystemCertsVerification.SubId=tps
 service.instanceDir=[PKI_INSTANCE_ROOT]
 service.instanceID=[PKI_INSTANCE_NAME]
diff --git a/base/tps-tomcat/src/org/dogtagpki/tps/selftests/TPSPresence.java b/base/tps-tomcat/src/org/dogtagpki/tps/selftests/TPSPresence.java
new file mode 100644
index 0000000000000000000000000000000000000000..e940e100333a6c28ea773b91775dbf251b723415
--- /dev/null
+++ b/base/tps-tomcat/src/org/dogtagpki/tps/selftests/TPSPresence.java
@@ -0,0 +1,187 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program 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; version 2 of the License.
+//
+// This program 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 a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package org.dogtagpki.tps.selftests;
+
+import java.security.PublicKey;
+import java.util.Locale;
+
+import org.dogtagpki.tps.server.TPSSubsystem;
+
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.base.EBaseException;
+import com.netscape.certsrv.base.IConfigStore;
+import com.netscape.certsrv.logging.ILogEventListener;
+import com.netscape.certsrv.selftests.EDuplicateSelfTestException;
+import com.netscape.certsrv.selftests.EInvalidSelfTestException;
+import com.netscape.certsrv.selftests.EMissingSelfTestException;
+import com.netscape.certsrv.selftests.ESelfTestException;
+import com.netscape.certsrv.selftests.ISelfTestSubsystem;
+import com.netscape.cms.selftests.ASelfTest;
+
+/**
+ * This class implements a self test to check for TPS presence.
+ * <P>
+ *
+ * @author alee
+ * @version $Revision$, $Date$
+ */
+public class TPSPresence extends ASelfTest {
+
+    public static final String PROP_TPS_SUB_ID = "TpsSubId";
+    private String tpsSubId = null;
+
+    /**
+     * Initializes this subsystem with the configuration store
+     * associated with this instance name.
+     * <P>
+     *
+     * @param subsystem the associated subsystem
+     * @param instanceName the name of this self test instance
+     * @param parameters configuration store (self test parameters)
+     * @exception EDuplicateSelfTestException subsystem has duplicate name/value
+     * @exception EInvalidSelfTestException subsystem has invalid name/value
+     * @exception EMissingSelfTestException subsystem has missing name/value
+     */
+    public void initSelfTest(ISelfTestSubsystem subsystem, String instanceName,
+            IConfigStore parameters) throws EDuplicateSelfTestException, EInvalidSelfTestException,
+            EMissingSelfTestException {
+        super.initSelfTest(subsystem, instanceName, parameters);
+
+        try {
+            tpsSubId = mConfig.getString(PROP_TPS_SUB_ID);
+            if (tpsSubId != null) {
+                tpsSubId = tpsSubId.trim();
+            } else {
+                mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
+                        CMS.getLogMessage("SELFTESTS_MISSING_VALUES", getSelfTestName(),
+                                mPrefix + "." + PROP_TPS_SUB_ID));
+
+                throw new EMissingSelfTestException(PROP_TPS_SUB_ID);
+            }
+        } catch (EBaseException e) {
+            mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
+                    CMS.getLogMessage("SELFTESTS_MISSING_NAME", getSelfTestName(),
+                            mPrefix + "." + PROP_TPS_SUB_ID));
+
+            throw new EMissingSelfTestException(mPrefix, PROP_TPS_SUB_ID, null);
+        }
+    }
+
+    /**
+     * Notifies this subsystem if it is in execution mode.
+     * <P>
+     *
+     * @exception ESelfTestException failed to start
+     */
+    public void startupSelfTest() throws ESelfTestException {
+    }
+
+    /**
+     * Stops this subsystem. The subsystem may call shutdownSelfTest
+     * anytime after initialization.
+     * <P>
+     */
+    public void shutdownSelfTest() {
+    }
+
+    /**
+     * Returns the name associated with this self test. This method may
+     * return null if the self test has not been initialized.
+     * <P>
+     *
+     * @return instanceName of this self test
+     */
+    public String getSelfTestName() {
+        return super.getSelfTestName();
+    }
+
+    /**
+     * Returns the root configuration storage (self test parameters)
+     * associated with this subsystem.
+     * <P>
+     *
+     * @return configuration store (self test parameters) of this subsystem
+     */
+    public IConfigStore getSelfTestConfigStore() {
+        return super.getSelfTestConfigStore();
+    }
+
+    /**
+     * Retrieves description associated with an individual self test.
+     * This method may return null.
+     * <P>
+     *
+     * @param locale locale of the client that requests the description
+     * @return description of self test
+     */
+    public String getSelfTestDescription(Locale locale) {
+        return CMS.getUserMessage(locale,
+                "CMS_SELFTESTS_TPS_PRESENCE_DESCRIPTION");
+    }
+
+    /**
+     * Execute an individual self test.
+     * <P>
+     *
+     * @param logger specifies logging subsystem
+     * @exception ESelfTestException self test exception
+     */
+    public void runSelfTest(ILogEventListener logger)
+            throws ESelfTestException {
+        String logMessage = null;
+        TPSSubsystem tps = (TPSSubsystem) CMS.getSubsystem(tpsSubId);
+        if (tps == null) {
+            // log that the TPS is not installed
+            logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_NOT_PRESENT", getSelfTestName());
+            mSelfTestSubsystem.log(logger, logMessage);
+            throw new ESelfTestException(logMessage);
+        } else {
+            // Retrieve the TPS certificate
+            org.mozilla.jss.crypto.X509Certificate tpsCert = null;
+            try {
+                tpsCert = tps.getSubsystemCert();
+            } catch (Exception e) {
+                e.printStackTrace();
+                // cert does not exist or is not yet configured
+                // tpsCert will remain null
+            }
+
+            if (tpsCert == null) {
+                // log that the TPS is not yet initialized
+                logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_NOT_INITIALIZED",
+                        getSelfTestName());
+                mSelfTestSubsystem.log(logger, logMessage);
+                throw new ESelfTestException(logMessage);
+            }
+
+            // Retrieve the TPS certificate public key
+            PublicKey tpsPubKey = tpsCert.getPublicKey();
+            if (tpsPubKey == null) {
+                // log that something is seriously wrong with the TPS
+                logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_CORRUPT", getSelfTestName());
+                mSelfTestSubsystem.log(logger, logMessage);
+                throw new ESelfTestException(logMessage);
+            }
+
+            // log that the TPS is present
+            logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_PRESENT", getSelfTestName());
+            mSelfTestSubsystem.log(logger, logMessage);
+        }
+    }
+}
diff --git a/base/tps-tomcat/src/org/dogtagpki/tps/selftests/TPSValidity.java b/base/tps-tomcat/src/org/dogtagpki/tps/selftests/TPSValidity.java
new file mode 100644
index 0000000000000000000000000000000000000000..e128e246c29269c1f8e42fde24d96592a3b7eb86
--- /dev/null
+++ b/base/tps-tomcat/src/org/dogtagpki/tps/selftests/TPSValidity.java
@@ -0,0 +1,197 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program 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; version 2 of the License.
+//
+// This program 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 a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2013 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package org.dogtagpki.tps.selftests;
+
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateNotYetValidException;
+import java.util.Locale;
+
+import netscape.security.x509.X509CertImpl;
+
+import org.dogtagpki.tps.server.TPSSubsystem;
+
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.base.EBaseException;
+import com.netscape.certsrv.base.IConfigStore;
+import com.netscape.certsrv.logging.ILogEventListener;
+import com.netscape.certsrv.selftests.EDuplicateSelfTestException;
+import com.netscape.certsrv.selftests.EInvalidSelfTestException;
+import com.netscape.certsrv.selftests.EMissingSelfTestException;
+import com.netscape.certsrv.selftests.ESelfTestException;
+import com.netscape.certsrv.selftests.ISelfTestSubsystem;
+import com.netscape.cms.selftests.ASelfTest;
+
+/**
+ * This class implements a self test to check the validity of the TPS.
+ * <P>
+ *
+ * @author alee
+ * @version $Revision$, $Date$
+ */
+public class TPSValidity extends ASelfTest {
+
+    // parameter information
+    public static final String PROP_TPS_SUB_ID = "TpsSubId";
+    private String tpsSubId = null;
+
+    /**
+     * Initializes this subsystem with the configuration store
+     * associated with this instance name.
+     * <P>
+     *
+     * @param subsystem the associated subsystem
+     * @param instanceName the name of this self test instance
+     * @param parameters configuration store (self test parameters)
+     * @exception EDuplicateSelfTestException subsystem has duplicate name/value
+     * @exception EInvalidSelfTestException subsystem has invalid name/value
+     * @exception EMissingSelfTestException subsystem has missing name/value
+     */
+    public void initSelfTest(ISelfTestSubsystem subsystem, String instanceName,
+            IConfigStore parameters) throws EDuplicateSelfTestException,
+            EInvalidSelfTestException, EMissingSelfTestException {
+        super.initSelfTest(subsystem, instanceName, parameters);
+
+        try {
+            tpsSubId = mConfig.getString(PROP_TPS_SUB_ID);
+            if (tpsSubId != null) {
+                tpsSubId = tpsSubId.trim();
+            } else {
+                mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
+                        CMS.getLogMessage("SELFTESTS_MISSING_VALUES", getSelfTestName(),
+                                mPrefix + "." + PROP_TPS_SUB_ID));
+
+                throw new EMissingSelfTestException(PROP_TPS_SUB_ID);
+            }
+        } catch (EBaseException e) {
+            mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
+                    CMS.getLogMessage("SELFTESTS_MISSING_NAME", getSelfTestName(),
+                            mPrefix + "." + PROP_TPS_SUB_ID));
+
+            throw new EMissingSelfTestException(mPrefix, PROP_TPS_SUB_ID, null);
+        }
+    }
+
+    /**
+     * Notifies this subsystem if it is in execution mode.
+     * <P>
+     *
+     * @exception ESelfTestException failed to start
+     */
+    public void startupSelfTest() throws ESelfTestException {
+    }
+
+    /**
+     * Stops this subsystem. The subsystem may call shutdownSelfTest
+     * anytime after initialization.
+     * <P>
+     */
+    public void shutdownSelfTest() {
+    }
+
+    /**
+     * Returns the name associated with this self test. This method may
+     * return null if the self test has not been intialized.
+     * <P>
+     *
+     * @return instanceName of this self test
+     */
+    public String getSelfTestName() {
+        return super.getSelfTestName();
+    }
+
+    /**
+     * Returns the root configuration storage (self test parameters)
+     * associated with this subsystem.
+     * <P>
+     *
+     * @return configuration store (self test parameters) of this subsystem
+     */
+    public IConfigStore getSelfTestConfigStore() {
+        return super.getSelfTestConfigStore();
+    }
+
+    /**
+     * Retrieves description associated with an individual self test.
+     * This method may return null.
+     * <P>
+     *
+     * @param locale locale of the client that requests the description
+     * @return description of self test
+     */
+    public String getSelfTestDescription(Locale locale) {
+        return CMS.getUserMessage(locale,
+                "CMS_SELFTESTS_TPS_VALIDITY_DESCRIPTION");
+    }
+
+    /**
+     * Execute an individual self test.
+     * <P>
+     *
+     * @param logger specifies logging subsystem
+     * @exception ESelfTestException self test exception
+     */
+    public void runSelfTest(ILogEventListener logger)
+            throws ESelfTestException {
+        String logMessage = null;
+        TPSSubsystem tps = (TPSSubsystem) CMS.getSubsystem(tpsSubId);
+
+        if (tps == null) {
+            // log that the TPS is not installed
+            logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_NOT_PRESENT", getSelfTestName());
+            mSelfTestSubsystem.log(logger, logMessage);
+            throw new ESelfTestException(logMessage);
+        } else {
+            // Retrieve the TPS subsystem certificate
+            X509CertImpl tpsCert = null;
+            try {
+                tpsCert = new X509CertImpl(tps.getSubsystemCert().getEncoded());
+            } catch (Exception e) {
+                // certificate is not present or has not been configured
+                // tpsCert will remain null
+            }
+
+            if (tpsCert == null) {
+                // log that the TPS is not yet initialized
+                logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_NOT_INITIALIZED",
+                        getSelfTestName());
+                mSelfTestSubsystem.log(logger, logMessage);
+                throw new ESelfTestException(logMessage);
+            }
+
+            // Check the TPS validity period
+            try {
+                tpsCert.checkValidity();
+            } catch (CertificateNotYetValidException e) {
+                // log that the TPS is not yet valid
+                logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_NOT_YET_VALID", getSelfTestName());
+                mSelfTestSubsystem.log(logger, logMessage);
+                throw new ESelfTestException(logMessage);
+            } catch (CertificateExpiredException e) {
+                // log that the TPS is expired
+                logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_EXPIRED", getSelfTestName());
+                mSelfTestSubsystem.log(logger, logMessage);
+                throw new ESelfTestException(logMessage);
+            }
+
+            // log that the TPS is valid
+            logMessage = CMS.getLogMessage("SELFTESTS_TPS_IS_VALID", getSelfTestName());
+            mSelfTestSubsystem.log(logger, logMessage);
+        }
+    }
+}
diff --git a/base/tps-tomcat/src/org/dogtagpki/tps/server/TPSSubsystem.java b/base/tps-tomcat/src/org/dogtagpki/tps/server/TPSSubsystem.java
index 92017812cfc0b09058133a3b85aee5b0b6c5dc46..ef92c7284c314f5d35ab62332e01ed59785ca151 100644
--- a/base/tps-tomcat/src/org/dogtagpki/tps/server/TPSSubsystem.java
+++ b/base/tps-tomcat/src/org/dogtagpki/tps/server/TPSSubsystem.java
@@ -18,6 +18,10 @@
 package org.dogtagpki.tps.server;
 
 import org.dogtagpki.tps.token.TokenDatabase;
+import org.mozilla.jss.CryptoManager;
+import org.mozilla.jss.CryptoManager.NotInitializedException;
+import org.mozilla.jss.crypto.ObjectNotFoundException;
+import org.mozilla.jss.crypto.TokenException;
 
 import com.netscape.certsrv.apps.CMS;
 import com.netscape.certsrv.authority.IAuthority;
@@ -112,4 +116,16 @@ public class TPSSubsystem implements IAuthority, ISubsystem {
     public TokenDatabase getTokenDatabase() {
         return tokenDatabase;
     }
+
+    public org.mozilla.jss.crypto.X509Certificate getSubsystemCert() throws EBaseException, NotInitializedException,
+            ObjectNotFoundException, TokenException {
+        IConfigStore cs = CMS.getConfigStore();
+        String nickname = cs.getString("tps.subsystem.nickname", "");
+        String tokenname = cs.getString("tps.subsystem.tokenname", "");
+        if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token"))
+            nickname = tokenname + ":" + nickname;
+
+        CryptoManager cm = CryptoManager.getInstance();
+        return cm.findCertByNickname(nickname);
+    }
 }
-- 
1.8.1.4

