Search in sources :

Example 1 with RevokedCert

use of rhsm.data.RevokedCert in project rhsm-qe by RedHatQE.

the class BugzillaTests method testConsumerUnsubscribedWhenSubscriptionRevoked.

/**
 * @author skallesh
 * @throws Exception
 * @throws JSONException
 */
@SuppressWarnings("deprecation")
@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21905", "RHEL7-51766" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "Consumer unsubscribed when Subscription revoked", groups = { "Tier3Tests", "ConsumerUnsubscribedWhenSubscriptionRevoked", "blockedByBug-947429", "blockedByBug-1555582" }, enabled = true)
@ImplementsNitrateTest(caseId = 56025)
public void testConsumerUnsubscribedWhenSubscriptionRevoked() throws Exception {
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, null, null, null, null, null);
    clienttasks.autoheal(null, null, true, null, null, null, null);
    String consumerId = clienttasks.getCurrentConsumerId();
    ownerKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, consumerId);
    String name, productId;
    List<String> providedProductIds = new ArrayList<String>();
    name = "Test product to check subscription-removal";
    productId = "test-product";
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.clear();
    attributes.put("version", "1.0");
    attributes.put("variant", "server");
    attributes.put("arch", "ALL");
    attributes.put("warning_period", "30");
    attributes.put("type", "MKT");
    attributes.put("type", "SVC");
    File entitlementCertFile = null;
    CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
    String resourcePath = "/products/" + productId;
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.0"))
        resourcePath = "/owners/" + sm_clientOrg + resourcePath;
    CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, resourcePath);
    clienttasks.unsubscribeFromAllOfTheCurrentlyConsumedProductSubscriptions();
    CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, name + " BITS", productId, 1, attributes, null);
    CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1 * 24 * 60, /* 1 day ago */
    15 * 24 * 60, /* 15 days from now */
    getRandInt(), getRandInt(), productId, providedProductIds, null);
    server.runCommandAndWait("rm -rf " + CandlepinTasks.candlepinCRLFile);
    for (SubscriptionPool pool : clienttasks.getCurrentlyAllAvailableSubscriptionPools()) {
        if (pool.productId.equals(productId)) {
            entitlementCertFile = clienttasks.subscribeToSubscriptionPool(pool, sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl);
        }
    }
    Assert.assertNotNull(entitlementCertFile, "Successfully created and subscribed to product subscription '" + productId + "' created by and needed for this test.");
    EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(entitlementCertFile);
    List<ProductSubscription> consumedSusbscription = clienttasks.getCurrentlyConsumedProductSubscriptions();
    Assert.assertFalse(consumedSusbscription.isEmpty());
    CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
    resourcePath = "/products/" + productId;
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.0"))
        resourcePath = "/owners/" + sm_clientOrg + resourcePath;
    CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, resourcePath);
    sleep(2 * /* min */
    60 * 1000);
    // verify the entitlement serial has been added to the CRL on the server
    List<RevokedCert> revokedCerts = servertasks.getCurrentlyRevokedCerts();
    RevokedCert revokedCert = RevokedCert.findFirstInstanceWithMatchingFieldFromList("serialNumber", entitlementCert.serialNumber, revokedCerts);
    Assert.assertNotNull(revokedCert, "The Certificate Revocation List file on the candlepin server contains an entitlement serial '" + entitlementCert.serialNumber + "' to the product subscription '" + productId + "' that was just deleted on the candlepin server.");
    // trigger the rhsmcertd on the system and verify the entitlement has
    // been removed
    clienttasks.run_rhsmcertd_worker(false);
    Assert.assertTrue(clienttasks.getCurrentlyConsumedProductSubscriptions().isEmpty(), "The revoked entitlement has been removed from the system by rhsmcertd.");
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) File(java.io.File) SubscriptionPool(rhsm.data.SubscriptionPool) RevokedCert(rhsm.data.RevokedCert) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 2 with RevokedCert

use of rhsm.data.RevokedCert in project rhsm-qe by RedHatQE.

the class ExpirationTests method testExpiredEntitlementIsAddedToCertificateRevocationList.

