Search in sources :

Example 11 with UnauthorizedException

use of io.cdap.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.

the class MonitorHandlerAuthorizationTest method testGetLatestRestartServiceInstanceStatusAuthorization.

@Test
public void testGetLatestRestartServiceInstanceStatusAuthorization() throws Exception {
    SystemServiceId systemServiceId = new SystemServiceId(SERVICE_NAME);
    MonitorHandler handler = createMonitorHandler(Authorizable.fromEntityId(systemServiceId), Arrays.asList(StandardPermission.GET));
    HttpRequest request = mock(HttpRequest.class);
    HttpResponder responder = mock(HttpResponder.class);
    AuthenticationTestContext.actAsPrincipal(UNPRIVILEGED_PRINCIPAL);
    try {
        handler.getLatestRestartServiceInstanceStatus(request, responder, SERVICE_NAME);
    } catch (UnauthorizedException e) {
    // expected
    }
    AuthenticationTestContext.actAsPrincipal(MASTER_PRINCIPAL);
    handler.getLatestRestartServiceInstanceStatus(request, responder, SERVICE_NAME);
}
Also used : SystemServiceId(io.cdap.cdap.proto.id.SystemServiceId) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpResponder(io.cdap.http.HttpResponder) MonitorHandler(io.cdap.cdap.gateway.handlers.MonitorHandler) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) Test(org.junit.Test)

Example 12 with UnauthorizedException

use of io.cdap.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.

the class MonitorHandlerAuthorizationTest method testSetServiceInstanceAuthorization.

@Test
public void testSetServiceInstanceAuthorization() throws Exception {
    SystemServiceId systemServiceId = new SystemServiceId(SERVICE_NAME);
    MonitorHandler handler = createMonitorHandler(Authorizable.fromEntityId(systemServiceId), Arrays.asList(StandardPermission.UPDATE));
    Instances instances = new Instances(1);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "system/services/service/instances", Unpooled.copiedBuffer(GSON.toJson(instances), StandardCharsets.UTF_8));
    HttpResponder responder = mock(HttpResponder.class);
    AuthenticationTestContext.actAsPrincipal(UNPRIVILEGED_PRINCIPAL);
    try {
        handler.setServiceInstance(request, responder, SERVICE_NAME);
    } catch (UnauthorizedException e) {
    // expected
    }
    AuthenticationTestContext.actAsPrincipal(MASTER_PRINCIPAL);
    handler.setServiceInstance(request, responder, SERVICE_NAME);
}
Also used : SystemServiceId(io.cdap.cdap.proto.id.SystemServiceId) Instances(io.cdap.cdap.proto.Instances) HttpResponder(io.cdap.http.HttpResponder) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) MonitorHandler(io.cdap.cdap.gateway.handlers.MonitorHandler) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) Test(org.junit.Test)

Example 13 with UnauthorizedException

use of io.cdap.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.

the class TimePartitionedFileSetTest method validateInputPaths.

/**
 * Validates that the output configuration of the tpfs, when instantiated with (time - start * minutes) as
 * input start time and (time + end * minutes) as input end time, returns the expected list of paths.
 */
private void validateInputPaths(long time, long start, long end, final String... expected) throws IOException, DatasetManagementException, InterruptedException, TransactionFailureException, UnauthorizedException {
    Map<String, String> arguments = Maps.newHashMap();
    TimePartitionedFileSetArguments.setInputStartTime(arguments, time + start * MINUTE);
    TimePartitionedFileSetArguments.setInputEndTime(arguments, time + end * MINUTE);
    final TimePartitionedFileSet tpfs = dsFrameworkUtil.getInstance(TPFS_INSTANCE, arguments);
    TransactionAware txAwareDataset = (TransactionAware) tpfs;
    dsFrameworkUtil.newInMemoryTransactionExecutor(txAwareDataset).execute(new TransactionExecutor.Subroutine() {

        @Override
        public void apply() throws Exception {
            Map<String, String> inputConfig = tpfs.getInputFormatConfiguration();
            String inputs = inputConfig.get(FileInputFormat.INPUT_DIR);
            Assert.assertNotNull(inputs);
            if (expected.length == 0) {
                Assert.assertTrue(inputs.isEmpty());
                return;
            }
            String[] inputPaths = inputs.split(",");
            Assert.assertEquals(expected.length, inputPaths.length);
            // order is not guaranteed.
            Arrays.sort(expected);
            Arrays.sort(inputPaths);
            for (int i = 0; i < expected.length; i++) {
                // every input path is absolute, whereas expected paths are relative
                Assert.assertTrue("path #" + i + " does not match", inputPaths[i].endsWith(expected[i]));
            }
        }
    });
}
Also used : TransactionAware(org.apache.tephra.TransactionAware) TransactionExecutor(org.apache.tephra.TransactionExecutor) TimePartitionedFileSet(io.cdap.cdap.api.dataset.lib.TimePartitionedFileSet) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) TransactionFailureException(org.apache.tephra.TransactionFailureException) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) DataSetException(io.cdap.cdap.api.dataset.DataSetException) DatasetManagementException(io.cdap.cdap.api.dataset.DatasetManagementException) IOException(java.io.IOException)

