@Test
  public void testCreatedDevPoolAttributes() {
    Owner owner = TestUtil.createOwner("o");
    List<ProductData> devProdDTOs = new ArrayList<ProductData>();
    Product p1 = TestUtil.createProduct("dev-product", "Dev Product");
    p1.setAttribute("support_level", "Premium");
    p1.setAttribute("expires_after", "47");
    Product p2 = TestUtil.createProduct("provided-product1", "Provided Product 1");
    Product p3 = TestUtil.createProduct("provided-product2", "Provided Product 2");
    devProdDTOs.add(p1.toDTO());
    devProdDTOs.add(p2.toDTO());
    devProdDTOs.add(p3.toDTO());
    Consumer devSystem = TestUtil.createConsumer(owner);
    devSystem.setFact("dev_sku", p1.getId());
    devSystem.addInstalledProduct(new ConsumerInstalledProduct(p2));
    devSystem.addInstalledProduct(new ConsumerInstalledProduct(p3));
    when(productAdapter.getProductsByIds(eq(owner), any(List.class))).thenReturn(devProdDTOs);

    this.mockProducts(owner, p1, p2, p3);
    this.mockProductImport(owner, p1, p2, p3);
    this.mockContentImport(owner, Collections.<String, Content>emptyMap());

    Pool created = entitler.assembleDevPool(devSystem, devSystem.getFact("dev_sku"));
    Calendar cal = Calendar.getInstance();
    cal.setTime(created.getStartDate());
    cal.add(Calendar.DAY_OF_YEAR, 47);
    assertEquals(created.getEndDate(), cal.getTime());
    assertEquals("true", created.getAttributeValue(Pool.Attributes.DEVELOPMENT_POOL));
    assertEquals(devSystem.getUuid(), created.getAttributeValue(Pool.Attributes.REQUIRES_CONSUMER));
    assertEquals(p1.getId(), created.getProductId());
    assertEquals(2, created.getProvidedProducts().size());
    assertEquals("Premium", created.getProduct().getAttributeValue("support_level"));
    assertEquals(1L, created.getQuantity().longValue());
  }
  @Test
  public void testDevPoolCreationAtBindNoFailMissingInstalledProduct() throws Exception {
    Owner owner = TestUtil.createOwner("o");
    List<ProductData> devProdDTOs = new ArrayList<ProductData>();
    Product p = TestUtil.createProduct("test-product", "Test Product");
    Product ip1 = TestUtil.createProduct("test-product-installed-1", "Installed Test Product 1");
    Product ip2 = TestUtil.createProduct("test-product-installed-2", "Installed Test Product 2");
    devProdDTOs.add(p.toDTO());
    devProdDTOs.add(ip1.toDTO());

    Pool activePool = TestUtil.createPool(owner, p);
    List<Pool> activeList = new ArrayList<Pool>();
    activeList.add(activePool);

    Consumer devSystem = TestUtil.createConsumer(owner);
    devSystem.setFact("dev_sku", p.getId());
    devSystem.addInstalledProduct(new ConsumerInstalledProduct(ip1));
    devSystem.addInstalledProduct(new ConsumerInstalledProduct(ip2));

    when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false);
    when(poolCurator.hasActiveEntitlementPools(eq(owner), any(Date.class))).thenReturn(true);
    when(productAdapter.getProductsByIds(any(Owner.class), any(List.class)))
        .thenReturn(devProdDTOs);

    this.mockProducts(owner, p, ip1, ip2);
    this.mockProductImport(owner, p, ip1, ip2);
    this.mockContentImport(owner, Collections.<String, Content>emptyMap());

    Pool expectedPool = entitler.assembleDevPool(devSystem, p.getId());
    when(pm.createPool(any(Pool.class))).thenReturn(expectedPool);
    AutobindData ad = new AutobindData(devSystem);
    entitler.bindByProducts(ad);
  }
  @Test
  public void testDevPoolCreationAtBind() throws Exception {
    Owner owner = TestUtil.createOwner("o");
    List<ProductData> devProdDTOs = new ArrayList<ProductData>();
    Product p = TestUtil.createProduct("test-product", "Test Product");

    p.setAttribute("support_level", "Premium");
    devProdDTOs.add(p.toDTO());
    Pool activePool = TestUtil.createPool(owner, p);
    List<Pool> activeList = new ArrayList<Pool>();
    activeList.add(activePool);
    Pool devPool = mock(Pool.class);

    Consumer devSystem = TestUtil.createConsumer(owner);
    devSystem.setFact("dev_sku", p.getId());

    when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false);
    when(poolCurator.hasActiveEntitlementPools(eq(owner), any(Date.class))).thenReturn(true);
    when(productAdapter.getProductsByIds(eq(owner), any(List.class))).thenReturn(devProdDTOs);

    this.mockProducts(owner, p);
    this.mockProductImport(owner, p);
    this.mockContentImport(owner, Collections.<String, Content>emptyMap());

    when(pm.createPool(any(Pool.class))).thenReturn(devPool);
    when(devPool.getId()).thenReturn("test_pool_id");

    AutobindData ad = new AutobindData(devSystem);
    entitler.bindByProducts(ad);
    verify(pm).createPool(any(Pool.class));
  }
