Search in sources :

Example 6 with ApiKey

use of io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey in project hopsworks by logicalclocks.

the class ApiKeyFacade method findByUser.

public CollectionInfo findByUser(Integer offset, Integer limit, Set<? extends FilterBy> filter, Set<? extends SortBy> sort, Users user) {
    String queryStr = buildQuery("SELECT a FROM ApiKey a ", filter, sort, "a.user = :user AND a.reserved = 0");
    String queryCountStr = buildQuery("SELECT COUNT(a.id) FROM ApiKey a ", filter, sort, "a.user = :user " + "AND a.reserved = 0");
    Query query = em.createQuery(queryStr, ApiKey.class).setParameter("user", user);
    Query queryCount = em.createQuery(queryCountStr, ApiKey.class).setParameter("user", user);
    return findAll(offset, limit, filter, query, queryCount);
}
Also used : ApiKey(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey) Query(javax.persistence.Query) TypedQuery(javax.persistence.TypedQuery)

Example 7 with ApiKey

use of io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey in project hopsworks by logicalclocks.

the class ApiKeyFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
    JsonResponse jsonResponse = new RESTApiJsonResponse();
    if (authorizationHeader == null) {
        LOGGER.log(Level.FINEST, "Authorization header not set.");
        jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getCode());
        jsonResponse.setErrorMsg("Authorization header not set.");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(jsonResponse).build());
        return;
    }
    if (authorizationHeader.startsWith(BEARER)) {
        LOGGER.log(Level.FINEST, "{0} token found, leaving Api key interceptor", BEARER);
        if (getJWTAnnotation() == null) {
            jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getCode());
            jsonResponse.setErrorMsg("Authorization method not supported.");
            requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(jsonResponse).build());
        }
        return;
    }
    if (!authorizationHeader.startsWith(API_KEY)) {
        LOGGER.log(Level.FINEST, "Invalid Api key. AuthorizationHeader : {0}", authorizationHeader);
        jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getCode());
        jsonResponse.setErrorMsg("Invalidated Api key.");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(jsonResponse).build());
        return;
    }
    String key = authorizationHeader.substring(API_KEY.length()).trim();
    try {
        ApiKey apiKey = apiKeyController.getApiKey(key);
        Users user = apiKey.getUser();
        List<String> roles = usersController.getUserRoles(user);
        Set<ApiScope> scopes = apiKeyController.getScopes(apiKey);
        checkRole(roles);
        checkScope(scopes);
        Subject subject = new Subject(user.getUsername(), roles);
        String scheme = requestContext.getUriInfo().getRequestUri().getScheme();
        requestContext.setSecurityContext(new HopsworksSecurityContext(subject, scheme));
    } catch (ApiKeyException e) {
        LOGGER.log(Level.FINEST, "Api key Verification Exception: {0}", e.getMessage());
        e.buildJsonResponse(jsonResponse, settings.getHopsworksRESTLogLevel());
        requestContext.abortWith(Response.status(e.getErrorCode().getRespStatus().getStatusCode()).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(jsonResponse).build());
    }
}
Also used : ApiKeyException(io.hops.hopsworks.exceptions.ApiKeyException) ApiKey(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey) RESTApiJsonResponse(io.hops.hopsworks.api.util.RESTApiJsonResponse) ApiScope(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiScope) Users(io.hops.hopsworks.persistence.entity.user.Users) RESTApiJsonResponse(io.hops.hopsworks.api.util.RESTApiJsonResponse) JsonResponse(io.hops.hopsworks.restutils.JsonResponse) Subject(io.hops.hopsworks.api.filter.util.Subject) HopsworksSecurityContext(io.hops.hopsworks.api.filter.util.HopsworksSecurityContext)

Example 8 with ApiKey

use of io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey in project hopsworks by logicalclocks.

the class ApiKeyResource method update.

@PUT
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update an api key.", response = ApiKeyDTO.class)
@JWTRequired(acceptedTokens = { Audience.API }, allowedUserRoles = { "HOPS_ADMIN", "HOPS_USER" })
public Response update(@QueryParam("name") String name, @QueryParam("action") ApiKeyUpdateAction action, @QueryParam("scope") Set<ApiScope> scopes, @Context UriInfo uriInfo, @Context HttpServletRequest req, @Context SecurityContext sc) throws ApiKeyException {
    Users user = jwtHelper.getUserPrincipal(sc);
    Set<ApiScope> validatedScopes = validateScopes(user, scopes);
    ApiKey apikey;
    switch(action == null ? ApiKeyUpdateAction.ADD : action) {
        case ADD:
            apikey = apikeyController.addScope(user, name, validatedScopes);
            break;
        case DELETE:
            apikey = apikeyController.removeScope(user, name, validatedScopes);
            break;
        case UPDATE:
            apikey = apikeyController.update(user, name, validatedScopes);
            break;
        default:
            throw new WebApplicationException("Action need to set a valid action, but found: " + action, Response.Status.NOT_FOUND);
    }
    ResourceRequest resourceRequest = new ResourceRequest(ResourceRequest.Name.APIKEY);
    ApiKeyDTO dto = apikeyBuilder.build(uriInfo, resourceRequest, apikey);
    return Response.ok().entity(dto).build();
}
Also used : ApiKey(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey) WebApplicationException(javax.ws.rs.WebApplicationException) ApiScope(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiScope) Users(io.hops.hopsworks.persistence.entity.user.Users) ResourceRequest(io.hops.hopsworks.common.api.ResourceRequest) Produces(javax.ws.rs.Produces) JWTRequired(io.hops.hopsworks.jwt.annotation.JWTRequired) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT)

