use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class WorkflowOperationWorker method resume.
/**
* Resumes a previously suspended workflow operation. Note that only workflow operation handlers that implement
* {@link ResumableWorkflowOperationHandler} can be resumed.
*
* @return the workflow operation result
* @throws WorkflowOperationException
* if executing the workflow operation handler fails
* @throws WorkflowException
* if there is a problem processing the workflow
* @throws IllegalStateException
* if the workflow operation cannot be resumed
*/
public WorkflowOperationResult resume() throws WorkflowOperationException, WorkflowException, IllegalStateException, UnauthorizedException {
WorkflowOperationInstance operation = workflow.getCurrentOperation();
// Make sure we have a (suitable) handler
if (handler == null) {
// If there is no handler for the operation, yet we are supposed to run it, we must fail
logger.warn("No handler available to resume operation '{}'", operation.getTemplate());
throw new IllegalStateException("Unable to find a workflow handler for '" + operation.getTemplate() + "'");
} else if (!(handler instanceof ResumableWorkflowOperationHandler)) {
throw new IllegalStateException("An attempt was made to resume a non-resumable operation");
}
ResumableWorkflowOperationHandler resumableHandler = (ResumableWorkflowOperationHandler) handler;
operation.setState(OperationState.RUNNING);
service.update(workflow);
try {
WorkflowOperationResult result = resumableHandler.resume(workflow, null, properties);
return result;
} catch (Exception e) {
operation.setState(OperationState.FAILED);
if (e instanceof WorkflowOperationException)
throw (WorkflowOperationException) e;
throw new WorkflowOperationException(e);
}
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class WorkflowServiceImplAuthzTest method testWorkflowWithoutSecurityPolicy.
@Test
public void testWorkflowWithoutSecurityPolicy() throws Exception {
// Mock up an authorization service that always returns "false" for hasPermission()
AuthorizationService authzService = EasyMock.createNiceMock(AuthorizationService.class);
EasyMock.expect(authzService.getActiveAcl((MediaPackage) EasyMock.anyObject())).andReturn(Tuple.tuple(new AccessControlList(), AclScope.Series)).anyTimes();
EasyMock.expect(authzService.hasPermission((MediaPackage) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(false).anyTimes();
EasyMock.replay(authzService);
service.setAuthorizationService(authzService);
dao.setAuthorizationService(authzService);
// Create the workflow and its dependent object graph
WorkflowDefinitionImpl def = new WorkflowDefinitionImpl();
def.add(new WorkflowOperationDefinitionImpl("op1", "op1", null, true));
MediaPackage mp = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().createNew();
// As an instructor, create a workflow
userResponder.setResponse(instructor1);
WorkflowInstance workflow = service.start(def, mp);
service.suspend(workflow.getId());
// Ensure that this instructor can access the workflow
try {
service.getWorkflowById(workflow.getId());
assertEquals(1, service.countWorkflowInstances());
} catch (Exception e) {
fail(e.getMessage());
}
// Ensure the organization admin can access that workflow
userResponder.setResponse(DEFAULT_ORG_ADMIN);
try {
service.getWorkflowById(workflow.getId());
assertEquals(1, service.countWorkflowInstances());
} catch (Exception e) {
fail(e.getMessage());
}
// Ensure the global admin can access that workflow
userResponder.setResponse(globalAdmin);
try {
service.getWorkflowById(workflow.getId());
assertEquals(1, service.countWorkflowInstances());
} catch (Exception e) {
fail(e.getMessage());
}
// Ensure the other instructor can not see the workflow, since there is no security policy granting access
userResponder.setResponse(instructor2);
try {
service.getWorkflowById(workflow.getId());
fail();
} catch (UnauthorizedException e) {
// expected
}
assertEquals(0, service.countWorkflowInstances());
// Ensure the instructor from a different org can not see the workflow, even though they share a role
organizationResponder.setResponse(otherOrganization);
userResponder.setResponse(instructorFromDifferentOrg);
try {
service.getWorkflowById(workflow.getId());
fail();
} catch (Exception e) {
// expected
}
assertEquals(0, service.countWorkflowInstances());
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class RestPublisher method activate.
/**
* Activates this rest publisher
*/
@SuppressWarnings("unchecked")
protected void activate(ComponentContext componentContext) {
logger.debug("activate()");
baseServerUri = componentContext.getBundleContext().getProperty(OpencastConstants.SERVER_URL_PROPERTY);
this.componentContext = componentContext;
// TODO: Replace this with something a little nicer
fourOhFour = "The resource you requested does not exist.";
servletRegistrationMap = new ConcurrentHashMap<>();
providers = new ArrayList<>();
JSONProvider jsonProvider = new OpencastJSONProvider();
jsonProvider.setIgnoreNamespaces(true);
jsonProvider.setNamespaceMap(NAMESPACE_MAP);
providers.add(jsonProvider);
providers.add(new ExceptionMapper<NotFoundException>() {
@Override
public Response toResponse(NotFoundException e) {
return Response.status(404).entity(fourOhFour).type(MediaType.TEXT_PLAIN).build();
}
});
providers.add(new ExceptionMapper<UnauthorizedException>() {
@Override
public Response toResponse(UnauthorizedException e) {
return Response.status(HttpStatus.SC_UNAUTHORIZED).entity("unauthorized").type(MediaType.TEXT_PLAIN).build();
}
});
try {
jaxRsTracker = new JaxRsServiceTracker();
bundleTracker = new StaticResourceBundleTracker(componentContext.getBundleContext());
} catch (InvalidSyntaxException e) {
throw new IllegalStateException(e);
}
jaxRsTracker.open();
bundleTracker.open();
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class IngestServiceImpl method getWorkflowDefinition.
private WorkflowDefinition getWorkflowDefinition(String workflowDefinitionID, MediaPackage mediapackage) throws NotFoundException, WorkflowDatabaseException, IngestException {
// If the workflow definition and instance ID are null, use the default, or throw if there is none
if (isBlank(workflowDefinitionID)) {
String mediaPackageId = mediapackage.getIdentifier().compact();
if (schedulerService != null) {
logger.info("Determining workflow template for ingested mediapckage {} from capture event {}", mediapackage, mediaPackageId);
try {
Map<String, String> recordingProperties = schedulerService.getCaptureAgentConfiguration(mediaPackageId);
workflowDefinitionID = recordingProperties.get(CaptureParameters.INGEST_WORKFLOW_DEFINITION);
if (isBlank(workflowDefinitionID)) {
workflowDefinitionID = defaultWorkflowDefinionId;
logger.debug("No workflow set. Falling back to default.");
}
if (isBlank(workflowDefinitionID)) {
throw new IngestException("No value found for key '" + CaptureParameters.INGEST_WORKFLOW_DEFINITION + "' from capture event configuration of scheduler event '" + mediaPackageId + "'");
}
logger.info("Ingested event {} will be processed using workflow '{}'", mediapackage, workflowDefinitionID);
} catch (NotFoundException e) {
logger.warn("Specified capture event {} was not found", mediaPackageId);
} catch (UnauthorizedException e) {
throw new IllegalStateException(e);
} catch (SchedulerException e) {
logger.warn("Unable to get the workflow definition id from scheduler event {}: {}", mediaPackageId, ExceptionUtils.getMessage(e));
throw new IngestException(e);
}
} else {
logger.warn("Scheduler service not bound, unable to determine the workflow template to use for ingested mediapckage {}", mediapackage);
}
} else {
logger.info("Ingested mediapackage {} is processed using workflow template '{}', specified during ingest", mediapackage, workflowDefinitionID);
}
// Use the default workflow definition if nothing was determined
if (isBlank(workflowDefinitionID) && defaultWorkflowDefinionId != null) {
logger.info("Using default workflow definition '{}' to process ingested mediapackage {}", defaultWorkflowDefinionId, mediapackage);
workflowDefinitionID = defaultWorkflowDefinionId;
}
// Check if the workflow definition is valid
if (StringUtils.isNotBlank(workflowDefinitionID) && StringUtils.isNotBlank(defaultWorkflowDefinionId)) {
try {
workflowService.getWorkflowDefinitionById(workflowDefinitionID);
} catch (WorkflowDatabaseException e) {
throw new IngestException(e);
} catch (NotFoundException nfe) {
logger.warn("Workflow definition {} not found, using default workflow {} instead", workflowDefinitionID, defaultWorkflowDefinionId);
workflowDefinitionID = defaultWorkflowDefinionId;
}
}
// Have we been able to find a workflow definition id?
if (isBlank(workflowDefinitionID)) {
ingestStatistics.failed();
throw new IllegalStateException("Can not ingest a workflow without a workflow definition or an existing instance. No default definition is specified");
}
// Let's make sure the workflow definition exists
return workflowService.getWorkflowDefinitionById(workflowDefinitionID);
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class AbstractEventEndpoint method applyAclToEvent.
@POST
@Path("{eventId}/access")
@RestQuery(name = "applyAclToEvent", description = "Immediate application of an ACL to an event", returnDescription = "Status code", pathParameters = { @RestParameter(name = "eventId", isRequired = true, description = "The event ID", type = STRING) }, restParameters = { @RestParameter(name = "acl", isRequired = true, description = "The ACL to apply", type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The ACL has been successfully applied"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Unable to parse the given ACL"), @RestResponse(responseCode = SC_NOT_FOUND, description = "The the event has not been found"), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "Not authorized to perform this action"), @RestResponse(responseCode = SC_INTERNAL_SERVER_ERROR, description = "Internal error") })
public Response applyAclToEvent(@PathParam("eventId") String eventId, @FormParam("acl") String acl) throws NotFoundException, UnauthorizedException, SearchIndexException, IndexServiceException {
final AccessControlList accessControlList;
try {
accessControlList = AccessControlParser.parseAcl(acl);
} catch (Exception e) {
logger.warn("Unable to parse ACL '{}'", acl);
return badRequest();
}
try {
final Opt<Event> optEvent = getIndexService().getEvent(eventId, getIndex());
if (optEvent.isNone()) {
logger.warn("Unable to find the event '{}'", eventId);
return notFound();
}
Source eventSource = getIndexService().getEventSource(optEvent.get());
if (eventSource == Source.ARCHIVE) {
if (getAclService().applyAclToEpisode(eventId, accessControlList, Option.<ConfiguredWorkflowRef>none())) {
return ok();
} else {
logger.warn("Unable to find the event '{}'", eventId);
return notFound();
}
} else if (eventSource == Source.WORKFLOW) {
logger.warn("An ACL cannot be edited while an event is part of a current workflow because it might" + " lead to inconsistent ACLs i.e. changed after distribution so that the old ACL is still " + "being used by the distribution channel.");
JSONObject json = new JSONObject();
json.put("Error", "Unable to edit an ACL for a current workflow.");
return conflict(json.toJSONString());
} else {
MediaPackage mediaPackage = getIndexService().getEventMediapackage(optEvent.get());
mediaPackage = getAuthorizationService().setAcl(mediaPackage, AclScope.Episode, accessControlList).getA();
getSchedulerService().updateEvent(eventId, Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), some(mediaPackage), Opt.<Map<String, String>>none(), Opt.<Map<String, String>>none(), Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
return ok();
}
} catch (AclServiceException e) {
logger.error("Error applying acl '{}' to event '{}' because: {}", accessControlList, eventId, ExceptionUtils.getStackTrace(e));
return serverError();
} catch (SchedulerException e) {
logger.error("Error applying ACL to scheduled event {} because {}", eventId, ExceptionUtils.getStackTrace(e));
return serverError();
}
}
Aggregations