Search in sources :

Example 81 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class ModificationBean method submit.

/**
 * Execute a Modification service with the given name and runtime parameters
 *
 * @param modificationServiceName
 *            Name of the modification service configuration
 * @param request
 *            object type specified in listConfigurations response.
 * @return datawave.webservice.result.VoidResponse
 * @RequestHeader X-ProxiedEntitiesChain use when proxying request for user
 * @RequestHeader X-ProxiedIssuersChain required when using X-ProxiedEntitiesChain, specify one issuer DN per subject DN listed in X-ProxiedEntitiesChain
 * @ResponseHeader X-OperationTimeInMS time spent on the server performing the operation, does not account for network or result serialization
 * @HTTP 200 success
 * @HTTP 400 if jobName is invalid
 * @HTTP 401 if user does not have correct roles
 * @HTTP 500 error starting the job
 */
@PUT
@Consumes({ "application/xml", "text/xml", "application/json" })
@Produces({ "application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf", "application/x-protostuff" })
@Path("/{serviceName}/submit")
@GZIP
@Interceptors({ RequiredInterceptor.class, ResponseInterceptor.class })
public VoidResponse submit(@Required("modificationServiceName") @PathParam("serviceName") String modificationServiceName, @Required("request") ModificationRequestBase request) {
    VoidResponse response = new VoidResponse();
    // Find out who/what called this method
    Principal p = ctx.getCallerPrincipal();
    String user;
    Set<Authorizations> cbAuths = new HashSet<>();
    Collection<String> userRoles = Collections.emptySet();
    if (p instanceof DatawavePrincipal) {
        DatawavePrincipal dp = (DatawavePrincipal) p;
        user = dp.getShortName();
        userRoles = dp.getPrimaryUser().getRoles();
        for (Collection<String> c : dp.getAuthorizations()) cbAuths.add(new Authorizations(c.toArray(new String[c.size()])));
    } else {
        QueryException qe = new QueryException(DatawaveErrorCode.UNEXPECTED_PRINCIPAL_ERROR, MessageFormat.format("Class: {0}", p.getClass().getName()));
        response.addException(qe);
        throw new DatawaveWebApplicationException(qe, response);
    }
    Connector con = null;
    AccumuloConnectionFactory.Priority priority;
    try {
        // Get the Modification Service from the configuration
        ModificationServiceConfiguration service = modificationConfiguration.getConfiguration(modificationServiceName);
        if (!request.getClass().equals(service.getRequestClass())) {
            BadRequestQueryException qe = new BadRequestQueryException(DatawaveErrorCode.INVALID_REQUEST_CLASS, MessageFormat.format("Requires: {0}", service.getRequestClass().getName()));
            response.addException(qe);
            throw new BadRequestException(qe, response);
        }
        priority = service.getPriority();
        // Ensure that the user is in the list of authorized roles
        if (null != service.getAuthorizedRoles()) {
            boolean authorized = !Collections.disjoint(userRoles, service.getAuthorizedRoles());
            if (!authorized) {
                // Then the user does not have any of the authorized roles
                UnauthorizedQueryException qe = new UnauthorizedQueryException(DatawaveErrorCode.JOB_EXECUTION_UNAUTHORIZED, MessageFormat.format("Requires one of: {0}", service.getAuthorizedRoles()));
                response.addException(qe);
                throw new UnauthorizedException(qe, response);
            }
        }
        if (service.getRequiresAudit()) {
            try {
                MultivaluedMap<String, String> requestMap = new MultivaluedMapImpl<>();
                requestMap.putAll(request.toMap());
                auditParameterBuilder.convertAndValidate(requestMap);
            } catch (Exception e) {
                QueryException qe = new QueryException(DatawaveErrorCode.QUERY_AUDITING_ERROR, e);
                log.error(qe);
                response.addException(qe.getBottomQueryException());
            }
        }
        // Process the modification
        Map<String, String> trackingMap = connectionFactory.getTrackingMap(Thread.currentThread().getStackTrace());
        con = connectionFactory.getConnection(modificationConfiguration.getPoolName(), priority, trackingMap);
        service.setQueryService(queryService);
        log.info("Processing modification request from user=" + user + ": \n" + request);
        service.process(con, request, cache.getCachedMutableFieldList(), cbAuths, user);
        return response;
    } catch (DatawaveWebApplicationException e) {
        throw e;
    } catch (Exception e) {
        QueryException qe = new QueryException(DatawaveErrorCode.MODIFICATION_ERROR, e);
        log.error(qe);
        response.addException(qe.getBottomQueryException());
        throw new DatawaveWebApplicationException(e, response);
    } finally {
        if (null != con)
            try {
                connectionFactory.returnConnection(con);
            } catch (Exception e) {
                log.error("Error returning connection", e);
            }
    }
}
Also used : Connector(org.apache.accumulo.core.client.Connector) Authorizations(org.apache.accumulo.core.security.Authorizations) BadRequestQueryException(datawave.webservice.query.exception.BadRequestQueryException) MultivaluedMapImpl(org.jboss.resteasy.specimpl.MultivaluedMapImpl) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) BadRequestException(datawave.webservice.common.exception.BadRequestException) DatawaveWebApplicationException(datawave.webservice.common.exception.DatawaveWebApplicationException) UnauthorizedQueryException(datawave.webservice.query.exception.UnauthorizedQueryException) UnauthorizedException(datawave.webservice.common.exception.UnauthorizedException) BadRequestQueryException(datawave.webservice.query.exception.BadRequestQueryException) QueryException(datawave.webservice.query.exception.QueryException) AccumuloConnectionFactory(datawave.webservice.common.connection.AccumuloConnectionFactory) UnauthorizedQueryException(datawave.webservice.query.exception.UnauthorizedQueryException) UnauthorizedQueryException(datawave.webservice.query.exception.UnauthorizedQueryException) BadRequestQueryException(datawave.webservice.query.exception.BadRequestQueryException) QueryException(datawave.webservice.query.exception.QueryException) VoidResponse(datawave.webservice.result.VoidResponse) UnauthorizedException(datawave.webservice.common.exception.UnauthorizedException) DatawaveWebApplicationException(datawave.webservice.common.exception.DatawaveWebApplicationException) BadRequestException(datawave.webservice.common.exception.BadRequestException) Principal(java.security.Principal) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) HashSet(java.util.HashSet) ModificationServiceConfiguration(datawave.webservice.modification.configuration.ModificationServiceConfiguration) Path(javax.ws.rs.Path) Interceptors(javax.interceptor.Interceptors) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GZIP(org.jboss.resteasy.annotations.GZIP) PUT(javax.ws.rs.PUT)

