Search in sources :

Example 11 with EnvironmentContent

use of org.candlepin.model.EnvironmentContent in project candlepin by candlepin.

the class DefaultEntitlementCertServiceAdapterTest method testPrefixExpandsEnvIfConsumerHasOne.

@Test
@SuppressWarnings("checkstyle:indentation")
public void testPrefixExpandsEnvIfConsumerHasOne() throws Exception {
    owner.setContentPrefix("/someorg/$env/");
    // Setup an environment for the consumer:
    Environment e = this.mockEnvironment(new Environment("env1", "Awesome Environment #1", owner));
    e.getEnvironmentContent().add(new EnvironmentContent(e, content, true));
    this.consumer.setEnvironment(e);
    certServiceAdapter.createX509Certificate(consumer, owner, pool, entitlement, product, new HashSet<>(), getProductModels(product, new HashSet<>(), "prefix", entitlement), new BigInteger("1234"), keyPair, true);
    verify(mockedPKI).createX509Certificate(any(String.class), argThat(new ListContainsContentUrl("/someorg/Awesome+Environment+%231" + CONTENT_URL, CONTENT_ID)), any(Set.class), any(Date.class), any(Date.class), any(KeyPair.class), any(BigInteger.class), any(String.class));
}
Also used : KeyPair(java.security.KeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) Set(java.util.Set) HashSet(java.util.HashSet) Environment(org.candlepin.model.Environment) BigInteger(java.math.BigInteger) EnvironmentContent(org.candlepin.model.EnvironmentContent) Matchers.anyString(org.mockito.Matchers.anyString) Date(java.util.Date) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 12 with EnvironmentContent

use of org.candlepin.model.EnvironmentContent in project candlepin by candlepin.

the class DefaultEntitlementCertServiceAdapterTest method testURLEncoding.

@Test
@SuppressWarnings("checkstyle:indentation")
public void testURLEncoding() throws Exception {
    owner.setContentPrefix("/some org/$env/");
    // Setup an environment for the consumer:
    Environment e = this.mockEnvironment(new Environment("env1", "Awesome Environment #1", owner));
    e.getEnvironmentContent().add(new EnvironmentContent(e, content, true));
    this.consumer.setEnvironment(e);
    certServiceAdapter.createX509Certificate(consumer, owner, pool, entitlement, product, new HashSet<>(), getProductModels(product, new HashSet<>(), "prefix", entitlement), new BigInteger("1234"), keyPair, true);
    verify(mockedPKI).createX509Certificate(any(String.class), argThat(new ListContainsContentUrl("/some+org/Awesome+Environment+%231" + CONTENT_URL, CONTENT_ID)), any(Set.class), any(Date.class), any(Date.class), any(KeyPair.class), any(BigInteger.class), any(String.class));
}
Also used : KeyPair(java.security.KeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) Set(java.util.Set) HashSet(java.util.HashSet) Environment(org.candlepin.model.Environment) BigInteger(java.math.BigInteger) EnvironmentContent(org.candlepin.model.EnvironmentContent) Matchers.anyString(org.mockito.Matchers.anyString) Date(java.util.Date) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 13 with EnvironmentContent

use of org.candlepin.model.EnvironmentContent in project candlepin by candlepin.

the class EnvironmentTranslatorTest method initSourceObject.

@Override
protected Environment initSourceObject() {
    Environment source = new Environment();
    source.setId("test_id");
    source.setName("test_name");
    source.setDescription("test_description");
    source.setOwner(ownerTranslatorTest.initSourceObject());
    Set<EnvironmentContent> environmentContents = new HashSet<>();
    for (int i = 0; i < 3; ++i) {
        Content content = TestUtil.createContent("content-" + i);
        content.setUuid(content.getId() + "_uuid");
        EnvironmentContent environmentContent = new EnvironmentContent(source, content, true);
        environmentContents.add(environmentContent);
    }
    source.setEnvironmentContent(environmentContents);
    return source;
}
Also used : EnvironmentContent(org.candlepin.model.EnvironmentContent) Content(org.candlepin.model.Content) Environment(org.candlepin.model.Environment) EnvironmentContent(org.candlepin.model.EnvironmentContent) HashSet(java.util.HashSet)

Example 14 with EnvironmentContent

use of org.candlepin.model.EnvironmentContent in project candlepin by candlepin.

the class X509V3ExtensionUtil method createContent.

/*
     * createContent
     *
     * productArchList is a list of arch strings parse from
     *   product attributes.
     */