Example 14 with UnauthorizedException

use of io.cdap.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method resetLogLevels.

private void resetLogLevels(FullHttpRequest request, HttpResponder responder, String namespace, String appName, String appVersion, String type, String programName, String runId) throws Exception {
    ProgramType programType = getProgramType(type);
    try {
        Set<String> loggerNames = parseBody(request, SET_STRING_TYPE);
        lifecycleService.resetProgramLogLevels(new ApplicationId(namespace, appName, appVersion).program(programType, programName), loggerNames == null ? Collections.emptySet() : loggerNames, runId);
        responder.sendStatus(HttpResponseStatus.OK);
    } catch (JsonSyntaxException e) {
        throw new BadRequestException("Invalid JSON in body");
    } catch (SecurityException e) {
        throw new UnauthorizedException("Unauthorized to reset the log levels");
    }
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) BadRequestException(io.cdap.cdap.common.BadRequestException) ProgramType(io.cdap.cdap.proto.ProgramType) ApplicationId(io.cdap.cdap.proto.id.ApplicationId)

Example 15 with UnauthorizedException

use of io.cdap.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method getLatestRuns.

/**
 * Returns the latest runs for all program runnables that are passed into the data. The data is an array of
 * Json objects where each object must contain the following three elements: appId, programType, and programId.
 * <p>
 * Example input:
 * <pre><code>
 * [{"appId": "App1", "programType": "Service", "programId": "Service1"},
 *  {"appId": "App1", "programType": "Workflow", "programId": "testWorkflow"},
 *  {"appId": "App2", "programType": "Workflow", "programId": "DataPipelineWorkflow"}]
 * </code></pre>
 * </p><p>
 * </p><p>
 * The response will be an array of JsonObjects each of which will contain the three input parameters
 * as well as 2 fields, "runs" which is a list of the latest run records and "statusCode" which maps to the
 * status code for the data in that JsonObjects.
 * </p><p>
 * If an error occurs in the input (for the example above, workflow in app1 does not exist),
 * then all JsonObjects for which the parameters have a valid status will have the count field but all JsonObjects
 * for which the parameters do not have a valid status will have an error message and statusCode.
 * </p><p>
 * For example, if there is no workflow in App1 in the data above, then the response would be 200 OK with following
 * possible data:
 * </p>
 * <pre><code>
 * [{"appId": "App1", "programType": "Service", "programId": "Service1",
 * "statusCode": 200, "runs": [...]},
 * {"appId": "App1", "programType": "Workflow", "programId": "testWorkflow", "statusCode": 404,
 * "error": "Program 'testWorkflow' is not found"},
 *  {"appId": "App2", "programType": "Workflow", "programId": "DataPipelineWorkflow", "runnableId": "Flowlet1",
 *  "statusCode": 200, "runs": [...]}]
 * </code></pre>
 */