Example 9 with ApiKey

use of io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey in project hopsworks by logicalclocks.

the class ApiKeyResource method getByKey.

@GET
@Path("key")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Find api key by name.", response = ApiKeyDTO.class)
@JWTRequired(acceptedTokens = { Audience.API }, allowedUserRoles = { "HOPS_ADMIN", "HOPS_USER" })
public Response getByKey(@QueryParam("key") String key, @Context UriInfo uriInfo, @Context SecurityContext sc) throws ApiKeyException {
    ResourceRequest resourceRequest = new ResourceRequest(ResourceRequest.Name.APIKEY);
    ApiKey apikey = apikeyController.getApiKey(key);
    ApiKeyDTO dto = apikeyBuilder.build(uriInfo, resourceRequest, apikey);
    return Response.ok().entity(dto).build();
}
Also used : ApiKey(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey) ResourceRequest(io.hops.hopsworks.common.api.ResourceRequest) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) JWTRequired(io.hops.hopsworks.jwt.annotation.JWTRequired) ApiOperation(io.swagger.annotations.ApiOperation)

Example 10 with ApiKey

use of io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey in project hopsworks by logicalclocks.

the class ApiKeyController method createNewKey.

/**
 * Create new key for the give user with the given key name and scopes.
 * @param user
 * @param keyName
 * @param scopes
 * @throws UserException
 * @throws ApiKeyException
 * @return
 */
public String createNewKey(Users user, String keyName, Set<ApiScope> scopes, Boolean reserved) throws UserException, ApiKeyException {
    if (user == null) {
        throw new UserException(RESTCodes.UserErrorCode.USER_WAS_NOT_FOUND, Level.FINE);
    }
    if (keyName == null || keyName.isEmpty()) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_NAME_NOT_SPECIFIED, Level.FINE);
    }
    if (keyName.length() > 45) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_NAME_NOT_VALID, Level.FINE);
    }
    if (scopes == null || scopes.isEmpty()) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_SCOPE_NOT_SPECIFIED, Level.FINE);
    }
    ApiKey apiKey = apiKeyFacade.findByUserAndName(user, keyName);
    if (apiKey != null) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_NAME_EXIST, Level.FINE);
    }
    Secret secret = generateApiKey();
    Date date = new Date();
    apiKey = new ApiKey(user, secret.getPrefix(), secret.getSha256HexDigest(), secret.getSalt(), date, date, keyName, reserved);
    List<ApiKeyScope> keyScopes = getKeyScopes(scopes, apiKey);
    apiKey.setApiKeyScopeCollection(keyScopes);
    apiKeyFacade.save(apiKey);
    // run create handlers
    ApiKeyHandler.runApiKeyCreateHandlers(apiKeyHandlers, apiKey);
    sendCreatedEmail(user, keyName, date, scopes);
    return secret.getPrefixPlusSecret();
}
Also used : ApiKeyException(io.hops.hopsworks.exceptions.ApiKeyException) Secret(io.hops.hopsworks.common.security.utils.Secret) ApiKey(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey) ApiKeyScope(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKeyScope) UserException(io.hops.hopsworks.exceptions.UserException) Date(java.util.Date)

Aggregations

ApiKey (io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey)12 ApiKeyException (io.hops.hopsworks.exceptions.ApiKeyException)5 ApiScope (io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiScope)5 ApiKeyScope (io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKeyScope)4 Date (java.util.Date)4 Users (io.hops.hopsworks.persistence.entity.user.Users)3 ResourceRequest (io.hops.hopsworks.common.api.ResourceRequest)2 Secret (io.hops.hopsworks.common.security.utils.Secret)2 JWTRequired (io.hops.hopsworks.jwt.annotation.JWTRequired)2 ApiOperation (io.swagger.annotations.ApiOperation)2 ArrayList (java.util.ArrayList)2 Produces (javax.ws.rs.Produces)2 HopsworksSecurityContext (io.hops.hopsworks.api.filter.util.HopsworksSecurityContext)1 Subject (io.hops.hopsworks.api.filter.util.Subject)1 RESTApiJsonResponse (io.hops.hopsworks.api.util.RESTApiJsonResponse)1 UserException (io.hops.hopsworks.exceptions.UserException)1 HdfsUsers (io.hops.hopsworks.persistence.entity.hdfs.user.HdfsUsers)1 YarnApplicationstate (io.hops.hopsworks.persistence.entity.jobs.history.YarnApplicationstate)1 JsonResponse (io.hops.hopsworks.restutils.JsonResponse)1 IOException (java.io.IOException)1