public List<Content> createContent(Set<ProductContent> productContent, Product sku, String contentPrefix, Map<String, EnvironmentContent> promotedContent, Consumer consumer, Product product) {
    List<Content> toReturn = new ArrayList<>();
    boolean enableEnvironmentFiltering = config.getBoolean(ConfigProperties.ENV_CONTENT_FILTERING);
    // Return only the contents that are arch appropriate
    Set<ProductContent> archApproriateProductContent = filterContentByContentArch(productContent, consumer, product);
    List<String> skuDisabled = sku.getSkuDisabledContentIds();
    List<String> skuEnabled = sku.getSkuEnabledContentIds();
    for (ProductContent pc : archApproriateProductContent) {
        Content content = new Content();
        if (enableEnvironmentFiltering && consumer.getEnvironmentId() != null && !promotedContent.containsKey(pc.getContent().getId())) {
            log.debug("Skipping content not promoted to environment: {}", pc.getContent());
            continue;
        }
        // Augment the content path with the prefix if it is passed in
        String contentPath = this.createFullContentPath(contentPrefix, pc);
        content.setId(pc.getContent().getId());
        content.setType(pc.getContent().getType());
        content.setName(pc.getContent().getName());
        content.setLabel(pc.getContent().getLabel());
        content.setVendor(pc.getContent().getVendor());
        content.setPath(contentPath);
        content.setGpgUrl(pc.getContent().getGpgUrl());
        // Set content model's arches here, inheriting from the product if
        // they are not set on the content.
        List<String> archesList = new ArrayList<>();
        Set<String> contentArches = Arch.parseArches(pc.getContent().getArches());
        if (contentArches.isEmpty()) {
            archesList.addAll(Arch.parseArches(product.getAttributeValue(Product.Attributes.ARCHITECTURE)));
        } else {
            archesList.addAll(Arch.parseArches(pc.getContent().getArches()));
        }
        content.setArches(archesList);
        Boolean enabled = pc.isEnabled();
        // sku level content enable override. if on both lists, active wins.
        if (skuDisabled.contains(pc.getContent().getId())) {
            enabled = false;
        }
        if (skuEnabled.contains(pc.getContent().getId())) {
            enabled = true;
        }
        // Check if we should override the enabled flag due to setting on promoted content
        if (enableEnvironmentFiltering && consumer.getEnvironmentId() != null) {
            // we know content has been promoted at this point
            Boolean enabledOverride = promotedContent.get(pc.getContent().getId()).getEnabled();
            if (enabledOverride != null) {
                log.debug("overriding enabled flag: {}", enabledOverride);
                enabled = enabledOverride;
            }
        }
        // only included if not the default value of true
        if (!enabled) {
            content.setEnabled(enabled);
        }
        // Include metadata expiry if specified on the content
        if (pc.getContent().getMetadataExpire() != null) {
            content.setMetadataExpire(pc.getContent().getMetadataExpire());
        }
        // Include required tags if specified on the content set
        String requiredTags = pc.getContent().getRequiredTags();
        if ((requiredTags != null) && !requiredTags.equals("")) {
            StringTokenizer st = new StringTokenizer(requiredTags, ",");
            List<String> tagList = new ArrayList<>();
            while (st.hasMoreElements()) {
                tagList.add((String) st.nextElement());
            }
            content.setRequiredTags(tagList);
        }
        toReturn.add(content);
    }
    return toReturn;
}
Also used : StringTokenizer(java.util.StringTokenizer) ProductContent(org.candlepin.model.ProductContent) Content(org.candlepin.model.dto.Content) EnvironmentContent(org.candlepin.model.EnvironmentContent) ArrayList(java.util.ArrayList) ProductContent(org.candlepin.model.ProductContent)

Example 15 with EnvironmentContent

use of org.candlepin.model.EnvironmentContent in project candlepin by candlepin.

the class DefaultEntitlementCertServiceAdapter method doEntitlementCertGeneration.

/**
 * @param entitlements a map of entitlements indexed by pool ids to generate
 *        the certs of
 * @param productMap a map of respective products indexed by pool id
 * @throws IOException
 * @throws GeneralSecurityException
 * @return entitlementCerts the respective entitlement certs indexed by pool
 *         id
 */
