Search in sources :

Example 56 with UnauthorizedException

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);
    }
}
Also used : WorkflowOperationInstance(org.opencastproject.workflow.api.WorkflowOperationInstance) ResumableWorkflowOperationHandler(org.opencastproject.workflow.api.ResumableWorkflowOperationHandler) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) WorkflowOperationResult(org.opencastproject.workflow.api.WorkflowOperationResult) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) WorkflowException(org.opencastproject.workflow.api.WorkflowException) JobCanceledException(org.opencastproject.util.JobCanceledException) WorkflowOperationAbortedException(org.opencastproject.workflow.api.WorkflowOperationAbortedException) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException)

Example 57 with UnauthorizedException

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());
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) WorkflowOperationDefinitionImpl(org.opencastproject.workflow.api.WorkflowOperationDefinitionImpl) WorkflowDefinitionImpl(org.opencastproject.workflow.api.WorkflowDefinitionImpl) AuthorizationService(org.opencastproject.security.api.AuthorizationService) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) Test(org.junit.Test)

Example 58 with UnauthorizedException

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();
}
Also used : NotFoundException(org.opencastproject.util.NotFoundException) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONProvider(org.apache.cxf.jaxrs.provider.json.JSONProvider) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException)

Example 59 with UnauthorizedException

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);
}
Also used : WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) IngestException(org.opencastproject.ingest.api.IngestException)

Example 60 with UnauthorizedException

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();
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) Set(java.util.Set) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Source(org.opencastproject.index.service.api.IndexService.Source) Date(java.util.Date) Opt(com.entwinemedia.fn.data.Opt) JSONObject(org.json.simple.JSONObject) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)133 NotFoundException (org.opencastproject.util.NotFoundException)109 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)52 IOException (java.io.IOException)42 SchedulerConflictException (org.opencastproject.scheduler.api.SchedulerConflictException)39 SchedulerTransactionLockException (org.opencastproject.scheduler.api.SchedulerTransactionLockException)38 HttpResponse (org.apache.http.HttpResponse)37 SeriesException (org.opencastproject.series.api.SeriesException)36 WebApplicationException (javax.ws.rs.WebApplicationException)33 Path (javax.ws.rs.Path)29 RestQuery (org.opencastproject.util.doc.rest.RestQuery)29 ParseException (java.text.ParseException)28 MediaPackage (org.opencastproject.mediapackage.MediaPackage)27 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)26 AccessControlList (org.opencastproject.security.api.AccessControlList)22 ArrayList (java.util.ArrayList)21 User (org.opencastproject.security.api.User)21 WorkflowDatabaseException (org.opencastproject.workflow.api.WorkflowDatabaseException)21 HttpGet (org.apache.http.client.methods.HttpGet)19 Date (java.util.Date)18