Search in sources :

Example 11 with EntityId

use of co.cask.cdap.proto.id.EntityId in project cdap by caskdata.

the class DefaultMetadataAdmin method filterAuthorizedSearchResult.

/**
   * Filter a list of {@link MetadataSearchResultRecord} that ensures the logged-in user has a privilege on
   *
   * @param results the {@link MetadataSearchResponse} to filter
   * @return filtered {@link MetadataSearchResponse}
   */
private MetadataSearchResponse filterAuthorizedSearchResult(MetadataSearchResponse results) throws Exception {
    Principal principal = authenticationContext.getPrincipal();
    final Predicate<EntityId> filter = authorizationEnforcer.createFilter(principal);
    return new MetadataSearchResponse(results.getSort(), results.getOffset(), results.getLimit(), results.getNumCursors(), results.getTotal(), ImmutableSet.copyOf(Iterables.filter(results.getResults(), new com.google.common.base.Predicate<MetadataSearchResultRecord>() {

        @Override
        public boolean apply(MetadataSearchResultRecord metadataSearchResultRecord) {
            return filter.apply(metadataSearchResultRecord.getEntityId());
        }
    })), results.getCursors(), results.isShowHidden(), results.getEntityScope());
}
Also used : NamespacedEntityId(co.cask.cdap.proto.id.NamespacedEntityId) EntityId(co.cask.cdap.proto.id.EntityId) MetadataSearchResultRecord(co.cask.cdap.proto.metadata.MetadataSearchResultRecord) MetadataSearchResponse(co.cask.cdap.proto.metadata.MetadataSearchResponse) Principal(co.cask.cdap.proto.security.Principal)

Example 12 with EntityId

use of co.cask.cdap.proto.id.EntityId in project cdap by caskdata.

the class ArtifactRepository method ensureAccess.

/**
   * Ensures that the logged-in user has a {@link Action privilege} on the specified dataset instance.
   *
   * @param artifactId the {@link co.cask.cdap.proto.id.ArtifactId} to check for privileges
   * @throws UnauthorizedException if the logged in user has no {@link Action privileges} on the specified dataset
   */
private void ensureAccess(co.cask.cdap.proto.id.ArtifactId artifactId) throws Exception {
    // No authorization for system artifacts
    if (NamespaceId.SYSTEM.equals(artifactId.getParent())) {
        return;
    }
    Principal principal = authenticationContext.getPrincipal();
    Predicate<EntityId> filter = authorizationEnforcer.createFilter(principal);
    if (!filter.apply(artifactId)) {
        throw new UnauthorizedException(principal, artifactId);
    }
}
Also used : EntityId(co.cask.cdap.proto.id.EntityId) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) Principal(co.cask.cdap.proto.security.Principal)

Example 13 with EntityId

use of co.cask.cdap.proto.id.EntityId in project cdap by caskdata.

the class AuthorizationBootstrapperTest method test.