@Test(description = "Verify expired entitlement is added to the certifiate revocation list after the subscription expires", groups = { "Tier2Tests" }, dependsOnMethods = { "testEntitlementsAfterSubscriptionExpires" }, // TODO Review the validity of this testcase with development (Current behavior is that expiringCert is NOT actually added to list of RevokedCerts.  Instead they remain on the system for acknowledgment and manual removal)
enabled = false)
public void testExpiredEntitlementIsAddedToCertificateRevocationList() throws Exception {
    if (expiringCert == null)
        throw new SkipException("This test requires a successful run of a prior test whose entitlement cert has expired.");
    log.info("Check the CRL list on the server and verify the expired entitlement cert serial is revoked...");
    log.info("Waiting 2 minutes...  (Assuming this is the candlepin.conf value set for pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule)");
    // give the CertificateRevocationListTask.schedule 2 minutes to update the list since that is what was set in setupBeforeSuite()
    sleep(2 * 60 * 1000);
    // NOTE: The refresh schedule should have been set with a call to servertasks.updateConfigFileParameter in the setupBeforeSuite()
    // Set inside /etc/candlepin/candlepin.conf
    // pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule=0 0/2 * * * ?
    // NOTE: if not set, the default is  public static final String DEFAULT_SCHEDULE = "0 0 12 * * ?" Fire at 12pm (noon) every day
    RevokedCert revokedCert = RevokedCert.findFirstInstanceWithMatchingFieldFromList("serialNumber", expiringCert.serialNumber, servertasks.getCurrentlyRevokedCerts());
    Assert.assertTrue(revokedCert != null, "Expiring entitlement certificate serial number '" + expiringCert.serialNumber + "' has been added to the Certificate Revocation List (CRL) as: " + revokedCert);
    Assert.assertEquals(revokedCert.reasonCode, "Privilege Withdrawn", "An expired entitlement certificate should be revoked with a reason code of Privilege Withdrawn.");
}
Also used : SkipException(org.testng.SkipException) RevokedCert(rhsm.data.RevokedCert) Test(org.testng.annotations.Test)

Example 3 with RevokedCert

use of rhsm.data.RevokedCert in project rhsm-qe by RedHatQE.

the class CRLTests method testCandlepinCRLForDuplicates.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-39302", "RHEL7-97554" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "verify that candlepin's crl file does not contain duplicate serials otherwise it may be growing out of control", groups = { "Tier3Tests", "blockedByBug-1399356" }, enabled = true)
public void testCandlepinCRLForDuplicates() {
    if (sm_serverType.equals(CandlepinType.hosted))
        throw new SkipException("This test requires that your candlepin server NOT be a hosted RHN Classic system.");
    // if not we should wait two cycles of pinsetter.org.candlepin.pinsetter.tasks.ExpiredPoolsJob.schedule defined in /etc/candlepin/candlepin.conf and then check again
    if (!RemoteFileTasks.testExists(server, servertasks.candlepinCRLFile)) {
        Assert.fail("Expected CRL file '" + servertasks.candlepinCRLFile + "' to exist.  We probably have to wait for the next trigger of the ExpiredPoolsJob.schedule.");
    }
    // get the currently revoked certs
    List<RevokedCert> revokedCerts = servertasks.getCurrentlyRevokedCerts();
    // if the list is empty, then maybe this candlepin server is brand new and no consumers have attached and removed a subscription yet
    if (revokedCerts.isEmpty()) {
        Assert.fail("Expected CRL file '" + servertasks.candlepinCRLFile + "' to have some revoked serials by now.  We may have to attach and remove an entitlement and then wait for the ExpiredPoolsJob.schedule to trigger.");
    }
    // search and log all serials that appear in duplicate
    boolean foundDuplicateRevokedCertsWithMatchingSerials = false;
    for (RevokedCert revokedCert : revokedCerts) {
        List<RevokedCert> allRevokedCertsWithMatchingSerial = RevokedCert.findAllInstancesWithMatchingFieldFromList("serialNumber", revokedCert.serialNumber, revokedCerts);
        if (allRevokedCertsWithMatchingSerial.size() > 1) {
            log.warning("Found multiple revoked entitlement certificates on candlepin server '" + server.getConnection().getRemoteHostname() + "' file '" + servertasks.candlepinCRLFile + "' matching serial '" + String.format("%016X", revokedCert.serialNumber) + "' (BigInteger='" + revokedCert.serialNumber + "').");
            foundDuplicateRevokedCertsWithMatchingSerials = true;
        }
    }
    // assert no duplicates were found
    Assert.assertTrue(!foundDuplicateRevokedCertsWithMatchingSerials, "Did not find any revoked entitlement certificates on candlepin server '" + server.getConnection().getRemoteHostname() + "' file '" + servertasks.candlepinCRLFile + "'.  If failed, see warnings above for duplicate serials.");
}
Also used : SkipException(org.testng.SkipException) RevokedCert(rhsm.data.RevokedCert) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 4 with RevokedCert