Exemple #4
0
  private void exportProducts(File baseDir, Consumer consumer) throws IOException {
    File productDir = new File(baseDir.getCanonicalPath(), "products");
    productDir.mkdir();

    Map<String, Product> products = new HashMap<String, Product>();
    for (Entitlement entitlement : consumer.getEntitlements()) {

      for (ProvidedProduct providedProduct : entitlement.getPool().getProvidedProducts()) {
        // Don't want to call the adapter if not needed, it can be expensive.
        if (!products.containsKey(providedProduct.getProductId())) {
          products.put(
              providedProduct.getProductId(),
              productAdapter.getProductById(providedProduct.getProductId()));
        }
      }

      // Don't forget the 'main' product!
      String productId = entitlement.getPool().getProductId();
      if (!products.containsKey(productId)) {
        products.put(productId, productAdapter.getProductById(productId));
      }
    }

    for (Product product : products.values()) {
      String path = productDir.getCanonicalPath();
      String productId = product.getId();
      File file = new File(path, productId + ".json");
      FileWriter writer = new FileWriter(file);
      productExporter.export(mapper, writer, product);
      writer.close();

      // Real products have a numeric id.
      if (StringUtils.isNumeric(product.getId())) {
        ProductCertificate cert = productAdapter.getProductCertificate(product);
        // XXX: not all product adapters implement getProductCertificate,
        // so just skip over this if we get null back
        // XXX: need to decide if the cert should always be in the export, or never.
        if (cert != null) {
          file = new File(productDir.getCanonicalPath(), product.getId() + ".pem");
          writer = new FileWriter(file);
          productCertExporter.export(writer, cert);
          writer.close();
        }
      }
    }
  }
  @Test
  public void testCreatedDevSkuWithNoSla() {
    Owner owner = TestUtil.createOwner("o");
    List<ProductData> devProdDTOs = new ArrayList<ProductData>();
    final Product p1 = TestUtil.createProduct("dev-product", "Dev Product");
    devProdDTOs.add(p1.toDTO());
    Consumer devSystem = TestUtil.createConsumer(owner);
    devSystem.setFact("dev_sku", p1.getId());

    when(productAdapter.getProductsByIds(eq(owner), any(List.class))).thenReturn(devProdDTOs);
    mockUpdateProduct(p1, owner);

    this.mockContentImport(owner, Collections.<String, Content>emptyMap());
    when(productManager.importProducts(eq(owner), any(Map.class), any(Map.class)))
        .thenAnswer(
            new Answer<ImportResult<Product>>() {
              @Override
              public ImportResult<Product> answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                Map<String, ProductData> productData = (Map<String, ProductData>) args[1];
                ImportResult<Product> importResult = new ImportResult<Product>();
                Map<String, Product> output = importResult.getCreatedEntities();

                // We need to copy the attributes from the product data to the product to
                // simulate a proper update.
                for (ProductData pdata : productData.values()) {
                  if (pdata != null) {
                    if (p1.getId().equals(pdata.getId())) {
                      p1.clearAttributes();
                      if (pdata.getAttributes() != null) {
                        for (ProductAttributeData attrib : pdata.getAttributes()) {
                          p1.setAttribute(attrib.getName(), attrib.getValue());
                        }
                      }

                      output.put(p1.getId(), p1);
                    } else {
                      Product product = new Product(pdata.getId(), pdata.getName());
                      // Do we care about this product? Probably not.
                      output.put(product.getId(), product);
                    }
                  }
                }

                return importResult;
              }
            });

    Pool created = entitler.assembleDevPool(devSystem, devSystem.getFact("dev_sku"));
    assertEquals(entitler.DEFAULT_DEV_SLA, created.getProduct().getAttributeValue("support_level"));
  }
  @Test(expected = ForbiddenException.class)
  public void testDevPoolCreationAtBindFailNotActive() throws Exception {
    Owner owner = TestUtil.createOwner("o");
    List<ProductData> devProdDTOs = new ArrayList<ProductData>();
    Product p = TestUtil.createProduct("test-product", "Test Product");
    devProdDTOs.add(p.toDTO());

    Consumer devSystem = TestUtil.createConsumer(owner);
    devSystem.setFact("dev_sku", p.getId());
    devSystem.addInstalledProduct(new ConsumerInstalledProduct(p));

    when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false);
    when(poolCurator.hasActiveEntitlementPools(eq(owner), any(Date.class))).thenReturn(false);
    when(productAdapter.getProductsByIds(any(Owner.class), any(List.class)))
        .thenReturn(devProdDTOs);
    when(ownerProductCurator.getProductById(eq(owner), eq(p.getId()))).thenReturn(p);

    AutobindData ad = new AutobindData(devSystem);
    entitler.bindByProducts(ad);
  }
  /**
   * Checks if the given pool provides any product with a content set which modifies the given
   * product ID.
   *
   * @param ent Entitlement to check.
   * @param modifiedProductId Product ID we're looking for a modifier to.
   * @return true if entitlement modifies the given product
   */
  public boolean modifies(Entitlement ent, String modifiedProductId) {
    Set<String> prodIdsToCheck = new HashSet<String>();
    prodIdsToCheck.add(ent.getPool().getProductId());
    for (ProvidedProduct pp : ent.getPool().getProvidedProducts()) {
      prodIdsToCheck.add(pp.getProductId());
    }

    for (String prodId : prodIdsToCheck) {
      Product p = productAdapter.getProductById(prodId);
      if (null == p) {
        String msg = i18n.tr("No product found for product ID {0}", prodId);
        log.error("No product found for product id " + prodId);
        throw new CuratorException(msg);
      } else {
        if (p.modifies(modifiedProductId)) {
          return true;
        }
      }
    }
    return false;
  }
 private Set<Product> getProvidedProducts(Pool pool, Subscription sub) {
   Set<Product> providedProducts = new HashSet<Product>();
   // TODO: eliminate the use of subscription here by looking up products in a batch
   // somehow, and we can eliminate all use of subscriptions during bind.
   if (sub != null) {
     // need to use the sub provided products if creating an
     // entitlement for derived pool who's sub specifies a
     // sub product.
     boolean derived = pool.hasAttribute("pool_derived");
     providedProducts =
         derived && sub.getDerivedProduct() != null
             ? sub.getDerivedProvidedProducts()
             : sub.getProvidedProducts();
   } else {
     // If this pool doesn't have a subscription associated with it, we need to
     // lookup all the Product objects manually:
     for (ProvidedProduct providedProduct : pool.getProvidedProducts()) {
       providedProducts.add(productAdapter.getProductById(providedProduct.getProductId()));
     }
   }
   return providedProducts;
 }
  @Test
  public void testDevPoolCreationAtBindFailNoSkuProduct() throws Exception {
    Owner owner = TestUtil.createOwner("o");
    List<ProductData> devProdDTOs = new ArrayList<ProductData>();
    Product p = TestUtil.createProduct("test-product", "Test Product");
    Product ip = TestUtil.createProduct("test-product-installed", "Installed Test Product");
    devProdDTOs.add(ip.toDTO());

    Pool activePool = TestUtil.createPool(owner, p);
    List<Pool> activeList = new ArrayList<Pool>();
    activeList.add(activePool);

    Consumer devSystem = TestUtil.createConsumer(owner);
    devSystem.setFact("dev_sku", p.getId());
    devSystem.addInstalledProduct(new ConsumerInstalledProduct(ip));

    when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false);
    when(poolCurator.hasActiveEntitlementPools(eq(owner), any(Date.class))).thenReturn(true);
    when(productAdapter.getProductsByIds(any(Owner.class), any(List.class)))
        .thenReturn(devProdDTOs);
    when(ownerProductCurator.getProductById(eq(owner), eq(p.getId()))).thenReturn(p);
    when(ownerProductCurator.getProductById(eq(owner), eq(ip.getId()))).thenReturn(ip);

    mockUpdateProduct(p, owner);
    mockUpdateProduct(ip, owner);
    mockProductImport(owner, p, ip);
    mockContentImport(owner, new Content[] {});

    AutobindData ad = new AutobindData(devSystem);
    try {
      entitler.bindByProducts(ad);
    } catch (ForbiddenException fe) {
      assertEquals(
          i18n.tr("SKU product not available to this development unit: ''{0}''", p.getId()),
          fe.getMessage());
    }
  }
