Search in sources :

Example 1 with JsonResponse

use of io.hops.hopsworks.restutils.JsonResponse in project hopsworks by logicalclocks.

the class ProjectAuthFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    MultivaluedMap<String, String> pathParameters = requestContext.getUriInfo().getPathParameters();
    String projectId = pathParameters.getFirst("projectId");
    String projectName = pathParameters.getFirst("projectName");
    String path = requestContext.getUriInfo().getPath();
    Class<?> resourceClass = resourceInfo.getResourceClass();
    Method method = resourceInfo.getResourceMethod();
    if (projectId == null && projectName == null) {
        LOGGER.log(Level.WARNING, "Annotated with AllowedProjectRoles but no project identifier " + "(projectId or projectName) found in the requesed path: {0}", path);
        return;
    }
    JsonResponse jsonResponse = new RESTApiJsonResponse();
    Integer id = null;
    String userRole;
    try {
        id = Integer.valueOf(projectId);
    } catch (NumberFormatException ne) {
    // 
    }
    Project project = id != null ? projectBean.find(id) : projectBean.findByName(projectName);
    if (project == null) {
        jsonResponse.setErrorCode(RESTCodes.ProjectErrorCode.PROJECT_NOT_FOUND.getCode());
        jsonResponse.setErrorMsg(RESTCodes.ProjectErrorCode.PROJECT_NOT_FOUND.getMessage());
        requestContext.abortWith(Response.status(Response.Status.NOT_FOUND).entity(jsonResponse).build());
        return;
    }
    LOGGER.log(Level.FINEST, "Filtering project request path: {0}", project.getName());
    AllowedProjectRoles methodProjectRolesAnnotation = method.getAnnotation(AllowedProjectRoles.class);
    AllowedProjectRoles classProjectRolesAnnotation = resourceClass.getAnnotation(AllowedProjectRoles.class);
    AllowedProjectRoles rolesAnnotation = methodProjectRolesAnnotation != null ? methodProjectRolesAnnotation : classProjectRolesAnnotation;
    Set<String> rolesSet;
    rolesSet = new HashSet<>(Arrays.asList(rolesAnnotation.value()));
    if (requestContext.getSecurityContext().getUserPrincipal() == null) {
        LOGGER.log(Level.WARNING, "Authentication not done. No user found.");
        jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getCode());
        jsonResponse.setErrorMsg(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getMessage());
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(jsonResponse).build());
        return;
    }
    String username = requestContext.getSecurityContext().getUserPrincipal().getName();
    Users user = userFacade.findByUsername(username);
    if (user == null) {
        LOGGER.log(Level.WARNING, "User not found.");
        jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getCode());
        jsonResponse.setErrorMsg(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getMessage());
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(jsonResponse).build());
        return;
    }
    userRole = projectTeamBean.findCurrentRole(project, user);
    // If the resource is allowed for all roles check if user is a member of the project.
    if (userRole != null && !userRole.isEmpty() && rolesSet.contains(AllowedProjectRoles.ANYONE)) {
        LOGGER.log(Level.FINEST, "Accessing resource that is allowed for all members.");
        return;
    }
    // if the resource is only allowed for some roles check if the user have the requierd role for the resource.
    if (userRole == null || userRole.isEmpty()) {
        LOGGER.log(Level.INFO, "Trying to access resource, but you dont have any role in this project");
        jsonResponse.setErrorCode(RESTCodes.UserErrorCode.NO_ROLE_FOUND.getCode());
        jsonResponse.setErrorMsg(RESTCodes.UserErrorCode.NO_ROLE_FOUND.getMessage());
        requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(jsonResponse).build());
    } else if (!rolesSet.contains(userRole)) {
        LOGGER.log(Level.INFO, "Trying to access resource that is only allowed for: {0}, But you are a: {1}", new Object[] { rolesSet, userRole });
        jsonResponse.setErrorCode(RESTCodes.ProjectErrorCode.PROJECT_ROLE_FORBIDDEN.getCode());
        jsonResponse.setErrorMsg(RESTCodes.ProjectErrorCode.PROJECT_ROLE_FORBIDDEN.getMessage());
        requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(jsonResponse).build());
    }
}
Also used : Method(java.lang.reflect.Method) Users(io.hops.hopsworks.persistence.entity.user.Users) JsonResponse(io.hops.hopsworks.restutils.JsonResponse) RESTApiJsonResponse(io.hops.hopsworks.api.util.RESTApiJsonResponse) Project(io.hops.hopsworks.persistence.entity.project.Project) RESTApiJsonResponse(io.hops.hopsworks.api.util.RESTApiJsonResponse)

Example 2 with JsonResponse

use of io.hops.hopsworks.restutils.JsonResponse 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 3 with JsonResponse

use of io.hops.hopsworks.restutils.JsonResponse in project hopsworks by logicalclocks.

the class AuthFilter method responseEntity.