use of rhsm.data.RevokedCert in project rhsm-qe by RedHatQE.

the class BugzillaTests method testCRL.

/**
 * @author skallesh
 * @throws Exception
 * @throws JSONException
 */
@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21902", "RHEL7-51763" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "Consumer unsubscribed when Subscription revoked", groups = { "Tier3Tests", "CRLTest", "blockedByBug-1389559", "blockedByBug-1399356" }, enabled = true)
@ImplementsNitrateTest(caseId = 55355)
public void testCRL() {
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, false, null, null, null, null);
    List<SubscriptionPool> availPools = clienttasks.getCurrentlyAvailableSubscriptionPools();
    File entitlementCertFile = clienttasks.subscribeToSubscriptionPool(availPools.get(randomGenerator.nextInt(availPools.size())), sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl);
    BigInteger serialNumber = clienttasks.getSerialNumberFromEntitlementCertFile(entitlementCertFile);
    clienttasks.unsubscribe(null, serialNumber, null, null, null, null, null);
    // give the server time to update;
    sleep(2 * /* min */
    90 * 1000);
    // schedule is set in
    // /etc/candlepin/candlepin.conf
    // pinsetter.org.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule=0
    // 0/2 * * * ?
    RevokedCert revokedCert = RevokedCert.findFirstInstanceWithMatchingFieldFromList("serialNumber", serialNumber, servertasks.getCurrentlyRevokedCerts());
    Assert.assertNotNull(revokedCert, "Found expected Revoked Cert on the server's Certificate Revocation List (CRL) after unsubscribing from serial '" + serialNumber + "'.");
    log.info("Verified revoked certificate: " + revokedCert);
}
Also used : BigInteger(java.math.BigInteger) SubscriptionPool(rhsm.data.SubscriptionPool) File(java.io.File) RevokedCert(rhsm.data.RevokedCert) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 5 with RevokedCert

use of rhsm.data.RevokedCert in project rhsm-qe by RedHatQE.

the class CRLTests method testChangeToSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools.