@POST
@Path("/runs")
public void getLatestRuns(FullHttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId) throws Exception {
    List<BatchProgram> programs = validateAndGetBatchInput(request, BATCH_PROGRAMS_TYPE);
    List<ProgramId> programIds = programs.stream().map(batchProgram -> new ProgramId(namespaceId, batchProgram.getAppId(), batchProgram.getProgramType(), batchProgram.getProgramId())).collect(Collectors.toList());
    List<BatchProgramHistory> response = new ArrayList<>(programs.size());
    List<ProgramHistory> result = lifecycleService.getRunRecords(programIds, ProgramRunStatus.ALL, 0, Long.MAX_VALUE, 1);
    for (ProgramHistory programHistory : result) {
        ProgramId programId = programHistory.getProgramId();
        Exception exception = programHistory.getException();
        BatchProgram batchProgram = new BatchProgram(programId.getApplication(), programId.getType(), programId.getProgram());
        if (exception == null) {
            response.add(new BatchProgramHistory(batchProgram, HttpResponseStatus.OK.code(), null, programHistory.getRuns()));
        } else if (exception instanceof NotFoundException) {
            response.add(new BatchProgramHistory(batchProgram, HttpResponseStatus.NOT_FOUND.code(), exception.getMessage(), Collections.emptyList()));
        } else if (exception instanceof UnauthorizedException) {
            response.add(new BatchProgramHistory(batchProgram, HttpResponseStatus.FORBIDDEN.code(), exception.getMessage(), Collections.emptyList()));
        } else {
            response.add(new BatchProgramHistory(batchProgram, HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), exception.getMessage(), Collections.emptyList()));
        }
    }
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(response));
}
Also used : BatchProgramSchedule(io.cdap.cdap.proto.BatchProgramSchedule) AuditDetail(io.cdap.cdap.common.security.AuditDetail) RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) BatchProgramResult(io.cdap.cdap.proto.BatchProgramResult) TypeToken(com.google.gson.reflect.TypeToken) MRJobInfoFetcher(io.cdap.cdap.app.mapreduce.MRJobInfoFetcher) MRJobInfo(io.cdap.cdap.proto.MRJobInfo) GsonBuilder(com.google.gson.GsonBuilder) ScheduledRuntime(io.cdap.cdap.proto.ScheduledRuntime) ProgramScheduleStatus(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleStatus) ScheduleId(io.cdap.cdap.proto.id.ScheduleId) Map(java.util.Map) ProgramStatus(io.cdap.cdap.proto.ProgramStatus) ScheduleDetail(io.cdap.cdap.proto.ScheduleDetail) EnumSet(java.util.EnumSet) HttpRequest(io.netty.handler.codec.http.HttpRequest) Set(java.util.Set) Reader(java.io.Reader) Constraint(io.cdap.cdap.internal.schedule.constraint.Constraint) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) ProgramScheduleRecord(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleRecord) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) StandardCharsets(java.nio.charset.StandardCharsets) Id(io.cdap.cdap.common.id.Id) ApplicationSpecificationAdapter(io.cdap.cdap.internal.app.ApplicationSpecificationAdapter) TriggerCodec(io.cdap.cdap.internal.app.runtime.schedule.trigger.TriggerCodec) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) Joiner(com.google.common.base.Joiner) Singleton(com.google.inject.Singleton) RunRecord(io.cdap.cdap.proto.RunRecord) GET(javax.ws.rs.GET) SatisfiableTrigger(io.cdap.cdap.internal.app.runtime.schedule.trigger.SatisfiableTrigger) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) ArrayList(java.util.ArrayList) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) Nullable(javax.annotation.Nullable) Charsets(com.google.common.base.Charsets) AuditPolicy(io.cdap.cdap.common.security.AuditPolicy) BatchRunnableInstances(io.cdap.cdap.proto.BatchRunnableInstances) ProgramLiveInfo(io.cdap.cdap.proto.ProgramLiveInfo) ProgramLifecycleService(io.cdap.cdap.internal.app.services.ProgramLifecycleService) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) ConflictException(io.cdap.cdap.common.ConflictException) NotImplementedException(io.cdap.cdap.common.NotImplementedException) ServiceInstances(io.cdap.cdap.proto.ServiceInstances) InputStreamReader(java.io.InputStreamReader) ProgramRuntimeService(io.cdap.cdap.app.runtime.ProgramRuntimeService) Futures(com.google.common.util.concurrent.Futures) ProgramSpecification(io.cdap.cdap.api.ProgramSpecification) Schedulers(io.cdap.cdap.internal.app.runtime.schedule.store.Schedulers) RunCountResult(io.cdap.cdap.proto.RunCountResult) BatchProgramStatus(io.cdap.cdap.proto.BatchProgramStatus) JsonObject(com.google.gson.JsonObject) NamespaceQueryAdmin(io.cdap.cdap.common.namespace.NamespaceQueryAdmin) RandomEndpointStrategy(io.cdap.cdap.common.discovery.RandomEndpointStrategy) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Inject(com.google.inject.Inject) ProgramScheduleService(io.cdap.cdap.scheduler.ProgramScheduleService) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ServiceUnavailableException(io.cdap.cdap.common.ServiceUnavailableException) EndpointStrategy(io.cdap.cdap.common.discovery.EndpointStrategy) QueryParam(javax.ws.rs.QueryParam) Gson(com.google.gson.Gson) DefaultValue(javax.ws.rs.DefaultValue) Objects(com.google.common.base.Objects) ProgramHistory(io.cdap.cdap.proto.ProgramHistory) ConstraintCodec(io.cdap.cdap.internal.app.runtime.schedule.constraint.ConstraintCodec) DELETE(javax.ws.rs.DELETE) Containers(io.cdap.cdap.proto.Containers) Function(com.google.common.base.Function) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) BatchProgramStart(io.cdap.cdap.proto.BatchProgramStart) BatchRunnable(io.cdap.cdap.proto.BatchRunnable) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Collectors(java.util.stream.Collectors) ProgramStatusTrigger(io.cdap.cdap.internal.app.runtime.schedule.trigger.ProgramStatusTrigger) List(java.util.List) Type(java.lang.reflect.Type) CaseInsensitiveEnumTypeAdapterFactory(io.cdap.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory) Constants(io.cdap.cdap.common.conf.Constants) NotFoundException(io.cdap.cdap.common.NotFoundException) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) BatchProgramHistory(io.cdap.cdap.proto.BatchProgramHistory) BatchProgramCount(io.cdap.cdap.proto.BatchProgramCount) HashMap(java.util.HashMap) ProgramType(io.cdap.cdap.proto.ProgramType) JsonElement(com.google.gson.JsonElement) NotRunningProgramLiveInfo(io.cdap.cdap.proto.NotRunningProgramLiveInfo) HashSet(java.util.HashSet) Trigger(io.cdap.cdap.api.schedule.Trigger) BatchProgram(io.cdap.cdap.proto.BatchProgram) Instances(io.cdap.cdap.proto.Instances) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) AbstractAppFabricHttpHandler(io.cdap.cdap.gateway.handlers.util.AbstractAppFabricHttpHandler) ProtoTrigger(io.cdap.cdap.proto.ProtoTrigger) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) HttpResponder(io.cdap.http.HttpResponder) JsonSyntaxException(com.google.gson.JsonSyntaxException) SchedulerException(io.cdap.cdap.internal.app.runtime.schedule.SchedulerException) ProgramId(io.cdap.cdap.proto.id.ProgramId) BadRequestException(io.cdap.cdap.common.BadRequestException) ProgramSchedule(io.cdap.cdap.internal.app.runtime.schedule.ProgramSchedule) Store(io.cdap.cdap.app.store.Store) TimeUnit(java.util.concurrent.TimeUnit) ServiceDiscoverable(io.cdap.cdap.common.service.ServiceDiscoverable) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) ArrayList(java.util.ArrayList) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) NotFoundException(io.cdap.cdap.common.NotFoundException) ProgramId(io.cdap.cdap.proto.id.ProgramId) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) IOException(java.io.IOException) ConflictException(io.cdap.cdap.common.ConflictException) NotImplementedException(io.cdap.cdap.common.NotImplementedException) ServiceUnavailableException(io.cdap.cdap.common.ServiceUnavailableException) NotFoundException(io.cdap.cdap.common.NotFoundException) JsonSyntaxException(com.google.gson.JsonSyntaxException) SchedulerException(io.cdap.cdap.internal.app.runtime.schedule.SchedulerException) BadRequestException(io.cdap.cdap.common.BadRequestException) BatchProgramHistory(io.cdap.cdap.proto.BatchProgramHistory) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) ProgramHistory(io.cdap.cdap.proto.ProgramHistory) BatchProgramHistory(io.cdap.cdap.proto.BatchProgramHistory) BatchProgram(io.cdap.cdap.proto.BatchProgram) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Aggregations

UnauthorizedException (io.cdap.cdap.security.spi.authorization.UnauthorizedException)98 Test (org.junit.Test)44 IOException (java.io.IOException)38 HttpResponder (io.cdap.http.HttpResponder)28 ApplicationId (io.cdap.cdap.proto.id.ApplicationId)26 BadRequestException (io.cdap.cdap.common.BadRequestException)22 NotFoundException (io.cdap.cdap.common.NotFoundException)22 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)20 JsonSyntaxException (com.google.gson.JsonSyntaxException)18 DatasetManagementException (io.cdap.cdap.api.dataset.DatasetManagementException)18 NamespaceNotFoundException (io.cdap.cdap.common.NamespaceNotFoundException)18 MonitorHandler (io.cdap.cdap.gateway.handlers.MonitorHandler)18 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)18 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)18 ExecutionException (java.util.concurrent.ExecutionException)18 ConflictException (io.cdap.cdap.common.ConflictException)16 StandardPermission (io.cdap.cdap.proto.security.StandardPermission)16 SystemServiceId (io.cdap.cdap.proto.id.SystemServiceId)14 HttpRequest (io.netty.handler.codec.http.HttpRequest)14 HashSet (java.util.HashSet)14