use of org.candlepin.common.exceptions.ForbiddenException in project candlepin by candlepin.
the class ManifestManagerTest method verifyCdnExistsBeforeSchedulingManifestGeneration.
@Test
public void verifyCdnExistsBeforeSchedulingManifestGeneration() throws Exception {
Owner owner = TestUtil.createOwner();
Consumer consumer = this.createMockConsumer(owner, true);
Cdn cdn = new Cdn("test-cdn", "Test CDN", "");
String webAppPrefix = "webapp-prefix";
String apiUrl = "api-url";
Map<String, String> extData = new HashMap<>();
when(consumerCurator.verifyAndLookupConsumer(eq(consumer.getUuid()))).thenReturn(consumer);
when(cdnCurator.lookupByLabel(eq(cdn.getLabel()))).thenReturn(null);
try {
manager.generateManifestAsync(consumer.getUuid(), owner.getKey(), cdn.getLabel(), webAppPrefix, apiUrl, extData);
fail("Expected ForbiddenException not thrown");
} catch (Exception e) {
assertTrue(e instanceof ForbiddenException);
String expectedMsg = String.format("A CDN with label %s does not exist on this system.", cdn.getLabel());
assertEquals(e.getMessage(), expectedMsg);
}
}
use of org.candlepin.common.exceptions.ForbiddenException in project candlepin by candlepin.
the class EntitlerTest method testDevPoolCreationAtBindFailNoSkuProduct.
@Test
public void testDevPoolCreationAtBindFailNoSkuProduct() throws Exception {
Owner owner = TestUtil.createOwner("o");
List<ProductData> devProdDTOs = new ArrayList<>();
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<>();
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.getId()), 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, owner);
try {
entitler.bindByProducts(ad);
} catch (ForbiddenException fe) {
assertEquals(i18n.tr("SKU product not available to this development unit: \"{0}\"", p.getId()), fe.getMessage());
}
}
use of org.candlepin.common.exceptions.ForbiddenException in project candlepin by candlepin.
the class ConsumerResource method createConsumerFromDTO.
public Consumer createConsumerFromDTO(ConsumerDTO consumer, ConsumerType type, Principal principal, String userName, String ownerKey, String activationKeys, boolean identityCertCreation) throws BadRequestException {
// API:registerConsumer
Set<String> keyStrings = splitKeys(activationKeys);
// Only let NoAuth principals through if there are activation keys to consider:
if ((principal instanceof NoAuthPrincipal) && keyStrings.isEmpty()) {
throw new ForbiddenException(i18n.tr("Insufficient permissions"));
}
validateOnKeyStrings(keyStrings, ownerKey, userName);
Owner owner = setupOwner(principal, ownerKey);
// Raise an exception if none of the keys specified exist for this owner.
List<ActivationKey> keys = checkActivationKeys(principal, owner, keyStrings);
userName = setUserName(consumer, principal, userName);
checkConsumerName(consumer);
validateViaConsumerType(consumer, type, keys, owner, userName, principal);
if (type.isType(ConsumerTypeEnum.SHARE)) {
// Share consumers do not need identity certificates so refuse to create them.
identityCertCreation = false;
validateShareConsumer(consumer, principal, keys);
// if there exists a share consumer between the two orgs, return it.
Consumer existingShareConsumer = consumerCurator.getSharingConsumer(owner, consumer.getRecipientOwnerKey());
if (existingShareConsumer != null) {
return existingShareConsumer;
}
consumer.setAutoheal(false);
} else {
// this is the default
consumer.setAutoheal(true);
if (StringUtils.isNotEmpty(consumer.getRecipientOwnerKey())) {
throw new BadRequestException(i18n.tr("Only share consumers can specify recipient owners"));
}
}
if (consumer.getServiceLevel() == null) {
consumer.setServiceLevel("");
}
// Sanitize the inbound facts
this.sanitizeConsumerFacts(consumer);
// If no service level was specified, and the owner has a default set, use it:
if (consumer.getServiceLevel().equals("") && owner.getDefaultServiceLevel() != null && !type.isType(ConsumerTypeEnum.SHARE)) {
consumer.setServiceLevel(owner.getDefaultServiceLevel());
}
Consumer consumerToCreate = new Consumer();
consumerToCreate.setOwner(owner);
populateEntity(consumerToCreate, consumer);
consumerToCreate.setType(type);
if (!type.isType(ConsumerTypeEnum.SHARE)) {
consumerToCreate.setCanActivate(subAdapter.canActivateSubscription(consumerToCreate));
}
HypervisorId hvsrId = consumerToCreate.getHypervisorId();
if (hvsrId != null && hvsrId.getHypervisorId() != null && !hvsrId.getHypervisorId().isEmpty()) {
// If a hypervisorId is supplied, make sure the consumer and owner are correct
hvsrId.setConsumer(consumerToCreate);
hvsrId.setOwner(owner);
}
updateCapabilities(consumerToCreate, null);
logNewConsumerDebugInfo(consumerToCreate, keys, type);
validateContentAccessMode(consumerToCreate, owner);
consumerBindUtil.validateServiceLevel(owner.getId(), consumerToCreate.getServiceLevel());
try {
Date createdDate = consumerToCreate.getCreated();
Date lastCheckIn = consumerToCreate.getLastCheckin();
// create sets created to current time.
consumerToCreate = consumerCurator.create(consumerToCreate);
// If we sent in a created date, we want it persisted at the update below
if (createdDate != null) {
consumerToCreate.setCreated(createdDate);
}
if (lastCheckIn != null) {
log.info("Creating with specific last check-in time: {}", lastCheckIn);
consumerToCreate.setLastCheckin(lastCheckIn);
}
if (identityCertCreation) {
IdentityCertificate idCert = generateIdCert(consumerToCreate, false);
consumerToCreate.setIdCert(idCert);
}
sink.emitConsumerCreated(consumerToCreate);
if (keys.size() > 0) {
consumerBindUtil.handleActivationKeys(consumerToCreate, keys, owner.isAutobindDisabled());
}
// Don't allow complianceRules to update entitlementStatus, because we're about to perform
// an update unconditionally.
complianceRules.getStatus(consumerToCreate, null, false, false);
consumerCurator.update(consumerToCreate);
log.info("Consumer {} created in org {}", consumerToCreate.getUuid(), consumerToCreate.getOwnerId());
return consumerToCreate;
} catch (CandlepinException ce) {
// If it is one of ours, rethrow it.
throw ce;
} catch (Exception e) {
log.error("Problem creating unit:", e);
throw new BadRequestException(i18n.tr("Problem creating unit {0}", consumer));
}
}
use of org.candlepin.common.exceptions.ForbiddenException in project candlepin by candlepin.
the class ConsumerResource method verifyPersonConsumer.
private void verifyPersonConsumer(ConsumerDTO consumer, ConsumerType type, Owner owner, String username, Principal principal) {
User user = null;
try {
user = userService.findByLogin(username);
} catch (UnsupportedOperationException e) {
log.warn("User service does not allow user lookups, cannot verify person consumer.");
}
if (user == null) {
throw new NotFoundException(i18n.tr("User with ID \"{0}\" could not be found."));
}
// has some association with the owner the consumer is destined for:
if (!principal.canAccess(owner, SubResource.NONE, Access.ALL) && !principal.hasFullAccess()) {
throw new ForbiddenException(i18n.tr("User \"{0}\" has no roles for organization \"{1}\"", user.getUsername(), owner.getKey()));
}
// TODO: Refactor out type specific checks?
if (type.isType(ConsumerTypeEnum.PERSON)) {
Consumer existing = consumerCurator.findByUser(user);
if (existing != null && this.consumerTypeCurator.getConsumerType(existing).isType(ConsumerTypeEnum.PERSON)) {
// TODO: This is not the correct error code for this situation!
throw new BadRequestException(i18n.tr("User \"{0}\" has already registered a personal consumer", user.getUsername()));
}
consumer.setName(user.getUsername());
}
}
use of org.candlepin.common.exceptions.ForbiddenException in project candlepin by candlepin.
the class ConsumerResource method deleteConsumer.
@ApiOperation(notes = "Removes a Consumer", value = "deleteConsumer")
@ApiResponses({ @ApiResponse(code = 403, message = ""), @ApiResponse(code = 404, message = "") })
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("{consumer_uuid}")
@Transactional
public void deleteConsumer(@PathParam("consumer_uuid") @Verify(Consumer.class) String uuid, @Context Principal principal) {
log.debug("Deleting consumer_uuid {}", uuid);
Consumer toDelete = consumerCurator.findByUuid(uuid);
this.consumerCurator.lock(toDelete);
try {
// We're about to delete this consumer; no need to regen/dirty its dependent
// entitlements or recalculate status.
this.poolManager.revokeAllEntitlements(toDelete, false);
} catch (ForbiddenException e) {
ConsumerType ctype = this.consumerTypeCurator.find(toDelete.getTypeId());
String msg = e.message().getDisplayMessage();
throw new ForbiddenException(i18n.tr("Cannot unregister {0} {1} because: {2}", ctype != null ? ctype.getLabel() : "unknown type", toDelete.getName(), msg), e);
}
consumerRules.onConsumerDelete(toDelete);
Event event = eventFactory.consumerDeleted(toDelete);
consumerCurator.delete(toDelete);
identityCertService.deleteIdentityCert(toDelete);
sink.queueEvent(event);
}
Aggregations