Exemple #10
0
  private void exportProducts(File baseDir, Consumer consumer) throws IOException {
    File productDir = new File(baseDir.getCanonicalPath(), "products");
    productDir.mkdir();

    Map<String, Product> products = new HashMap<String, Product>();
    for (Entitlement entitlement : consumer.getEntitlements()) {
      Pool pool = entitlement.getPool();

      for (Product providedProduct : pool.getProvidedProducts()) {
        products.put(providedProduct.getId(), providedProduct);
      }

      // Don't forget the 'main' product!
      Product product = pool.getProduct();
      products.put(product.getId(), product);

      // Also need to check for sub products
      Product derivedProduct = pool.getDerivedProduct();
      if (derivedProduct != null) {
        products.put(derivedProduct.getId(), derivedProduct);
      }

      for (Product derivedProvidedProduct : pool.getDerivedProvidedProducts()) {
        products.put(derivedProvidedProduct.getId(), derivedProvidedProduct);
      }
    }

    for (Product product : products.values()) {
      // Clear the owner and UUID so they can be re-generated/assigned on import
      // product.setUuid(null);
      // product.setOwner(null);

      String path = productDir.getCanonicalPath();
      String productId = product.getId();
      File file = new File(path, productId + ".json");
      FileWriter writer = null;
      try {
        writer = new FileWriter(file);
        productExporter.export(mapper, writer, product);
      } finally {
        if (writer != null) {
          writer.close();
        }
      }

      // Real products have a numeric id.
      if (StringUtils.isNumeric(product.getId())) {
        ProductCertificate cert =
            productAdapter.getProductCertificate(consumer.getOwner(), product.getId());

        // XXX: not all product adapters implement getProductCertificate,
        // so just skip over this if we get null back
        // XXX: need to decide if the cert should always be in the export, or never.
        if (cert != null) {
          file = new File(productDir.getCanonicalPath(), product.getId() + ".pem");
          writer = new FileWriter(file);
          productCertExporter.export(writer, cert);
          writer.close();
        }
      }
    }
  }
