Search in sources :

Example 1 with Principal

use of io.cdap.cdap.proto.security.Principal in project cdap by caskdata.

the class DefaultPreviewStore method getAllInWaitingState.

@Override
public List<PreviewRequest> getAllInWaitingState() {
    // PreviewStore is a singleton and we have to create gson for each operation since gson is not thread safe.
    Gson gson = new GsonBuilder().registerTypeAdapter(Schema.class, new SchemaTypeAdapter()).create();
    byte[] startRowKey = new MDSKey.Builder().add(WAITING).build().getKey();
    byte[] stopRowKey = new MDSKey(Bytes.stopKeyForPrefix(startRowKey)).getKey();
    List<PreviewRequest> result = new ArrayList<>();
    try (Scanner scanner = previewQueueTable.scan(startRowKey, stopRowKey, null, null, null)) {
        Row indexRow;
        while ((indexRow = scanner.next()) != null) {
            Map<byte[], byte[]> columns = indexRow.getColumns();
            AppRequest request = gson.fromJson(Bytes.toString(columns.get(CONFIG)), AppRequest.class);
            ApplicationId applicationId = gson.fromJson(Bytes.toString(columns.get(APPID)), ApplicationId.class);
            Principal principal = gson.fromJson(Bytes.toString(columns.get(PRINCIPAL)), Principal.class);
            result.add(new PreviewRequest(applicationId, request, principal));
        }
    } catch (IOException e) {
        throw new RuntimeException("Error while listing the waiting preview requests.", e);
    }
    return result;
}
Also used : Scanner(io.cdap.cdap.api.dataset.table.Scanner) GsonBuilder(com.google.gson.GsonBuilder) Schema(io.cdap.cdap.api.data.schema.Schema) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) MDSKey(io.cdap.cdap.data2.dataset2.lib.table.MDSKey) IOException(java.io.IOException) AppRequest(io.cdap.cdap.proto.artifact.AppRequest) SchemaTypeAdapter(io.cdap.cdap.internal.io.SchemaTypeAdapter) Row(io.cdap.cdap.api.dataset.table.Row) PreviewRequest(io.cdap.cdap.app.preview.PreviewRequest) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) Principal(io.cdap.cdap.proto.security.Principal)

Example 2 with Principal

use of io.cdap.cdap.proto.security.Principal in project cdap by caskdata.

the class DefaultNamespaceAdmin method create.

/**
 * Creates a new namespace
 *
 * @param metadata the {@link NamespaceMeta} for the new namespace to be created
 * @throws NamespaceAlreadyExistsException if the specified namespace already exists
 */
@Override
public synchronized void create(final NamespaceMeta metadata) throws Exception {
    // TODO: CDAP-1427 - This should be transactional, but we don't support transactions on files yet
    Preconditions.checkArgument(metadata != null, "Namespace metadata should not be null.");
    NamespaceId namespace = metadata.getNamespaceId();
    if (exists(namespace)) {
        throw new NamespaceAlreadyExistsException(namespace);
    }
    // need to enforce on the principal id if impersonation is involved
    String ownerPrincipal = metadata.getConfig().getPrincipal();
    Principal requestingUser = authenticationContext.getPrincipal();
    if (ownerPrincipal != null) {
        accessEnforcer.enforce(new KerberosPrincipalId(ownerPrincipal), requestingUser, AccessPermission.SET_OWNER);
    }
    accessEnforcer.enforce(namespace, requestingUser, StandardPermission.CREATE);
    // If this namespace has custom mapping then validate the given custom mapping
    if (hasCustomMapping(metadata)) {
        validateCustomMapping(metadata);
    }
    // check that the user has configured either both or none of the following configuration: principal and keytab URI
    boolean hasValidKerberosConf = false;
    if (metadata.getConfig() != null) {
        String configuredPrincipal = metadata.getConfig().getPrincipal();
        String configuredKeytabURI = metadata.getConfig().getKeytabURI();
        if ((!Strings.isNullOrEmpty(configuredPrincipal) && Strings.isNullOrEmpty(configuredKeytabURI)) || (Strings.isNullOrEmpty(configuredPrincipal) && !Strings.isNullOrEmpty(configuredKeytabURI))) {
            throw new BadRequestException(String.format("Either both or none of the following two configurations must be configured. " + "Configured principal: %s, Configured keytabURI: %s", configuredPrincipal, configuredKeytabURI));
        }
        hasValidKerberosConf = true;
    }
    // check that if explore as principal is explicitly set to false then user has kerberos configuration
    if (!metadata.getConfig().isExploreAsPrincipal() && !hasValidKerberosConf) {
        throw new BadRequestException(String.format("No kerberos principal or keytab-uri was provided while '%s' was set to true.", NamespaceConfig.EXPLORE_AS_PRINCIPAL));
    }
    // store the meta first in the namespace store because namespacedLocationFactory needs to look up location
    // mapping from namespace config
    nsStore.create(metadata);
    try {
        UserGroupInformation ugi;
        if (NamespaceId.DEFAULT.equals(namespace)) {
            ugi = UserGroupInformation.getCurrentUser();
        } else {
            ugi = impersonator.getUGI(namespace);
        }
        ImpersonationUtils.doAs(ugi, (Callable<Void>) () -> {
            storageProviderNamespaceAdmin.get().create(metadata);
            return null;
        });
        // if needed, run master environment specific logic
        MasterEnvironment masterEnv = MasterEnvironments.getMasterEnvironment();
        if (masterEnv != null) {
            masterEnv.onNamespaceCreation(namespace.getNamespace(), metadata.getConfig().getConfigs());
        }
    } catch (Throwable t) {
        LOG.error(String.format("Failed to create namespace '%s'", namespace.getNamespace()), t);
        // failed to create namespace in underlying storage so delete the namespace meta stored in the store earlier
        deleteNamespaceMeta(metadata.getNamespaceId());
        throw new NamespaceCannotBeCreatedException(namespace, t);
    }
    emitNamespaceCountMetric();
    LOG.info("Namespace {} created with meta {}", metadata.getNamespaceId(), metadata);
}
Also used : MasterEnvironment(io.cdap.cdap.master.spi.environment.MasterEnvironment) NamespaceCannotBeCreatedException(io.cdap.cdap.common.NamespaceCannotBeCreatedException) BadRequestException(io.cdap.cdap.common.BadRequestException) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) NamespaceAlreadyExistsException(io.cdap.cdap.common.NamespaceAlreadyExistsException) KerberosPrincipalId(io.cdap.cdap.proto.id.KerberosPrincipalId) Principal(io.cdap.cdap.proto.security.Principal) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 3 with Principal

