@Test
  public void refreshPoolsCleanupPoolThatLostVirtLimit() {
    List<Subscription> subscriptions = Util.newList();
    List<Pool> pools = Util.newList();
    Subscription s = TestUtil.createSubscription(getOwner(), TestUtil.createProduct());
    s.setId("01923");
    subscriptions.add(s);
    Pool p = TestUtil.createPool(s.getProduct());
    p.setSubscriptionId(s.getId());
    p.setAttribute(PoolManager.DELETE_FLAG, "true");
    pools.add(p);

    when(mockSubAdapter.getSubscriptions(any(Owner.class))).thenReturn(subscriptions);
    when(mockPoolCurator.listAvailableEntitlementPools(
            any(Consumer.class),
            any(Owner.class),
            anyString(),
            any(Date.class),
            anyBoolean(),
            anyBoolean()))
        .thenReturn(pools);

    List<PoolUpdate> updates = new LinkedList();
    updates.add(new PoolUpdate(p, false, true, false));
    when(poolRulesMock.updatePools(s, pools)).thenReturn(updates);

    this.manager.getRefresher().add(getOwner()).run();
    verify(this.mockPoolCurator, times(1)).delete(any(Pool.class));
  }
  @Test
  public void refreshPoolsCreatingPoolsForExistingSubscriptions() {
    List<Subscription> subscriptions = Util.newList();
    List<Pool> pools = Util.newList();
    Subscription s = TestUtil.createSubscription(getOwner(), TestUtil.createProduct());
    subscriptions.add(s);
    when(mockSubAdapter.getSubscriptions(any(Owner.class))).thenReturn(subscriptions);
    when(mockPoolCurator.listAvailableEntitlementPools(
            any(Consumer.class),
            any(Owner.class),
            anyString(),
            any(Date.class),
            anyBoolean(),
            anyBoolean()))
        .thenReturn(pools);

    List<Pool> newPools = new LinkedList<Pool>();
    Pool p = TestUtil.createPool(s.getProduct());
    p.setSubscriptionId(s.getId());
    newPools.add(p);
    when(poolRulesMock.createPools(s)).thenReturn(newPools);

    this.manager.getRefresher().add(getOwner()).run();
    verify(this.mockPoolCurator, times(1)).create(any(Pool.class));
  }
  @Test
  public void testRefreshPoolsRemovesExpiredSubscriptionsAlongWithItsPoolsAndEnts() {
    PreUnbindHelper preHelper = mock(PreUnbindHelper.class);

    Date expiredStart = TestUtil.createDate(2004, 5, 5);
    Date expiredDate = TestUtil.createDate(2005, 5, 5);

    List<Subscription> subscriptions = Util.newList();

    Subscription sub = TestUtil.createSubscription(getOwner(), TestUtil.createProduct());
    sub.setStartDate(expiredStart);
    sub.setEndDate(expiredDate);
    sub.setId("123");
    subscriptions.add(sub);

    when(mockSubAdapter.getSubscriptions(any(Owner.class))).thenReturn(subscriptions);

    List<Pool> pools = Util.newList();
    Pool p = TestUtil.createPool(sub.getOwner(), sub.getProduct());
    p.setSubscriptionId(sub.getId());
    p.setStartDate(expiredStart);
    p.setEndDate(expiredDate);
    p.setConsumed(1L);
    pools.add(p);

    when(mockPoolCurator.lockAndLoad(any(Pool.class))).thenReturn(p);

    when(mockPoolCurator.listAvailableEntitlementPools(
            any(Consumer.class),
            any(Owner.class),
            anyString(),
            any(Date.class),
            anyBoolean(),
            anyBoolean()))
        .thenReturn(pools);

    List<Entitlement> poolEntitlements = Util.newList();
    Entitlement ent = TestUtil.createEntitlement();
    ent.setPool(p);
    ent.setQuantity(1);
    poolEntitlements.add(ent);

    when(mockPoolCurator.entitlementsIn(eq(p))).thenReturn(poolEntitlements);

    ValidationResult result = new ValidationResult();
    when(preHelper.getResult()).thenReturn(result);

    this.manager.getRefresher().add(sub.getOwner()).run();

    verify(mockSubAdapter).deleteSubscription(eq(sub));
    verify(mockPoolCurator).delete(eq(p));

    // Verify the entitlement was removed.
    verify(entCertAdapterMock).revokeEntitlementCertificates(eq(ent));
    verify(entitlementCurator).delete(eq(ent));
  }
  @Test
  public void getBodyTest() throws IOException {
    TeeHttpServletRequest tee = new TeeHttpServletRequest(request);

    // Map content types to whether they should be logged as text or base64 encoded
    Map<String, Boolean> types = new HashMap<String, Boolean>();
    types.put(MediaType.APPLICATION_JSON, true);
    types.put(MediaType.APPLICATION_ATOM_XML, true);
    types.put(MediaType.TEXT_PLAIN, true);
    types.put(MediaType.TEXT_HTML, true);
    types.put(MediaType.TEXT_XML, true);
    types.put(MediaType.APPLICATION_FORM_URLENCODED, true);
    types.put(MediaType.APPLICATION_OCTET_STREAM, false);
    types.put("multipart/form-data", false);
    types.put("application/zip", false);

    for (String type : types.keySet()) {
      when(request.getContentType()).thenReturn(type);
      if (types.get(type)) {
        assertEquals(type + " failed!", "this is my body", tee.getBody());
      } else {
        assertEquals(type + " failed!", Util.toBase64("this is my body".getBytes()), tee.getBody());
      }
    }
  }