@Test
public void test() throws Exception {
    final Principal systemUser = new Principal(UserGroupInformation.getCurrentUser().getShortUserName(), Principal.PrincipalType.USER);
    // initial state: no privileges for system or admin users
    Predicate<EntityId> systemUserFilter = authorizationEnforcer.createFilter(systemUser);
    Predicate<EntityId> adminUserFilter = authorizationEnforcer.createFilter(ADMIN_USER);
    Assert.assertFalse(systemUserFilter.apply(instanceId));
    Assert.assertFalse(systemUserFilter.apply(NamespaceId.SYSTEM));
    Assert.assertFalse(adminUserFilter.apply(NamespaceId.DEFAULT));
    // privileges should be granted after running bootstrap
    authorizationBootstrapper.run();
    Tasks.waitFor(true, new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            Predicate<EntityId> systemUserFilter = authorizationEnforcer.createFilter(systemUser);
            Predicate<EntityId> adminUserFilter = authorizationEnforcer.createFilter(ADMIN_USER);
            return systemUserFilter.apply(instanceId) && systemUserFilter.apply(NamespaceId.SYSTEM) && adminUserFilter.apply(NamespaceId.DEFAULT);
        }
    }, 10, TimeUnit.SECONDS);
    txManager.startAndWait();
    datasetService.startAndWait();
    waitForService(Constants.Service.DATASET_MANAGER);
    defaultNamespaceEnsurer.startAndWait();
    systemArtifactLoader.startAndWait();
    waitForService(defaultNamespaceEnsurer);
    waitForService(systemArtifactLoader);
    // ensure that the default namespace was created, and that the system user has privileges to access it
    Tasks.waitFor(true, new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            try {
                return namespaceQueryAdmin.exists(NamespaceId.DEFAULT);
            } catch (Exception e) {
                return false;
            }
        }
    }, 10, TimeUnit.SECONDS);
    Assert.assertTrue(defaultNamespaceEnsurer.isRunning());
    // ensure that the system artifact was deployed, and that the system user has privileges to access it
    // this will throw an ArtifactNotFoundException if the artifact was not deployed, and UnauthorizedException if
    // the user does not have required privileges
    Tasks.waitFor(true, new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            try {
                artifactRepository.getArtifact(SYSTEM_ARTIFACT.toId());
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }, 20, TimeUnit.SECONDS);
    Assert.assertTrue(systemArtifactLoader.isRunning());
    // ensure that system datasets can be created by the system user
    Dataset systemDataset = DatasetsUtil.getOrCreateDataset(dsFramework, NamespaceId.SYSTEM.dataset("system-dataset"), Table.class.getName(), DatasetProperties.EMPTY, Collections.<String, String>emptyMap());
    Assert.assertNotNull(systemDataset);
    // as part of bootstrapping, admin users were also granted admin privileges on the CDAP instance, so they can
    // create namespaces
    SecurityRequestContext.setUserId(ADMIN_USER.getName());
    namespaceAdmin.create(new NamespaceMeta.Builder().setName("success").build());
    SecurityRequestContext.setUserId("bob");
    try {
        namespaceAdmin.create(new NamespaceMeta.Builder().setName("failure").build());
        Assert.fail("Bob should not have been able to create a namespace since he is not an admin user");
    } catch (UnauthorizedException expected) {
    // expected
    }
}
Also used : Table(co.cask.cdap.api.dataset.table.Table) Dataset(co.cask.cdap.api.dataset.Dataset) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) IOException(java.io.IOException) Predicate(co.cask.cdap.api.Predicate) EntityId(co.cask.cdap.proto.id.EntityId) NamespaceMeta(co.cask.cdap.proto.NamespaceMeta) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) Principal(co.cask.cdap.proto.security.Principal) Test(org.junit.Test)

Example 14 with EntityId

use of co.cask.cdap.proto.id.EntityId in project cdap by caskdata.

the class FileStreamAdmin method ensureAccess.

private <T extends EntityId> void ensureAccess(T entityId) throws Exception {
    Principal principal = authenticationContext.getPrincipal();
    Predicate<EntityId> filter = authorizationEnforcer.createFilter(principal);
    if (!filter.apply(entityId)) {
        throw new UnauthorizedException(principal, entityId);
    }
}
Also used : EntityId(co.cask.cdap.proto.id.EntityId) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) Principal(co.cask.cdap.proto.security.Principal)

Example 15 with EntityId

use of co.cask.cdap.proto.id.EntityId in project cdap by caskdata.

the class AuthorizationTest method testPrograms.