private Map<String, EntitlementCertificate> doEntitlementCertGeneration(Consumer consumer, Map<String, Product> productMap, Map<String, PoolQuantity> poolQuantities, Map<String, Entitlement> entitlements, boolean save) throws GeneralSecurityException, IOException {
    Owner owner = ownerCurator.findOwnerById(consumer.getOwnerId());
    log.debug("Generating entitlement cert for entitlements");
    KeyPair keyPair = keyPairCurator.getConsumerKeyPair(consumer);
    byte[] pemEncodedKeyPair = pki.getPemEncoded(keyPair.getPrivate());
    Map<String, CertificateSerial> serialMap = new HashMap<>();
    for (Entry<String, PoolQuantity> entry : poolQuantities.entrySet()) {
        // No need to persist the cert serial here as the IDs are generated on object creation.
        serialMap.put(entry.getKey(), new CertificateSerial(entry.getValue().getPool().getEndDate()));
    }
    Map<String, EntitlementCertificate> entitlementCerts = new HashMap<>();
    for (Entry<String, PoolQuantity> entry : poolQuantities.entrySet()) {
        Pool pool = entry.getValue().getPool();
        Entitlement ent = entitlements.get(entry.getKey());
        CertificateSerial serial = serialMap.get(entry.getKey());
        Product product = productMap.get(entry.getKey());
        log.info("Generating entitlement cert for pool: {} quantity: {} entitlement id: {}", pool, ent.getQuantity(), ent.getId());
        Set<Product> products = new HashSet<>(productCurator.getPoolProvidedProductsCached(pool));
        // If creating a certificate for a distributor, we need
        // to add any derived products as well so that their content
        // is available in the upstream certificate.
        products.addAll(getDerivedProductsForDistributor(pool, consumer));
        products.add(product);
        Map<String, EnvironmentContent> promotedContent = getPromotedContent(consumer);
        String contentPrefix = getContentPrefix(consumer, owner, true);
        log.info("Creating X509 cert for product: {}", product);
        log.debug("Provided products: {}", products);
        List<org.candlepin.model.dto.Product> productModels = v3extensionUtil.createProducts(product, products, contentPrefix, promotedContent, consumer, pool);
        X509Certificate x509Cert = createX509Certificate(consumer, owner, pool, ent, product, products, productModels, BigInteger.valueOf(serial.getId()), keyPair, true);
        log.debug("Getting PEM encoded cert.");
        String pem = new String(this.pki.getPemEncoded(x509Cert));
        if (shouldGenerateV3(consumer)) {
            log.debug("Generating v3 entitlement data");
            byte[] payloadBytes = v3extensionUtil.createEntitlementDataPayload(productModels, consumer, pool, ent.getQuantity());
            String payload = "-----BEGIN ENTITLEMENT DATA-----\n";
            payload += Util.toBase64(payloadBytes);
            payload += "-----END ENTITLEMENT DATA-----\n";
            byte[] bytes = pki.getSHA256WithRSAHash(new ByteArrayInputStream(payloadBytes));
            String signature = "-----BEGIN RSA SIGNATURE-----\n";
            signature += Util.toBase64(bytes);
            signature += "-----END RSA SIGNATURE-----\n";
            pem += payload + signature;
        }
        // Build a skeleton cert as part of the entitlement processing.
        EntitlementCertificate cert = new EntitlementCertificate();
        cert.setKeyAsBytes(pemEncodedKeyPair);
        cert.setCert(pem);
        if (save) {
            cert.setEntitlement(ent);
        }
        if (log.isDebugEnabled()) {
            log.debug("Generated cert serial number: {}", serial.getId());
            log.debug("Key: {}", cert.getKey());
            log.debug("Cert: {}", cert.getCert());
        }
        entitlementCerts.put(entry.getKey(), cert);
    }
    // Serials need to be saved before the certs.
    log.debug("Persisting new certificate serials");
    serialCurator.saveOrUpdateAll(serialMap);
    // certs with their serials and add them to the entitlements.
    for (Entry<String, PoolQuantity> entry : poolQuantities.entrySet()) {
        CertificateSerial nextSerial = serialMap.get(entry.getKey());
        if (nextSerial == null) {
            // This should never happen, but checking to be safe.
            throw new RuntimeException("Certificate serial not found for entitlement during cert generation.");
        }
        EntitlementCertificate nextCert = entitlementCerts.get(entry.getKey());
        if (nextCert == null) {
            // This should never happen, but checking to be safe.
            throw new RuntimeException("Entitlement certificate not found for entitlement during cert generation");
        }
        nextCert.setSerial(nextSerial);
        if (save) {
            Entitlement ent = entitlements.get(entry.getKey());
            ent.getCertificates().add(nextCert);
        }
    }
    if (save) {
        log.info("Persisting certs.");
        entCertCurator.saveOrUpdateAll(entitlementCerts.values(), false, false);
    }
    return entitlementCerts;
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Owner(org.candlepin.model.Owner) KeyPair(java.security.KeyPair) EntitlementCertificate(org.candlepin.model.EntitlementCertificate) HashMap(java.util.HashMap) CertificateSerial(org.candlepin.model.CertificateSerial) Product(org.candlepin.model.Product) EnvironmentContent(org.candlepin.model.EnvironmentContent) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

EnvironmentContent (org.candlepin.model.EnvironmentContent)17 HashSet (java.util.HashSet)9 Environment (org.candlepin.model.Environment)9 HashMap (java.util.HashMap)6 Content (org.candlepin.model.Content)6 Date (java.util.Date)4 Test (org.junit.Test)4 Matchers.anyString (org.mockito.Matchers.anyString)4 KeyPair (java.security.KeyPair)3 Entitlement (org.candlepin.model.Entitlement)3 Product (org.candlepin.model.Product)3 ApiOperation (io.swagger.annotations.ApiOperation)2 ApiResponses (io.swagger.annotations.ApiResponses)2 BigInteger (java.math.BigInteger)2 X509Certificate (java.security.cert.X509Certificate)2 ArrayList (java.util.ArrayList)2 LinkedHashSet (java.util.LinkedHashSet)2 Set (java.util.Set)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2