Exemple #5
0
  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    // Load the default production rules:
    InputStream is = this.getClass().getResourceAsStream(RulesCurator.DEFAULT_RULES_FILE);
    Rules rules = new Rules(Util.readFile(is));
    when(rulesCuratorMock.getUpdated()).thenReturn(new Date());
    when(rulesCuratorMock.getRules()).thenReturn(rules);
    when(cacheProvider.get()).thenReturn(cache);
    provider = new JsRunnerProvider(rulesCuratorMock, cacheProvider);
    quantityRules = new QuantityRules(provider.get());

    owner = new Owner("Test Owner " + TestUtil.randomInt());
    product = TestUtil.createProduct();
    pool = TestUtil.createPool(owner, product);
    pool.setId("fakepoolid");

    consumer = TestUtil.createConsumer(owner);
    Entitlement e = TestUtil.createEntitlement(owner, consumer, pool, new EntitlementCertificate());

    Set<Entitlement> entSet = new HashSet<Entitlement>();
    entSet.add(e);

    pool.setEntitlements(entSet);
    pool.getProduct().setAttribute("multi-entitlement", "yes");
    pool.getProduct().setAttribute("stacking_id", "1");
  }
  @Test
  public void testEntitleByProductsEmptyArray() throws Exception {
    Product product = TestUtil.createProduct();
    List<Pool> pools = Util.newList();
    Pool pool1 = TestUtil.createPool(product);
    pools.add(pool1);
    Date now = new Date();

    ValidationResult result = mock(ValidationResult.class);

    // Setup an installed product for the consumer, we'll make the bind request
    // with no products specified, so this should get used instead:
    String[] installedPids = new String[] {product.getId()};
    ComplianceStatus mockCompliance = new ComplianceStatus(now);
    mockCompliance.addNonCompliantProduct(installedPids[0]);
    when(complianceRules.getStatus(any(Consumer.class), any(Date.class)))
        .thenReturn(mockCompliance);

    when(mockPoolCurator.listAvailableEntitlementPools(
            any(Consumer.class),
            any(Owner.class),
            anyString(),
            eq(now),
            anyBoolean(),
            anyBoolean()))
        .thenReturn(pools);

    when(mockPoolCurator.lockAndLoad(any(Pool.class))).thenReturn(pool1);
    when(enforcerMock.preEntitlement(any(Consumer.class), any(Pool.class), anyInt()))
        .thenReturn(result);

    when(result.isSuccessful()).thenReturn(true);

    List<PoolQuantity> bestPools = new ArrayList<PoolQuantity>();
    bestPools.add(new PoolQuantity(pool1, 1));
    when(autobindRules.selectBestPools(
            any(Consumer.class),
            any(String[].class),
            any(List.class),
            any(ComplianceStatus.class),
            any(String.class),
            any(Set.class)))
        .thenReturn(bestPools);

    // Make the call but provide a null array of product IDs (simulates healing):
    manager.entitleByProducts(TestUtil.createConsumer(o), null, now);

    verify(autobindRules)
        .selectBestPools(
            any(Consumer.class),
            eq(installedPids),
            any(List.class),
            eq(mockCompliance),
            any(String.class),
            any(Set.class));
  }
 @Test
 public void testRefreshPoolsForDeactivatingPools() {
   List<Subscription> subscriptions = Util.newList();
   List<Pool> pools = Util.newList();
   Pool p = TestUtil.createPool(TestUtil.createProduct());
   p.setSubscriptionId("112");
   pools.add(p);
   when(mockSubAdapter.getSubscriptions(any(Owner.class))).thenReturn(subscriptions);
   when(mockPoolCurator.listAvailableEntitlementPools(
           any(Consumer.class),
           any(Owner.class),
           anyString(),
           any(Date.class),
           anyBoolean(),
           anyBoolean()))
       .thenReturn(pools);
   this.manager.getRefresher().add(getOwner()).run();
   verify(this.manager).deletePool(same(p));
 }
 @Before
 public void setUp() {
   MockitoAnnotations.initMocks(this);
   // Load the default production rules:
   InputStream is = this.getClass().getResourceAsStream(RulesCurator.DEFAULT_RULES_FILE);
   Rules rules = new Rules(Util.readFile(is));
   when(rulesCuratorMock.getUpdated()).thenReturn(new Date());
   when(rulesCuratorMock.getRules()).thenReturn(rules);
   provider = new JsRunnerProvider(rulesCuratorMock);
   poolTypeRules = new PoolComplianceTypeRules(provider.get());
 }
  @Override
  public boolean validateUser(String username, String password) {
    User user = this.userCurator.findByLogin(username);
    String hashedPassword = Util.hash(password);

    if (user != null && password != null && hashedPassword != null) {
      return hashedPassword.equals(user.getHashedPassword());
    }

    return false;
  }
  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    // Load the default production rules:
    InputStream is = this.getClass().getResourceAsStream(RULES_FILE);
    Rules rules = new Rules(Util.readFile(is));
    when(rulesCuratorMock.getUpdated()).thenReturn(new Date());
    when(rulesCuratorMock.getRules()).thenReturn(rules);
    provider = new JsRulesProvider(rulesCuratorMock);
    compliance = new ComplianceRules(provider.get(), entCurator);
    owner = new Owner("test");
  }
  public static JobDetail forProduct(Product product, Boolean lazy) {
    JobDataMap map = new JobDataMap();
    map.put(JobStatus.TARGET_TYPE, JobStatus.TargetType.PRODUCT);
    map.put(JobStatus.TARGET_ID, product.getId());
    map.put(LAZY_REGEN, lazy);

    JobDetail detail =
        newJob(RefreshPoolsForProductJob.class)
            .withIdentity("refresh_pools_for_product" + Util.generateUUID())
            .requestRecovery(true) // recover the job upon restarts
            .usingJobData(map)
            .build();

    return detail;
  }
