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;
}
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);
}
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));
}
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);
}
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));
}
Aggregations