use of io.cdap.cdap.proto.security.Principal in project cdap by caskdata.

the class RemotePrivilegesHandler method listPrivileges.

@POST
@Path("/listPrivileges")
public void listPrivileges(FullHttpRequest request, HttpResponder responder) throws Exception {
    Iterator<MethodArgument> arguments = parseArguments(request);
    Principal principal = deserializeNext(arguments);
    LOG.trace("Listing grantedPermissions for principal {}", principal);
    Set<GrantedPermission> grantedPermissions = permissionManager.listGrants(principal);
    LOG.debug("Returning grantedPermissions for principal {} as {}", principal, grantedPermissions);
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(grantedPermissions));
}
Also used : MethodArgument(io.cdap.cdap.common.internal.remote.MethodArgument) GrantedPermission(io.cdap.cdap.proto.security.GrantedPermission) Principal(io.cdap.cdap.proto.security.Principal) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 4 with Principal

use of io.cdap.cdap.proto.security.Principal in project cdap by caskdata.

the class ListRolesCommand method perform.

@Override
public void perform(Arguments arguments, PrintStream output) throws Exception {
    String principalType = arguments.getOptional(ArgumentName.PRINCIPAL_TYPE.toString());
    String principalName = arguments.getOptional(ArgumentName.PRINCIPAL_NAME.toString());
    Set<Role> roles;
    if (!(Strings.isNullOrEmpty(principalType) && Strings.isNullOrEmpty(principalName))) {
        roles = client.listRoles(new Principal(principalName, Principal.PrincipalType.valueOf(principalType.toUpperCase())));
    } else {
        roles = client.listAllRoles();
    }
    Table table = Table.builder().setHeader("Role").setRows(Lists.newArrayList(roles), new RowMaker<Role>() {

        @Override
        public List<?> makeRow(Role role) {
            return Lists.newArrayList(role.getName());
        }
    }).build();
    cliConfig.getTableRenderer().render(cliConfig, output, table);
}
Also used : Role(io.cdap.cdap.proto.security.Role) Table(io.cdap.cdap.cli.util.table.Table) RowMaker(io.cdap.cdap.cli.util.RowMaker) Principal(io.cdap.cdap.proto.security.Principal)

Example 5 with Principal

use of io.cdap.cdap.proto.security.Principal in project cdap by caskdata.

the class AuthorizationCLITest method testAuthorizationCLI.