Exemple #12
0
  @SuppressWarnings("unchecked")
  @Test
  public void testEntitleWithADate() throws Exception {
    Product product = TestUtil.createProduct();
    List<Pool> pools = Util.newList();
    Pool pool1 = TestUtil.createPool(product);
    pools.add(pool1);
    Pool pool2 = TestUtil.createPool(product);
    pools.add(pool2);
    Date now = new Date();

    ValidationResult result = mock(ValidationResult.class);

    when(mockPoolCurator.listAvailableEntitlementPools(
            any(Consumer.class),
            any(Owner.class),
            any(String.class),
            eq(now),
            anyBoolean(),
            anyBoolean()))
        .thenReturn(pools);
    when(mockPoolCurator.lockAndLoad(any(Pool.class))).thenReturn(pool1);
    when(enforcerMock.preEntitlement(any(Consumer.class), any(Pool.class), anyInt()))
        .thenReturn(result);

    when(result.isSuccessful()).thenReturn(true);

    List<PoolQuantity> bestPools = new ArrayList<PoolQuantity>();
    bestPools.add(new PoolQuantity(pool1, 1));
    when(autobindRules.selectBestPools(
            any(Consumer.class),
            any(String[].class),
            any(List.class),
            any(ComplianceStatus.class),
            any(String.class),
            any(Set.class)))
        .thenReturn(bestPools);

    List<Entitlement> e =
        manager.entitleByProducts(TestUtil.createConsumer(o), new String[] {product.getId()}, now);

    assertNotNull(e);
    assertEquals(e.size(), 1);
  }