// Test Methods ***********************************************************************
@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-27133", "RHEL7-51947" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "subscription-manager-cli: change subscription pool start/end dates and refresh subscription pools", groups = { "Tier3Tests", "ChangeSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools_Test" }, dependsOnGroups = {}, // dataProvider="getAvailableNonTemporarySubscriptionPoolsData",
dataProvider = "getRandomSubsetOfAvailableNonTemporarySubscriptionPoolsData", enabled = true)
@ImplementsNitrateTest(caseId = 56025)
public void testChangeToSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools(SubscriptionPool originalPool) throws Exception {
    // * the crl list on the server should be poplulated w/ the old entitlement cert serials
    if (servertasks.dbConnection == null)
        throw new SkipException("This testcase requires a connection to the candlepin database.");
    /* https://bugzilla.redhat.com/show_bug.cgi?id=663455#c1 < DUE TO THESE IMPLEMENTED CHANGES, THE FOLLOWING IS NO LONGER APPROPRIATE...
		// Before proceeding with this test, determine if the productId provided by this subscription pool has already been entitled.
		// This will happen when more than one pool has been created under a different contract/serial so as to increase the
		// total quantity of entitlements available to the consumers.
		if (alreadySubscribedProductIdsInChangeSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools_Test.contains(pool.productId)) {
			log.info("Because the productId '"+pool.productId+"' from this pool has already been subscribed to via a previously available pool, it only makes sense to skip this iteration of the test.");
			log.info("However, for the sake of testing, let's attempt to subscribe to it anyway and assert that our subscribe request is blocked with an appropriate message...");
			SSHCommandResult sshCommandResult = clienttasks.subscribe(pool.poolId, null, null, null, null, null, null, null);
			Assert.assertEquals(sshCommandResult.getStdout().trim(),"This consumer is already subscribed to the product matching pool with id '"+pool.poolId+"'.");
			throw new SkipException("Because this consumer is already subscribed to the product ("+pool.productId+") provided by this pool id '"+pool.poolId+".', this pool is unsubscribeable and therefore we must skip this test iteration.");
		}
		*/
    List<ProductSubscription> originalConsumedProducts = clienttasks.getCurrentlyConsumedProductSubscriptions();
    // With the introduction of virt-guest pools, it is possible that a former invocation of this test has changed the validity dates on this pool,
    // therefore, let's re-fetch the SubscriptionPool object that we are about to test.
    SubscriptionPool pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", originalPool.poolId, clienttasks.getCurrentlyAvailableSubscriptionPools());
    Assert.assertNotNull(pool, "Successfully found the SubscriptionPool with the poolId that we are about to test from list --available.");
    log.info("Subscribe client (already registered as a system under username '" + sm_clientUsername + "') to subscription pool " + pool + "...");
    File entitlementCertFile = clienttasks.subscribeToSubscriptionPool(pool, /*sm_serverAdminUsername*/
    sm_clientUsername, /*sm_serverAdminPassword*/
    sm_clientPassword, sm_serverUrl);
    Assert.assertNotNull(entitlementCertFile, "Our attempt to subscribe resulted in a new entitlement cert on our system.");
    alreadySubscribedProductIdsInChangeSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools_Test.add(pool.productId);
    EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(entitlementCertFile);
    log.info("Verify that the currently consumed product subscriptions that came from this subscription pool have the same start and end date as the pool...");
    List<ProductSubscription> originalProducts = ProductSubscription.findAllInstancesWithMatchingFieldFromList("serialNumber", entitlementCert.serialNumber, clienttasks.getCurrentlyConsumedProductSubscriptions());
    Assert.assertFalse(originalProducts.isEmpty(), "After subscribing to a new pool, at least one consumed product subscription matching the entitlement cert's serial number '" + entitlementCert.serialNumber + "' is expected.");
    // TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=660713 - jsefler 12/12/2010
    Boolean invokeWorkaroundWhileBugIsOpen = true;
    try {
        String bugId = "660713";
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        log.warning("The workaround while this bug is open is to skip the assertion that: The original end date for the subscribed product matches the end date of the subscription pool '" + pool.subscriptionName + "' from where it was entitled.");
    } else
        for (ProductSubscription originalProduct : originalProducts) {
            Assert.assertEquals(originalProduct.accountNumber, originalProducts.get(0).accountNumber, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same accountNumber.");
            Assert.assertEquals(originalProduct.contractNumber, originalProducts.get(0).contractNumber, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same contractNumber.");
            Assert.assertEquals(originalProduct.serialNumber, originalProducts.get(0).serialNumber, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same serialNumber.");
            Assert.assertEquals(originalProduct.isActive, originalProducts.get(0).isActive, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same active status.");
            Assert.assertTrue(originalProduct.startDate.compareTo(originalProducts.get(0).startDate) == 0, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same startDate.");
            Assert.assertTrue(originalProduct.endDate.compareTo(pool.endDate) == 0, "The original end date (" + ProductSubscription.formatDateString(originalProduct.endDate) + ") for the subscribed product '" + originalProduct.productName + "' matches the end date (" + SubscriptionPool.formatDateString(pool.endDate) + ") of the subscription pool '" + pool.subscriptionName + "' from where it was entitled.");
        }
    // new File(clienttasks.entitlementCertDir+"/"+products.get(0).serialNumber+".pem");
    File originalEntitlementCertFile = entitlementCertFile;
    Calendar originalStartDate = (Calendar) originalProducts.get(0).startDate.clone();
    Calendar originalEndDate = (Calendar) originalProducts.get(0).endDate.clone();
    Integer contractNumber = originalProducts.get(0).contractNumber;
    Assert.assertTrue(RemoteFileTasks.testExists(client, originalEntitlementCertFile.getPath()), "Original entitlement cert file '" + originalEntitlementCertFile + "' exists.");
    log.info("Now we will change the start and end date of the subscription pool adding one month to enddate and subtracting one month from startdate...");
    Calendar newStartDate = (Calendar) originalStartDate.clone();
    newStartDate.add(Calendar.MONTH, -1);
    Calendar newEndDate = (Calendar) originalEndDate.clone();
    newEndDate.add(Calendar.MONTH, 1);
    updateSubscriptionPoolDatesOnDatabase(pool, newStartDate, newEndDate);
    // TEMPORARY WORKAROUND FOR BUG
    invokeWorkaroundWhileBugIsOpen = true;
    try {
        String bugId = "883486";
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        log.warning("The workaround while this bug is open is to compensate the expected new start/end dates for daylight savings.");
        Calendar now = Calendar.getInstance();
        // adjust the expected entitlement dates for daylight savings time (changed by https://github.com/candlepin/subscription-manager/pull/385)
        // now.get(Calendar.DST_OFFSET) will equal 0 in the winter StandardTime; will equal 1000*60*60 in the summer DaylightSavingsTime (when the local time zone observes DST)
        newStartDate.add(Calendar.MILLISECOND, now.get(Calendar.DST_OFFSET) - newStartDate.get(Calendar.DST_OFFSET));
        newEndDate.add(Calendar.MILLISECOND, now.get(Calendar.DST_OFFSET) - newEndDate.get(Calendar.DST_OFFSET));
    }
    // END OF WORKAROUND
    log.info("Now let's refresh the subscription pools...");
    JSONObject jobDetail = CandlepinTasks.refreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, ownerKey);
    jobDetail = CandlepinTasks.waitForJobDetailStateUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, jobDetail, "FINISHED", 10 * 1000, 3);
    log.info("Refresh to make sure the latest entitlement certs are on the client...");
    // makes sure the new entitlement is downloaded
    clienttasks.refresh(null, null, null, null);
    log.info("The updated certs should now be on the client...");
    log.info("First, let's assert that the original entitlement cert file '" + originalEntitlementCertFile + "' is gone...");
    Assert.assertTrue(!RemoteFileTasks.testExists(client, originalEntitlementCertFile.getPath()), "Original certificate file '" + originalEntitlementCertFile + "' has been removed from the system.");
    log.info("Second, let's assert that the consumed products have been refreshed...");
    // List<ProductSubscription> newProducts = ProductSubscription.findAllInstancesWithMatchingFieldFromList("contractNumber",contractNumber, clienttasks.getCurrentlyConsumedProductSubscriptions());
    // Assert.assertEquals(newProducts.size(), originalProducts.size(),"The number of ProductSubscriptions corresponding to this subscription's original contract number ("+contractNumber+") remains the same.");
    List<ProductSubscription> newProducts = new ArrayList<ProductSubscription>();
    for (ProductSubscription productSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
        if (!originalConsumedProducts.contains(productSubscription))
            newProducts.add(productSubscription);
    }
    Assert.assertEquals(newProducts.size(), originalProducts.size(), "The number of ProductSubscriptions altered after changing the subscription's start/end dates remains confined to original consumed products.");
    BigInteger newSerialNumber = newProducts.get(0).serialNumber;
    File newCertFile = new File(clienttasks.entitlementCertDir + "/" + newSerialNumber + ".pem");
    Assert.assertNotSame(newCertFile, originalEntitlementCertFile, "The newly granted and refresh entitlement cert file should not be the same as the original cert file.");
    Assert.assertTrue(RemoteFileTasks.testExists(client, newCertFile.getPath()), "New entitlement certificate file '" + newCertFile + "' exists.");
    for (ProductSubscription newProduct : newProducts) {
        Assert.assertEquals(ProductSubscription.formatDateString(newProduct.startDate), ProductSubscription.formatDateString(newStartDate), "Rhsmcertd has updated the entitled startdate from '" + ProductSubscription.formatDateString(originalStartDate) + "' to '" + ProductSubscription.formatDateString(newStartDate) + "' for consumed product '" + newProduct.productName + "' that originated from poolId '" + pool.poolId + "'.");
        Assert.assertEquals(ProductSubscription.formatDateString(newProduct.endDate), ProductSubscription.formatDateString(newEndDate), "Rhsmcertd has updated the entitled enddate from '" + ProductSubscription.formatDateString(originalEndDate) + "' to '" + ProductSubscription.formatDateString(newEndDate) + "' for consumed product '" + newProduct.productName + "' that originated from poolId '" + pool.poolId + "'.");
        log.info("And, let's assert that consumed product entitlement serial has been updated...");
        Assert.assertTrue(!newProduct.serialNumber.equals(originalProducts.get(0).serialNumber) && newProduct.serialNumber.equals(newSerialNumber), "The consumed product entitlement serial has been updated from '" + originalProducts.get(0).serialNumber + "' to '" + newSerialNumber + "' for consumed product '" + newProduct.productName + "' that originated from poolId '" + pool.poolId + "'.");
        log.info("Let's assert that the following consumed product attributes have been left unchanged...");
        Assert.assertEquals(newProduct.accountNumber, originalProducts.get(0).accountNumber, "The consumed product accountNumber remains unchanged for '" + newProduct.productName + "' after its pool (poolId='" + pool.poolId + "') start/end dates have been modified and refreshed.");
        Assert.assertEquals(newProduct.contractNumber, originalProducts.get(0).contractNumber, "The consumed product contractNumber remains unchanged for '" + newProduct.productName + "' after its pool (poolId='" + pool.poolId + "') start/end dates have been modified and refreshed.");
        Assert.assertEquals(newProduct.isActive, originalProducts.get(0).isActive, "The consumed product active status remains unchanged for '" + newProduct.productName + "' after its pool (poolId='" + pool.poolId + "') start/end dates have been modified and refreshed.");
    }
    log.info("Third, let's assert that subscription pool reflects the new end date...");
    clienttasks.unsubscribeFromSerialNumber(newSerialNumber);
    pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", pool.poolId, clienttasks.getCurrentlyAvailableSubscriptionPools());
    Assert.assertNotNull(pool, "Successfully found the SubscriptionPool with the poolId that we just unsubscribed from and searched for in list --available.");
    Assert.assertEquals(SubscriptionPool.formatDateString(pool.endDate), SubscriptionPool.formatDateString(newEndDate), "As seen by the client, the enddate of the refreshed pool '" + pool.poolId + "' (" + pool.subscriptionName + ") has been changed from '" + SubscriptionPool.formatDateString(originalEndDate) + "' to '" + SubscriptionPool.formatDateString(newEndDate) + "'.");
    log.info("Forth, in honor of bugzillas 682930, 679617 let's assert that after unsubscribing, the subscription pool's original quantity is restored...");
    Assert.assertEquals(pool.quantity, originalPool.quantity, "Assuming that nobody else has recently subscribed to this pool, the original pool quantity should be restored after updating the subscription's start/end dates and unsubscribing from the poolId '" + pool.poolId + "' (" + pool.subscriptionName + ").");
    log.info("Finally, check the CRL list on the server and verify the original entitlement cert serial is revoked...");
    log.info("Waiting 2 minutes...  (Assuming this is the candlepin.conf value set for pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule)");
    // give the CertificateRevocationListTask.schedule 2 minutes to update the list since that is what was set in setupBeforeSuite()
    sleep(2 * 60 * 1000);
    // NOTE: The refresh schedule should have been set with a call to servertasks.updateConfigFileParameter in the setupBeforeSuite()
    // Set inside /etc/candlepin/candlepin.conf
    // pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule=0 0/2 * * * ?
    // NOTE: if not set, the default is  public static final String DEFAULT_SCHEDULE = "0 0 12 * * ?" Fire at 12pm (noon) every day
    RevokedCert revokedCert = RevokedCert.findFirstInstanceWithMatchingFieldFromList("serialNumber", entitlementCert.serialNumber, servertasks.getCurrentlyRevokedCerts());
    Assert.assertTrue(revokedCert != null, "Original entitlement certificate serial number '" + entitlementCert.serialNumber + "' granted from pool '" + pool.poolId + "' (" + pool.subscriptionName + ") has been added to the Certificate Revocation List (CRL) as: " + revokedCert);
    Assert.assertEquals(revokedCert.reasonCode, "Privilege Withdrawn", "Expanding the certificate start and end dates should revoke the certificated with a reason code of Privilege Withdrawn.");
// just to add some complexity to succeeding dataProvided runs of this test, let's re-subscribe to this pool
// FIXME The following will cause failures for pools that originate from a virtualization aware subscription.  It would be nice to re-subscribe, but first we need to determine if this pool came from a virt-aware subscription and excude it from the resubscribe
// clienttasks.subscribeToSubscriptionPool(pool);
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) Calendar(java.util.Calendar) ProductSubscription(rhsm.data.ProductSubscription) ArrayList(java.util.ArrayList) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) BigInteger(java.math.BigInteger) JSONObject(org.json.JSONObject) BigInteger(java.math.BigInteger) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) File(java.io.File) RevokedCert(rhsm.data.RevokedCert) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Aggregations

Test (org.testng.annotations.Test)5 RevokedCert (rhsm.data.RevokedCert)5 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)4 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)4 File (java.io.File)3 SkipException (org.testng.SkipException)3 SubscriptionPool (rhsm.data.SubscriptionPool)3 BigInteger (java.math.BigInteger)2 ArrayList (java.util.ArrayList)2 EntitlementCert (rhsm.data.EntitlementCert)2 ProductSubscription (rhsm.data.ProductSubscription)2 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)1 Calendar (java.util.Calendar)1 HashMap (java.util.HashMap)1 JSONObject (org.json.JSONObject)1