Example 82 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class DashboardBean method getQuerySummary.

@GET
@Path("/stats")
@Interceptors(ResponseInterceptor.class)
public ExtJsResponse<DashboardSummary> getQuerySummary(@QueryParam("start") long startMs, @QueryParam("end") long endMs) throws Exception {
    Instant now = Instant.now();
    Instant start = Instant.ofEpochMilli(startMs);
    Instant end = Instant.ofEpochMilli(endMs);
    String auths;
    DatawavePrincipal principal = getPrincipal();
    if (principal == null) {
        auths = "ALL";
    } else {
        auths = AuthorizationsUtil.buildAuthorizationString(principal.getAuthorizations());
    }
    ExtJsResponse<DashboardSummary> summary = null;
    try {
        summary = DashboardQuery.createQuery(queryExecutor, auths, Date.from(start), Date.from(end), Date.from(now));
    } catch (RuntimeException ex) {
        log.error("An error occurred querying for dashboard metrics: " + ex.getMessage(), ex);
        throw ex;
    } finally {
        if (summary != null) {
            queryExecutor.close(summary.getQueryId());
        }
    }
    return summary;
}
Also used : Instant(java.time.Instant) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) Path(javax.ws.rs.Path) Interceptors(javax.interceptor.Interceptors) GET(javax.ws.rs.GET)

Example 83 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class DashboardBean method getPrincipal.

private DatawavePrincipal getPrincipal() {
    Principal p = ctx.getCallerPrincipal();
    if (p instanceof DatawavePrincipal) {
        return (DatawavePrincipal) p;
    }
    log.warn("Principal is not of the correct type");
    return null;
}
Also used : DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) Principal(java.security.Principal) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal)

Example 84 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class DashboardBean method getAuths.