@Override
public Object responseEntity(Response.Status status, String msg) {
    JsonResponse jsonResponse = new CAJsonResponse();
    if (null == status) {
        jsonResponse.setErrorCode(RESTCodes.GenericErrorCode.UNKNOWN_ERROR.getCode());
    } else {
        switch(status) {
            case UNAUTHORIZED:
                jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getCode());
                break;
            case FORBIDDEN:
                jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.REST_ACCESS_CONTROL.getCode());
                break;
            default:
                jsonResponse.setErrorCode(RESTCodes.GenericErrorCode.UNKNOWN_ERROR.getCode());
                break;
        }
    }
    jsonResponse.setErrorMsg(msg);
    return jsonResponse;
}
Also used : CAJsonResponse(io.hops.hopsworks.ca.api.exception.mapper.CAJsonResponse) CAJsonResponse(io.hops.hopsworks.ca.api.exception.mapper.CAJsonResponse) JsonResponse(io.hops.hopsworks.restutils.JsonResponse)

Example 4 with JsonResponse

use of io.hops.hopsworks.restutils.JsonResponse in project hopsworks by logicalclocks.

the class AuthFilter method responseEntity.

@Override
public Object responseEntity(Response.Status status, String msg) {
    JsonResponse jsonResponse = new RESTApiJsonResponse();
    if (null == status) {
        jsonResponse.setErrorCode(RESTCodes.GenericErrorCode.UNKNOWN_ERROR.getCode());
    } else {
        switch(status) {
            case UNAUTHORIZED:
                jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.EJB_ACCESS_LOCAL.getCode());
                break;
            case FORBIDDEN:
                jsonResponse.setErrorCode(RESTCodes.SecurityErrorCode.REST_ACCESS_CONTROL.getCode());
                break;
            default:
                jsonResponse.setErrorCode(RESTCodes.GenericErrorCode.UNKNOWN_ERROR.getCode());
                break;
        }
    }
    jsonResponse.setErrorMsg(msg);
    return jsonResponse;
}
Also used : RESTApiJsonResponse(io.hops.hopsworks.api.util.RESTApiJsonResponse) RESTApiJsonResponse(io.hops.hopsworks.api.util.RESTApiJsonResponse) JsonResponse(io.hops.hopsworks.restutils.JsonResponse)

Example 5 with JsonResponse

use of io.hops.hopsworks.restutils.JsonResponse in project hopsworks by logicalclocks.

the class ClientWrapper method doGetGenericType.

public List<T> doGetGenericType() {
    performSanityCheck();
    try {
        WebTarget webTarget = client.target(target).path(path);
        Response response = webTarget.request(mediaType).get();
        ParameterizedType parameterizedGenericType = new ParameterizedType() {

            @Override
            public Type[] getActualTypeArguments() {
                return new Type[] { respContentClass };
            }

            @Override
            public Type getRawType() {
                return List.class;
            }

            @Override
            public Type getOwnerType() {
                return List.class;
            }
        };
        GenericType<List<T>> type = new GenericType<List<T>>(parameterizedGenericType) {
        };
        Family status = response.getStatusInfo().getFamily();
        try {
            if (status == Family.INFORMATIONAL || status == Family.SUCCESSFUL) {
                List<T> content = response.readEntity(type);
                return content;
            } else {
                JsonResponse jsonRes = response.readEntity(JsonResponse.class);
                throw new IllegalStateException(jsonRes.getErrorMsg());
            }
        } catch (ProcessingException e) {
            throw new IllegalStateException(e.getMessage());
        }
    } finally {
        if (client != null) {
            client.close();
            client = null;
        }
    }
}
Also used : GenericType(javax.ws.rs.core.GenericType) JsonResponse(io.hops.hopsworks.restutils.JsonResponse) JsonResponse(io.hops.hopsworks.restutils.JsonResponse) Response(javax.ws.rs.core.Response) ParameterizedType(java.lang.reflect.ParameterizedType) GenericType(javax.ws.rs.core.GenericType) MediaType(javax.ws.rs.core.MediaType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Family(javax.ws.rs.core.Response.Status.Family) List(java.util.List) WebTarget(javax.ws.rs.client.WebTarget) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

JsonResponse (io.hops.hopsworks.restutils.JsonResponse)5 RESTApiJsonResponse (io.hops.hopsworks.api.util.RESTApiJsonResponse)3 Users (io.hops.hopsworks.persistence.entity.user.Users)2 HopsworksSecurityContext (io.hops.hopsworks.api.filter.util.HopsworksSecurityContext)1 Subject (io.hops.hopsworks.api.filter.util.Subject)1 CAJsonResponse (io.hops.hopsworks.ca.api.exception.mapper.CAJsonResponse)1 ApiKeyException (io.hops.hopsworks.exceptions.ApiKeyException)1 Project (io.hops.hopsworks.persistence.entity.project.Project)1 ApiKey (io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey)1 ApiScope (io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiScope)1 Method (java.lang.reflect.Method)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 List (java.util.List)1 ProcessingException (javax.ws.rs.ProcessingException)1 WebTarget (javax.ws.rs.client.WebTarget)1 GenericType (javax.ws.rs.core.GenericType)1 MediaType (javax.ws.rs.core.MediaType)1 Response (javax.ws.rs.core.Response)1 Family (javax.ws.rs.core.Response.Status.Family)1