Exemple #11
0
  @SuppressWarnings("unchecked")
  @Test
  public void exportProducts() throws Exception {
    config.setProperty(ConfigProperties.SYNC_WORK_DIR, "/tmp/");
    Consumer consumer = mock(Consumer.class);
    Entitlement ent = mock(Entitlement.class);
    ProvidedProduct pp = mock(ProvidedProduct.class);
    Pool pool = mock(Pool.class);
    Rules mrules = mock(Rules.class);
    Principal principal = mock(Principal.class);
    IdentityCertificate idcert = new IdentityCertificate();

    Set<ProvidedProduct> ppset = new HashSet<ProvidedProduct>();
    ppset.add(pp);

    Set<Entitlement> entitlements = new HashSet<Entitlement>();
    entitlements.add(ent);

    Product prod = new Product("12345", "RHEL Product");
    prod.setMultiplier(1L);
    prod.setCreated(new Date());
    prod.setUpdated(new Date());
    prod.setHref("http://localhost");
    prod.setAttributes(Collections.EMPTY_SET);

    Product prod1 = new Product("MKT-prod", "RHEL Product");
    prod1.setMultiplier(1L);
    prod1.setCreated(new Date());
    prod1.setUpdated(new Date());
    prod1.setHref("http://localhost");
    prod1.setAttributes(Collections.EMPTY_SET);

    ProductCertificate pcert = new ProductCertificate();
    pcert.setKey("euh0876puhapodifbvj094");
    pcert.setCert("hpj-08ha-w4gpoknpon*)&^%#");
    pcert.setCreated(new Date());
    pcert.setUpdated(new Date());

    when(pp.getProductId()).thenReturn("12345");
    when(pool.getProvidedProducts()).thenReturn(ppset);
    when(pool.getProductId()).thenReturn("MKT-prod");
    when(ent.getPool()).thenReturn(pool);
    when(mrules.getRules()).thenReturn("foobar");
    when(pki.getSHA256WithRSAHash(any(InputStream.class))).thenReturn("signature".getBytes());
    when(rc.getRules()).thenReturn(mrules);
    when(consumer.getEntitlements()).thenReturn(entitlements);
    when(psa.getProductById("12345")).thenReturn(prod);
    when(psa.getProductById("MKT-prod")).thenReturn(prod1);
    when(psa.getProductCertificate(any(Product.class))).thenReturn(pcert);
    when(pprov.get()).thenReturn(principal);
    when(principal.getUsername()).thenReturn("testUser");
    idcert.setSerial(new CertificateSerial(10L, new Date()));
    idcert.setKey("euh0876puhapodifbvj094");
    idcert.setCert("hpj-08ha-w4gpoknpon*)&^%#");
    idcert.setCreated(new Date());
    idcert.setUpdated(new Date());
    when(consumer.getIdCert()).thenReturn(idcert);

    KeyPair keyPair = createKeyPair();
    when(consumer.getKeyPair()).thenReturn(keyPair);
    when(pki.getPemEncoded(keyPair.getPrivateKey())).thenReturn("privateKey".getBytes());
    when(pki.getPemEncoded(keyPair.getPublicKey())).thenReturn("publicKey".getBytes());

    // FINALLY test this badboy
    Exporter e =
        new Exporter(
            ctc, me, ce, cte, re, ece, ecsa, pe, psa, pce, ec, ee, pki, config, exportRules, pprov);

    File export = e.getFullExport(consumer);

    // VERIFY
    assertNotNull(export);
    verifyContent(export, "export/products/12345.pem", new VerifyProductCert("12345.pem"));
    assertFalse(verifyHasEntry(export, "export/products/MKT-prod.pem"));
    FileUtils.deleteDirectory(export.getParentFile());
    assertTrue(new File("/tmp/consumer_export.zip").delete());
    assertTrue(new File("/tmp/12345.pem").delete());
  }
  public Set<X509ExtensionWrapper> prepareV1Extensions(
      Set<Product> products,
      Entitlement ent,
      String contentPrefix,
      Map<String, EnvironmentContent> promotedContent) {
    Set<X509ExtensionWrapper> result = new LinkedHashSet<X509ExtensionWrapper>();

    Set<String> entitledProductIds =
        entCurator.listEntitledProductIds(
            ent.getConsumer(), ent.getPool().getStartDate(), ent.getPool().getEndDate());

    int contentCounter = 0;
    boolean enableEnvironmentFiltering = config.getBoolean(ConfigProperties.ENV_CONTENT_FILTERING);

    Product skuProd = productAdapter.getProductById(ent.getPool().getProductId());

    for (Product prod : Collections2.filter(products, X509Util.PROD_FILTER_PREDICATE)) {
      result.addAll(extensionUtil.productExtensions(prod));
      Set<ProductContent> filteredContent =
          extensionUtil.filterProductContent(
              prod,
              ent,
              entCurator,
              promotedContent,
              enableEnvironmentFiltering,
              entitledProductIds);

      filteredContent =
          extensionUtil.filterContentByContentArch(filteredContent, ent.getConsumer(), prod);

      // Keep track of the number of content sets that are being added.
      contentCounter += filteredContent.size();

      result.addAll(
          extensionUtil.contentExtensions(
              filteredContent, contentPrefix, promotedContent, ent.getConsumer(), skuProd));
    }

    // For V1 certificates we're going to error out if we exceed a limit which is
    // likely going to generate a certificate too large for the CDN, and return an
    // informative error message to the user.
    if (contentCounter > X509ExtensionUtil.V1_CONTENT_LIMIT) {
      String cause =
          i18n.tr(
              "Too many content sets for certificate {0}. A newer "
                  + "client may be available to address this problem. "
                  + "See kbase https://access.redhat.com/knowledge/node/129003 for more "
                  + "information.",
              ent.getPool().getProductName());
      throw new CertificateSizeException(cause);
    }

    result.addAll(extensionUtil.subscriptionExtensions(ent));

    result.addAll(extensionUtil.entitlementExtensions(ent));
    result.addAll(extensionUtil.consumerExtensions(ent.getConsumer()));

    if (log.isDebugEnabled()) {
      for (X509ExtensionWrapper eWrapper : result) {
        log.debug(
            String.format("Extension %s with value %s", eWrapper.getOid(), eWrapper.getValue()));
      }
    }
    return result;
  }