private Set<Authorizations> getAuths() {
    DatawavePrincipal dp = getPrincipal();
    Set<Authorizations> auths = new HashSet<>();
    for (Collection<String> cbAuths : dp.getAuthorizations()) {
        auths.add(new Authorizations(cbAuths.toArray(new String[cbAuths.size()])));
    }
    return auths;
}
Also used : Authorizations(org.apache.accumulo.core.security.Authorizations) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) HashSet(java.util.HashSet)

Example 85 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class Persister method findByName.

/**
 * Finds Query objects by the query name
 *
 * @param name
 * @return null if no results or list of query objects
 */
public List<Query> findByName(String name) {
    // Find out who/what called this method
    Principal p = ctx.getCallerPrincipal();
    String shortName = p.getName();
    Set<Authorizations> auths = new HashSet<>();
    if (p instanceof DatawavePrincipal) {
        DatawavePrincipal dp = (DatawavePrincipal) p;
        shortName = dp.getShortName();
        for (Collection<String> authCollection : dp.getAuthorizations()) auths.add(new Authorizations(authCollection.toArray(new String[authCollection.size()])));
    }
    log.trace(shortName + " has authorizations " + auths);
    Connector c = null;
    try {
        Map<String, String> trackingMap = connectionFactory.getTrackingMap(Thread.currentThread().getStackTrace());
        c = connectionFactory.getConnection(Priority.ADMIN, trackingMap);
        tableCheck(c);
        try (Scanner scanner = ScannerHelper.createScanner(c, TABLE_NAME, auths)) {
            Range range = new Range(shortName, shortName);
            scanner.setRange(range);
            scanner.fetchColumnFamily(new Text(name));
            List<Query> results = null;
            for (Entry<Key, Value> entry : scanner) {
                if (null == results)
                    results = new ArrayList<>();
                results.add(QueryUtil.deserialize(QueryUtil.getQueryImplClassName(entry.getKey()), entry.getKey().getColumnVisibility(), entry.getValue()));
            }
            return results;
        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        log.error("Error creating query", e);
        throw new EJBException("Error creating query", e);
    } finally {
        try {
            connectionFactory.returnConnection(c);
        } catch (Exception e) {
            log.error("Error creating query", e);
            c = null;
        }
    }
}
Also used : Connector(org.apache.accumulo.core.client.Connector) Scanner(org.apache.accumulo.core.client.Scanner) Authorizations(org.apache.accumulo.core.security.Authorizations) Query(datawave.webservice.query.Query) ArrayList(java.util.ArrayList) Text(org.apache.hadoop.io.Text) Range(org.apache.accumulo.core.data.Range) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) TableNotFoundException(org.apache.accumulo.core.client.TableNotFoundException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) EJBException(javax.ejb.EJBException) TableExistsException(org.apache.accumulo.core.client.TableExistsException) AccumuloSecurityException(org.apache.accumulo.core.client.AccumuloSecurityException) AccumuloException(org.apache.accumulo.core.client.AccumuloException) Value(org.apache.accumulo.core.data.Value) EJBException(javax.ejb.EJBException) Principal(java.security.Principal) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) Key(org.apache.accumulo.core.data.Key) HashSet(java.util.HashSet)

Aggregations

DatawavePrincipal (datawave.security.authorization.DatawavePrincipal)93 DatawaveUser (datawave.security.authorization.DatawaveUser)41 Principal (java.security.Principal)37 HashSet (java.util.HashSet)33 Test (org.junit.Test)29 QueryException (datawave.webservice.query.exception.QueryException)24 Connector (org.apache.accumulo.core.client.Connector)23 IOException (java.io.IOException)19 DatawaveWebApplicationException (datawave.webservice.common.exception.DatawaveWebApplicationException)18 NotFoundQueryException (datawave.webservice.query.exception.NotFoundQueryException)18 Authorizations (org.apache.accumulo.core.security.Authorizations)17 Query (datawave.webservice.query.Query)16 UnauthorizedQueryException (datawave.webservice.query.exception.UnauthorizedQueryException)15 NoResultsException (datawave.webservice.common.exception.NoResultsException)13 ArrayList (java.util.ArrayList)13 Path (javax.ws.rs.Path)13 Produces (javax.ws.rs.Produces)13 SubjectIssuerDNPair (datawave.security.authorization.SubjectIssuerDNPair)12 WebApplicationException (javax.ws.rs.WebApplicationException)12 BadRequestException (datawave.webservice.common.exception.BadRequestException)11