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.");
   }
 }
 @Before
 public void setUp() throws Exception {
   admin =
       (TestX509CertificateAuthenticationToken)
           simpleAuthenticationProvider.authenticate(new AuthenticationSubject(null, null));
   RoleData role = roleManagementSessionRemote.create(internalAdmin, ROLENAME);
   Collection<AccessUserAspectData> subjects = new LinkedList<AccessUserAspectData>();
   subjects.add(
       new AccessUserAspectData(
           ROLENAME,
           CertTools.getIssuerDN(admin.getCertificate()).hashCode(),
           X500PrincipalAccessMatchValue.WITH_COMMONNAME,
           AccessMatchType.TYPE_EQUALCASEINS,
           CertTools.getPartFromDN(SimpleAuthenticationProviderSessionRemote.DEFAULT_DN, "CN")));
   role = roleManagementSessionRemote.addSubjectsToRole(internalAdmin, role, subjects);
   Collection<AccessRuleData> accessRules = new LinkedList<AccessRuleData>();
   accessRules.add(
       new AccessRuleData(
           ROLENAME, AccessRulesConstants.ROLE_ADMINISTRATOR, AccessRuleState.RULE_ACCEPT, false));
   accessRules.add(
       new AccessRuleData(
           ROLENAME,
           AccessRulesConstants.REGULAR_EDITUSERDATASOURCES,
           AccessRuleState.RULE_ACCEPT,
           false));
   accessRules.add(
       new AccessRuleData(
           ROLENAME,
           AccessRulesConstants.USERDATASOURCEPREFIX
               + Integer.valueOf(
                   userDataSourceSession.getUserDataSourceId(admin, "TESTNEWDUMMYCUSTOM"))
               + AccessRulesConstants.UDS_FETCH_RIGHTS,
           AccessRuleState.RULE_ACCEPT,
           false));
   role = roleManagementSessionRemote.addAccessRulesToRole(internalAdmin, role, accessRules);
 }
  /** 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);
    }
  }
  @Test
  public void testIsAuthorizedToUserDataSource() throws Exception {
    final String rolename = "testIsAuthorizedToUserDataSource";
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new X500Principal("CN=" + rolename));
    TestX509CertificateAuthenticationToken adminNoAuth =
        (TestX509CertificateAuthenticationToken)
            simpleAuthenticationProvider.authenticate(new AuthenticationSubject(principals, null));

    final int caid = CertTools.getIssuerDN(admin.getCertificate()).hashCode();
    final String cN = CertTools.getPartFromDN(CertTools.getIssuerDN(admin.getCertificate()), "CN");
    RoleData role = roleManagementSessionRemote.create(internalAdmin, rolename);
    final String alias = "spacemonkeys";
    try {
      Collection<AccessUserAspectData> subjects = new ArrayList<AccessUserAspectData>();
      subjects.add(
          new AccessUserAspectData(
              rolename,
              caid,
              X500PrincipalAccessMatchValue.WITH_COMMONNAME,
              AccessMatchType.TYPE_EQUALCASE,
              cN));
      role = roleManagementSessionRemote.addSubjectsToRole(internalAdmin, role, subjects);
      Collection<AccessRuleData> accessRules = new ArrayList<AccessRuleData>();
      // Not authorized to user data sources
      accessRules.add(
          new AccessRuleData(
              rolename,
              AccessRulesConstants.REGULAR_EDITENDENTITYPROFILES,
              AccessRuleState.RULE_ACCEPT,
              true));
      role = roleManagementSessionRemote.addAccessRulesToRole(internalAdmin, role, accessRules);

      CustomUserDataSourceContainer userdatasource = new CustomUserDataSourceContainer();
      userdatasource.setClassPath(
          "org.ejbca.core.model.ra.userdatasource.DummyCustomUserDataSource");
      userdatasource.setDescription("Used in Junit Test, Remove this one");

      // Test authorization to edit with an unauthorized admin
      try {
        userDataSourceSession.addUserDataSource(adminNoAuth, alias, userdatasource);
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source spacemonkeys.", e.getMessage());
      }
      try {
        userDataSourceSession.changeUserDataSource(adminNoAuth, alias, userdatasource);
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source spacemonkeys.", e.getMessage());
      }
      // Add so we can try to clone, remove and rename
      userDataSourceSession.addUserDataSource(internalAdmin, alias, userdatasource);
      try {
        userDataSourceSession.cloneUserDataSource(adminNoAuth, alias, "newmonkeys");
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source newmonkeys.", e.getMessage());
      }
      try {
        userDataSourceSession.removeUserDataSource(adminNoAuth, alias);
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source spacemonkeys.", e.getMessage());
      }
      try {
        userDataSourceSession.renameUserDataSource(adminNoAuth, alias, "renamedmonkey");
        fail("admin should not have been authorized to edit user data source");
      } catch (AuthorizationDeniedException e) {
        assertEquals("Error, not authorized to user data source spacemonkeys.", e.getMessage());
      }

    } finally {
      userDataSourceSession.removeUserDataSource(internalAdmin, alias);
      roleManagementSessionRemote.remove(internalAdmin, rolename);
    }
  }