/** Test Overflow of CRL Period */
 @Test
 public void testCRLPeriodOverflow() throws Exception {
   log.trace(">test05CRLPeriodOverflow()");
   // Fetch CAInfo and save CRLPeriod
   CAInfo cainfo = testx509ca.getCAInfo();
   long tempCRLPeriod = cainfo.getCRLPeriod();
   X509Certificate cert = createCertWithValidity(1);
   try {
     // Revoke the user
     certificateStoreSession.setRevokeStatus(
         roleMgmgToken, cert, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, null);
     // Change CRLPeriod
     cainfo.setCRLPeriod(Long.MAX_VALUE);
     caSession.editCA(roleMgmgToken, cainfo);
     // Create new CRL's
     assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
     // Verify that status is not archived
     CertificateInfo certinfo =
         certificateStoreSession.getCertificateInfo(CertTools.getFingerprintAsString(cert));
     assertFalse(
         "Non Expired Revoked Certificate was archived",
         certinfo.getStatus() == CertificateConstants.CERT_ARCHIVED);
   } finally {
     internalCertificateStoreSession.removeCertificate(CertTools.getSerialNumber(cert));
     // Restore CRL Period
     cainfo.setCRLPeriod(tempCRLPeriod);
     caSession.editCA(roleMgmgToken, cainfo);
   }
 }
 /** Add a new user and an expire service. Test that the service expires the users password */
 @Test
 public void testExpireCertificateWithCertificateProfiles() throws Exception {
   final String certificateprofilename = "testExpireCertificateWithCertificateProfiles";
   int certificateProfileId =
       certificateProfileSession.addCertificateProfile(
           admin, certificateprofilename, new CertificateProfile());
   try {
     createCertificate(certificateProfileId);
     long seconds = (cert.getNotAfter().getTime() - new Date().getTime()) / 1000l;
     // Create a new UserPasswordExpireService
     ServiceConfiguration config = new ServiceConfiguration();
     config.setActive(true);
     config.setDescription("This is a description");
     // No mailsending for this Junit test service
     config.setActionClassPath(NoAction.class.getName());
     config.setActionProperties(null);
     config.setIntervalClassPath(PeriodicalInterval.class.getName());
     Properties intervalprop = new Properties();
     // Run the service every 3:rd second
     intervalprop.setProperty(PeriodicalInterval.PROP_VALUE, "3");
     intervalprop.setProperty(PeriodicalInterval.PROP_UNIT, PeriodicalInterval.UNIT_SECONDS);
     config.setIntervalProperties(intervalprop);
     config.setWorkerClassPath(CertificateExpirationNotifierWorker.class.getName());
     Properties workerprop = new Properties();
     workerprop.setProperty(EmailSendingWorkerConstants.PROP_SENDTOADMINS, "FALSE");
     workerprop.setProperty(EmailSendingWorkerConstants.PROP_SENDTOENDUSERS, "FALSE");
     workerprop.setProperty(BaseWorker.PROP_CAIDSTOCHECK, String.valueOf(caid));
     workerprop.setProperty(
         BaseWorker.PROP_CERTIFICATE_PROFILE_IDS_TO_CHECK, Integer.toString(certificateProfileId));
     workerprop.setProperty(BaseWorker.PROP_TIMEBEFOREEXPIRING, String.valueOf(seconds - 5));
     workerprop.setProperty(BaseWorker.PROP_TIMEUNIT, BaseWorker.UNIT_SECONDS);
     config.setWorkerProperties(workerprop);
     if (serviceSession.getService(CERTIFICATE_EXPIRATION_SERVICE) == null) {
       serviceSession.addService(admin, 4711, CERTIFICATE_EXPIRATION_SERVICE, config);
     }
     serviceSession.activateServiceTimer(admin, CERTIFICATE_EXPIRATION_SERVICE);
     // The service will run... the cert should still be active after 2
     // seconds..
     Thread.sleep(2000);
     info = certificateStoreSession.getCertificateInfo(fingerprint);
     assertEquals("status does not match.", CertificateConstants.CERT_ACTIVE, info.getStatus());
     // The service will run...We need some tolerance since timers cannot
     // be guaranteed to executed at the exact interval.
     Thread.sleep(10000);
     int tries = 0;
     while (info.getStatus() != CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION && tries < 5) {
       Thread.sleep(1000);
       info = certificateStoreSession.getCertificateInfo(fingerprint);
       tries++;
     }
     info = certificateStoreSession.getCertificateInfo(fingerprint);
     assertEquals(
         "Status does not match.",
         CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION,
         info.getStatus());
   } finally {
     // Clean the certificate profile
     certificateProfileSession.removeCertificateProfile(admin, certificateprofilename);
   }
 }
 private void createCertificate(int certificateProfileId) throws Exception {
   KeyPair keys = KeyTools.genKeys("1024", "RSA");
   cert =
       (X509Certificate)
           signSession.createCertificate(
               admin,
               USERNAME,
               PASSWORD,
               new PublicKeyWrapper(keys.getPublic()),
               -1,
               null,
               null,
               certificateProfileId,
               SecConst.CAID_USEUSERDEFINED);
   certificatesToRemove.add(cert);
   fingerprint = CertTools.getFingerprintAsString(cert);
   X509Certificate ce =
       (X509Certificate) certificateStoreSession.findCertificateByFingerprint(fingerprint);
   if (ce == null) {
     throw new Exception("Cannot find certificate with fp=" + fingerprint);
   }
   info = certificateStoreSession.getCertificateInfo(fingerprint);
   if (!fingerprint.equals(info.getFingerprint())) {
     throw new Exception("fingerprint does not match.");
   }
   if (!cert.getSerialNumber().equals(info.getSerialNumber())) {
     throw new Exception("serialnumber does not match.");
   }
   if (!CertTools.getIssuerDN(cert).equals(info.getIssuerDN())) {
     throw new Exception("issuerdn does not match.");
   }
   if (!CertTools.getSubjectDN(cert).equals(info.getSubjectDN())) {
     throw new Exception("subjectdn does not match.");
   }
   // The cert was just stored above with status INACTIVE
   if (!(CertificateConstants.CERT_ACTIVE == info.getStatus())) {
     throw new Exception("status does not match.");
   }
 }
  /** creates new crl */
  @Test
  public void testCreateNewCRL() throws Exception {
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    X509CRL x509crl = null;

    // Get number of last CRL
    int number = crlStoreSession.getLastCRLNumber(testx509ca.getSubjectDN(), false);
    log.debug("Last CRLNumber = " + number);
    byte[] crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
    assertNotNull("Could not get CRL", crl);
    x509crl = CertTools.getCRLfromByteArray(crl);

    BigInteger num = CrlExtensions.getCrlNumber(x509crl);
    // Create a new CRL again to see that the number increases
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    int number1 = crlStoreSession.getLastCRLNumber(testx509ca.getSubjectDN(), false);
    assertEquals(number + 1, number1);
    byte[] crl1 = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
    X509CRL x509crl1 = CertTools.getCRLfromByteArray(crl1);
    BigInteger num1 = CrlExtensions.getCrlNumber(x509crl1);
    assertEquals(num.intValue() + 1, num1.intValue());

    /*
     * check revoked certificates
     */

    // Get number of last CRL
    Collection<RevokedCertInfo> revfp =
        certificateStoreSession.listRevokedCertInfo(testx509ca.getSubjectDN(), -1);
    log.debug("Number of revoked certificates=" + revfp.size());
    crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
    assertNotNull("Could not get CRL", crl);

    x509crl = CertTools.getCRLfromByteArray(crl);
    Set<? extends X509CRLEntry> revset = x509crl.getRevokedCertificates();
    // Revset will be null if there are no revoked certificates
    if (revset != null) {
      int revsize = revset.size();
      assertEquals(revfp.size(), revsize);
    } else {
      assertEquals(0, revfp.size());
    }
  }
  /** Test revocation and reactivation of certificates */
  @Test
  public void testRevokeAndUnrevoke() throws Exception {

    X509Certificate cert = createCert();
    try {
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate is not present in a new CRL
      byte[] crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      X509CRL x509crl = CertTools.getCRLfromByteArray(crl);
      Set<? extends X509CRLEntry> revset = x509crl.getRevokedCertificates();
      if (revset != null) {
        Iterator<? extends X509CRLEntry> iter = revset.iterator();
        while (iter.hasNext()) {
          X509CRLEntry ce = iter.next();
          assertTrue(ce.getSerialNumber().compareTo(cert.getSerialNumber()) != 0);
        }
      } // If no revoked certificates exist at all, this test passed...

      certificateStoreSession.setRevokeStatus(
          roleMgmgToken, cert, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, null);
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate IS present in a new CRL
      crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      x509crl = CertTools.getCRLfromByteArray(crl);
      revset = x509crl.getRevokedCertificates();
      assertNotNull(revset);
      Iterator<? extends X509CRLEntry> iter = revset.iterator();
      boolean found = false;
      while (iter.hasNext()) {
        X509CRLEntry ce = iter.next();
        if (ce.getSerialNumber().compareTo(cert.getSerialNumber()) == 0) {
          found = true;
          // TODO: verify the reason code
        }
      }
      assertTrue(
          "Certificate with serial " + cert.getSerialNumber().toString(16) + " not revoked", found);

      // Unrevoke the certificate that we just revoked
      certificateStoreSession.setRevokeStatus(
          roleMgmgToken, cert, RevokedCertInfo.NOT_REVOKED, null);
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate IS NOT present in the new
      // CRL.
      crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      x509crl = CertTools.getCRLfromByteArray(crl);
      revset = x509crl.getRevokedCertificates();
      if (revset != null) {
        iter = revset.iterator();
        found = false;
        while (iter.hasNext()) {
          X509CRLEntry ce = iter.next();
          if (ce.getSerialNumber().compareTo(cert.getSerialNumber()) == 0) {
            found = true;
          }
        }
        assertFalse(found);
      } // If no revoked certificates exist at all, this test passed...

      certificateStoreSession.setRevokeStatus(
          roleMgmgToken, cert, RevokedCertInfo.REVOCATION_REASON_CACOMPROMISE, null);
      assertTrue(
          "Failed to revoke certificate!",
          certificateStoreSession.isRevoked(
              CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert)));
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate IS present in a new CRL
      crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      x509crl = CertTools.getCRLfromByteArray(crl);
      revset = x509crl.getRevokedCertificates();
      iter = revset.iterator();
      found = false;
      while (iter.hasNext()) {
        X509CRLEntry ce = (X509CRLEntry) iter.next();
        if (ce.getSerialNumber().compareTo(cert.getSerialNumber()) == 0) {
          found = true;
          // TODO: verify the reason code
        }
      }
      assertTrue(found);

      certificateStoreSession.setRevokeStatus(
          roleMgmgToken, cert, RevokedCertInfo.NOT_REVOKED, null);
      assertTrue(
          "Was able to re-activate permanently revoked certificate!",
          certificateStoreSession.isRevoked(
              CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert)));
      // Create a new CRL again...
      assertTrue(publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId()));
      // Check that our newly signed certificate is present in the new CRL,
      // because the revocation reason
      // was not CERTIFICATE_HOLD, we can only un-revoke certificates that are
      // on hold.
      crl = crlStoreSession.getLastCRL(testx509ca.getSubjectDN(), false);
      assertNotNull("Could not get CRL", crl);
      x509crl = CertTools.getCRLfromByteArray(crl);
      revset = x509crl.getRevokedCertificates();
      iter = revset.iterator();
      found = false;
      while (iter.hasNext()) {
        X509CRLEntry ce = (X509CRLEntry) iter.next();
        if (ce.getSerialNumber().compareTo(cert.getSerialNumber()) == 0) {
          found = true;
        }
      }
      assertTrue(found);
    } finally {
      internalCertificateStoreSession.removeCertificate(cert);
    }
  }
  /** Add a new user and an expire service. Test running on all CAs. */
  @Test
  public void testExpireCertificateWithAllCAs() throws Exception {
    try {
      createCertificate();
      long seconds = (cert.getNotAfter().getTime() - new Date().getTime()) / 1000l;
      // Create a new UserPasswordExpireService
      ServiceConfiguration config = new ServiceConfiguration();
      config.setActive(true);
      config.setDescription("This is a description");
      // No mailsending for this Junit test service
      config.setActionClassPath(NoAction.class.getName());
      config.setActionProperties(null);
      config.setIntervalClassPath(PeriodicalInterval.class.getName());
      Properties intervalprop = new Properties();
      // Run the service every 3:rd second
      intervalprop.setProperty(PeriodicalInterval.PROP_VALUE, "3");
      intervalprop.setProperty(PeriodicalInterval.PROP_UNIT, PeriodicalInterval.UNIT_SECONDS);
      config.setIntervalProperties(intervalprop);
      config.setWorkerClassPath(CertificateExpirationNotifierWorker.class.getName());
      Properties workerprop = new Properties();
      workerprop.setProperty(EmailSendingWorkerConstants.PROP_SENDTOADMINS, "FALSE");
      workerprop.setProperty(EmailSendingWorkerConstants.PROP_SENDTOENDUSERS, "FALSE");
      // Here is the line that matters for this test
      workerprop.setProperty(BaseWorker.PROP_CAIDSTOCHECK, String.valueOf(SecConst.ALLCAS));

      workerprop.setProperty(BaseWorker.PROP_TIMEBEFOREEXPIRING, String.valueOf(seconds - 5));
      workerprop.setProperty(BaseWorker.PROP_TIMEUNIT, BaseWorker.UNIT_SECONDS);
      config.setWorkerProperties(workerprop);
      if (serviceSession.getService(CERTIFICATE_EXPIRATION_SERVICE) == null) {
        serviceSession.addService(admin, 4711, CERTIFICATE_EXPIRATION_SERVICE, config);
      }
      serviceSession.activateServiceTimer(admin, CERTIFICATE_EXPIRATION_SERVICE);
      // The service will run... the cert should still be active after 2
      // seconds..
      Thread.sleep(2000);
      info = certificateStoreSession.getCertificateInfo(fingerprint);
      assertEquals("status does not match.", CertificateConstants.CERT_ACTIVE, info.getStatus());
      // The service will run...We need some tolerance since timers cannot
      // be guaranteed to executed at the exact interval.
      Thread.sleep(10000);
      int tries = 0;
      while (info.getStatus() != CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION && tries < 8) {
        Thread.sleep(1000);
        info = certificateStoreSession.getCertificateInfo(fingerprint);
        tries++;
      }
      info = certificateStoreSession.getCertificateInfo(fingerprint);
      assertEquals(
          "Status does not match.",
          CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION,
          info.getStatus());
    } finally {
      // Restore superadmin CA if it got screwed up.
      List<Certificate> certs = certificateStoreSession.findCertificatesByUsername("superadmin");
      for (Certificate certificate : certs) {
        String superAdminFingerprint = CertTools.getFingerprintAsString(certificate);
        internalCertificateStoreSession.setStatus(
            admin, superAdminFingerprint, CertificateConstants.CERT_ACTIVE);
      }
    }
  }