@Test
public void testAuthorizationCLI() throws Exception {
    Role role = new Role("admins");
    Principal principal = new Principal("spiderman", Principal.PrincipalType.USER);
    NamespaceId namespaceId = new NamespaceId("ns1");
    CLITestBase.testCommandOutputContains(cli, String.format("create namespace %s", namespaceId.getNamespace()), String.format("Namespace '%s' created successfully", namespaceId.getNamespace()));
    // test creating role
    CLITestBase.testCommandOutputContains(cli, "create role " + role.getName(), String.format("Successfully created role '%s'", role.getName()));
    // test add role to principal
    CLITestBase.testCommandOutputContains(cli, String.format("add role %s to %s %s", role.getName(), principal.getType(), principal.getName()), String.format("Successfully added role '%s' to '%s' '%s'", role.getName(), principal.getType(), principal.getName()));
    // test listing all roles
    String output = CLITestBase.getCommandOutput(cli, "list roles");
    List<String> lines = Arrays.asList(output.split("\\r?\\n"));
    Assert.assertEquals(2, lines.size());
    // 0 is just the table headers
    Assert.assertEquals(role.getName(), lines.get(1));
    // test listing roles for a principal
    output = CLITestBase.getCommandOutput(cli, String.format("list roles for %s %s", principal.getType(), principal.getName()));
    lines = Arrays.asList(output.split("\\r?\\n"));
    Assert.assertEquals(2, lines.size());
    Assert.assertEquals(role.getName(), lines.get(1));
    // test grant permission. also tests case insensitivity of Permission and Principal.PrincipalType
    CLITestBase.testCommandOutputContains(cli, String.format("grant permissions %s on entity %s to %s %s", StandardPermission.GET.name().toLowerCase(), namespaceId.toString(), principal.getType().name().toLowerCase(), principal.getName()), String.format("Successfully granted permission(s) '%s' on entity '%s' to %s '%s'", StandardPermission.GET, namespaceId.toString(), principal.getType(), principal.getName()));
    // test grant permission for application permission (dotted syntax)
    CLITestBase.testCommandOutputContains(cli, String.format("grant permissions %s.%s on entity %s to %s %s", PermissionType.APPLICATION.name().toLowerCase(), ApplicationPermission.EXECUTE.name().toLowerCase(), namespaceId.toString(), principal.getType().name().toLowerCase(), principal.getName()), String.format("Successfully granted permission(s) '%s' on entity '%s' to %s '%s'", ApplicationPermission.EXECUTE, namespaceId.toString(), principal.getType(), principal.getName()));
    // test listing privilege
    output = CLITestBase.getCommandOutput(cli, String.format("list privileges for %s %s", principal.getType(), principal.getName()));
    lines = Stream.of(output.split("\\r?\\n")).sorted().collect(Collectors.toList());
    Assert.assertEquals(3, lines.size());
    Assert.assertArrayEquals(new String[] { namespaceId.toString(), ApplicationPermission.EXECUTE.name() }, lines.get(1).split(","));
    Assert.assertArrayEquals(new String[] { namespaceId.toString(), StandardPermission.GET.name() }, lines.get(2).split(","));
    // test revoke permissions
    CLITestBase.testCommandOutputContains(cli, String.format("revoke permissions %s on entity %s from %s %s", StandardPermission.GET, namespaceId.toString(), principal.getType(), principal.getName()), String.format("Successfully revoked permission(s) '%s' on entity '%s' for %s '%s'", StandardPermission.GET, namespaceId.toString(), principal.getType(), principal.getName()));
    // grant and perform revoke on the entity
    CLITestBase.testCommandOutputContains(cli, String.format("grant permissions %s on entity %s to %s %s", StandardPermission.GET, namespaceId.toString(), principal.getType(), principal.getName()), String.format("Successfully granted permission(s) '%s' on entity '%s' to %s '%s'", StandardPermission.GET, namespaceId.toString(), principal.getType(), principal.getName()));
    CLITestBase.testCommandOutputContains(cli, String.format("revoke all on entity %s ", namespaceId.toString()), String.format("Successfully revoked all permissions on entity '%s' for all principals", namespaceId.toString()));
    // test remove role from principal
    CLITestBase.testCommandOutputContains(cli, String.format("remove role %s from %s %s", role.getName(), principal.getType(), principal.getName()), String.format("Successfully removed role '%s' from %s '%s'", role.getName(), principal.getType(), principal.getName()));
    // test remove role (which doesn't exist) from principal
    Role nonexistentRole = new Role("nonexistent_role");
    CLITestBase.testCommandOutputContains(cli, String.format("remove role %s from %s %s", nonexistentRole.getName(), principal.getType(), principal.getName()), String.format("Error: %s not found", nonexistentRole));
}
Also used : Role(io.cdap.cdap.proto.security.Role) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Principal(io.cdap.cdap.proto.security.Principal) Test(org.junit.Test)

Aggregations

Principal (io.cdap.cdap.proto.security.Principal)86 Test (org.junit.Test)35 Credential (io.cdap.cdap.proto.security.Credential)29 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)28 UserIdentity (io.cdap.cdap.security.auth.UserIdentity)13 EntityId (io.cdap.cdap.proto.id.EntityId)12 IOException (java.io.IOException)11 StandardPermission (io.cdap.cdap.proto.security.StandardPermission)9 Role (io.cdap.cdap.proto.security.Role)8 Path (javax.ws.rs.Path)8 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)7 AccessController (io.cdap.cdap.security.spi.authorization.AccessController)6 NoOpAccessController (io.cdap.cdap.security.spi.authorization.NoOpAccessController)6 ApplicationId (io.cdap.cdap.proto.id.ApplicationId)5 UnauthorizedException (io.cdap.cdap.security.spi.authorization.UnauthorizedException)5 DatasetSpecification (io.cdap.cdap.api.dataset.DatasetSpecification)4 DatasetNotFoundException (io.cdap.cdap.common.DatasetNotFoundException)4 SConfiguration (io.cdap.cdap.common.conf.SConfiguration)4 Injector (com.google.inject.Injector)3 DatasetManagementException (io.cdap.cdap.api.dataset.DatasetManagementException)3