@Test
public void testPrograms() throws Exception {
    createAuthNamespace();
    grantAndAssertSuccess(AUTH_NAMESPACE.app(DummyApp.class.getSimpleName()), ALICE, EnumSet.of(Action.ADMIN));
    ApplicationId dummyAppId = AUTH_NAMESPACE.app(DummyApp.class.getSimpleName());
    final ProgramId serviceId = dummyAppId.service(DummyApp.Greeting.SERVICE_NAME);
    Map<EntityId, Set<Action>> neededPrivileges = ImmutableMap.<EntityId, Set<Action>>builder().put(dummyAppId, EnumSet.of(Action.ADMIN)).put(AUTH_NAMESPACE.artifact(DummyApp.class.getSimpleName(), "1.0-SNAPSHOT"), EnumSet.of(Action.ADMIN)).put(AUTH_NAMESPACE.dataset("whom"), EnumSet.of(Action.ADMIN)).put(AUTH_NAMESPACE.stream("who"), EnumSet.of(Action.ADMIN)).put(AUTH_NAMESPACE.datasetType(KeyValueTable.class.getName()), EnumSet.of(Action.ADMIN)).put(serviceId, EnumSet.of(Action.EXECUTE, Action.ADMIN)).put(AUTH_NAMESPACE.dataset("customDataset"), EnumSet.of(Action.ADMIN)).put(AUTH_NAMESPACE.datasetType(DummyApp.CustomDummyDataset.class.getName()), EnumSet.of(Action.ADMIN)).put(AUTH_NAMESPACE.datasetModule(DummyApp.CustomDummyDataset.class.getName()), EnumSet.of(Action.ADMIN)).build();
    setUpPrivilegeAndRegisterForDeletion(ALICE, neededPrivileges);
    final ApplicationManager dummyAppManager = deployApplication(AUTH_NAMESPACE, DummyApp.class);
    // alice should be able to start and stop programs in the app she deployed since she has execute privilege
    dummyAppManager.startProgram(Id.Service.fromEntityId(serviceId));
    ServiceManager greetingService = dummyAppManager.getServiceManager(serviceId.getProgram());
    greetingService.waitForRun(ProgramRunStatus.RUNNING, 10, TimeUnit.SECONDS);
    // alice should be able to set instances for the program
    greetingService.setInstances(2);
    Assert.assertEquals(2, greetingService.getProvisionedInstances());
    // alice should also be able to save runtime arguments for all future runs of the program
    Map<String, String> args = ImmutableMap.of("key", "value");
    greetingService.setRuntimeArgs(args);
    // Alice should be able to get runtime arguments as she has ADMIN on it
    Assert.assertEquals(args, greetingService.getRuntimeArgs());
    dummyAppManager.stopProgram(Id.Service.fromEntityId(serviceId));
    greetingService.waitForRun(ProgramRunStatus.KILLED, 10, TimeUnit.SECONDS);
    // Bob should not be able to start programs in dummy app because he does not have privileges on it
    SecurityRequestContext.setUserId(BOB.getName());
    try {
        dummyAppManager.startProgram(Id.Service.fromEntityId(serviceId));
        Assert.fail("Bob should not be able to start the service because he does not have execute privileges on it.");
    } catch (RuntimeException expected) {
        // noinspection ThrowableResultOfMethodCallIgnored
        Assert.assertTrue(Throwables.getRootCause(expected) instanceof UnauthorizedException);
    }
    try {
        dummyAppManager.getInfo();
        Assert.fail("Bob should not be able to read the app info with out privileges");
    } catch (Exception expected) {
    // expected
    }
    // setting instances should fail because Bob does not have admin privileges on the program
    try {
        greetingService.setInstances(3);
        Assert.fail("Setting instances should have failed because bob does not have admin privileges on the service.");
    } catch (RuntimeException expected) {
        // noinspection ThrowableResultOfMethodCallIgnored
        Assert.assertTrue(Throwables.getRootCause(expected) instanceof UnauthorizedException);
    }
    try {
        greetingService.setRuntimeArgs(args);
        Assert.fail("Setting runtime arguments should have failed because bob does not have admin privileges on the " + "service");
    } catch (UnauthorizedException expected) {
    // expected
    }
    try {
        greetingService.getRuntimeArgs();
        Assert.fail("Getting runtime arguments should have failed because bob does not have one of READ, WRITE, ADMIN " + "privileges on the service");
    } catch (UnauthorizedException expected) {
    // expected
    }
    SecurityRequestContext.setUserId(ALICE.getName());
    dummyAppManager.delete();
}
Also used : ApplicationManager(co.cask.cdap.test.ApplicationManager) EnumSet(java.util.EnumSet) Set(java.util.Set) ImmutableSet(com.google.common.collect.ImmutableSet) HashSet(java.util.HashSet) PartitionedFileSet(co.cask.cdap.api.dataset.lib.PartitionedFileSet) ProgramId(co.cask.cdap.proto.id.ProgramId) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) EntityId(co.cask.cdap.proto.id.EntityId) KeyValueTable(co.cask.cdap.api.dataset.lib.KeyValueTable) ServiceManager(co.cask.cdap.test.ServiceManager) DummyApp(co.cask.cdap.test.app.DummyApp) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) ApplicationId(co.cask.cdap.proto.id.ApplicationId) Test(org.junit.Test)

Aggregations

EntityId (co.cask.cdap.proto.id.EntityId)62 Principal (co.cask.cdap.proto.security.Principal)21 EnumSet (java.util.EnumSet)18 HashSet (java.util.HashSet)18 Set (java.util.Set)18 PartitionedFileSet (co.cask.cdap.api.dataset.lib.PartitionedFileSet)17 ImmutableSet (com.google.common.collect.ImmutableSet)17 Test (org.junit.Test)17 Action (co.cask.cdap.proto.security.Action)14 UnauthorizedException (co.cask.cdap.security.spi.authorization.UnauthorizedException)13 DatasetId (co.cask.cdap.proto.id.DatasetId)12 ProgramId (co.cask.cdap.proto.id.ProgramId)11 ApplicationManager (co.cask.cdap.test.ApplicationManager)11 ApplicationId (co.cask.cdap.proto.id.ApplicationId)10 StreamId (co.cask.cdap.proto.id.StreamId)9 NamespaceId (co.cask.cdap.proto.id.NamespaceId)8 PrivilegedAction (java.security.PrivilegedAction)8 KeyValueTable (co.cask.cdap.api.dataset.lib.KeyValueTable)7 NamespaceMeta (co.cask.cdap.proto.NamespaceMeta)7 Authorizer (co.cask.cdap.security.spi.authorization.Authorizer)7