Exemple #13
0
  /**
   * Schedules the generation of a consumer export. This job starts immediately.
   *
   * @param consumer the target consumer
   * @param cdnLabel
   * @param webAppPrefix
   * @param apiUrl
   * @return a JobDetail representing the job to be started.
   */
  public static JobDetail scheduleExport(
      Consumer consumer,
      String cdnLabel,
      String webAppPrefix,
      String apiUrl,
      Map<String, String> extensionData) {
    JobDataMap map = new JobDataMap();
    map.put(JobStatus.OWNER_ID, consumer.getOwner().getKey());
    map.put(JobStatus.TARGET_TYPE, JobStatus.TargetType.CONSUMER);
    map.put(JobStatus.TARGET_ID, consumer.getUuid());
    map.put(CDN_LABEL, cdnLabel);
    map.put(WEBAPP_PREFIX, webAppPrefix);
    map.put(API_URL, apiUrl);
    map.put(EXTENSION_DATA, extensionData);

    return newJob(ExportJob.class)
        .withIdentity("export_" + Util.generateUUID())
        .usingJobData(map)
        .build();
  }
Exemple #14
0
 private Rules rulesFromFile(String path) {
   InputStream is = this.getClass().getResourceAsStream(path);
   Rules result = new Rules(Util.readFile(is));
   result.setRulesSource(Rules.RulesSourceEnum.DEFAULT);
   return result;
 }
  private EntitlementCertificate generateEntitlementCert(
      Entitlement entitlement, Subscription sub, Product product, boolean thisIsUeberCert)
      throws GeneralSecurityException, IOException {

    log.info("Generating entitlement cert.");

    KeyPair keyPair = keyPairCurator.getConsumerKeyPair(entitlement.getConsumer());
    CertificateSerial serial = new CertificateSerial(entitlement.getEndDate());
    // We need the sequence generated id before we create the EntitlementCertificate,
    // otherwise we could have used cascading create
    serial = serialCurator.create(serial);

    Set<Product> products = new HashSet<Product>(getProvidedProducts(entitlement.getPool(), sub));

    // 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(sub, entitlement));

    log.info("Creating X509 cert.");
    X509Certificate x509Cert =
        createX509Certificate(
            entitlement,
            product,
            products,
            BigInteger.valueOf(serial.getId()),
            keyPair,
            !thisIsUeberCert);

    EntitlementCertificate cert = new EntitlementCertificate();
    cert.setSerial(serial);
    cert.setKeyAsBytes(pki.getPemEncoded(keyPair.getPrivate()));

    products.add(product);
    Map<String, EnvironmentContent> promotedContent = getPromotedContent(entitlement);
    String contentPrefix = getContentPrefix(entitlement, !thisIsUeberCert);

    log.info("Getting PEM encoded cert.");
    String pem = new String(this.pki.getPemEncoded(x509Cert));

    if (shouldGenerateV3(entitlement)) {
      byte[] payloadBytes =
          v3extensionUtil.createEntitlementDataPayload(
              products, entitlement, contentPrefix, promotedContent);
      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;
    }

    cert.setCert(pem);

    cert.setEntitlement(entitlement);

    if (log.isDebugEnabled()) {
      log.debug("Generated cert serial number: " + serial.getId());
      log.debug("Key: " + cert.getKey());
      log.debug("Cert: " + cert.getCert());
    }

    log.info("Persisting cert.");
    entitlement.getCertificates().add(cert);
    entCertCurator.create(cert);
    return cert;
  }