Search in sources :

Example 1 with ApiKeyException

use of io.hops.hopsworks.exceptions.ApiKeyException in project hopsworks by logicalclocks.

the class ApiKeyController method getApiKey.

/**
 * @param key
 * @return
 * @throws ApiKeyException
 */
public ApiKey getApiKey(String key) throws ApiKeyException {
    String[] parts = key.split(Secret.KEY_ID_SEPARATOR_REGEX);
    if (parts.length < 2) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_NOT_FOUND, Level.FINE);
    }
    ApiKey apiKey = apiKeyFacade.findByPrefix(parts[0]);
    if (apiKey == null) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_NOT_FOUND, Level.FINE);
    }
    // ___MinLength can be set to 0 b/c no validation is needed if the key was in db
    Secret secret = new Secret(parts[0], parts[1], apiKey.getSalt());
    if (!secret.getSha256HexDigest().equals(apiKey.getSecret())) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_NOT_FOUND, Level.FINE);
    }
    return apiKey;
}
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)

Example 2 with ApiKeyException

use of io.hops.hopsworks.exceptions.ApiKeyException in project hopsworks by logicalclocks.

the class ApiKeyController method generateApiKey.

private Secret generateApiKey() throws ApiKeyException {
    int retry = RETRY_KEY_CREATION;
    Secret secret = securityUtils.generateSecret();
    while ((apiKeyFacade.findByPrefix(secret.getPrefix()) != null || !secret.validateSize()) && (retry-- > 0)) {
        secret = securityUtils.generateSecret();
    }
    if (retry < 1) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_NOT_CREATED, Level.SEVERE, "Failed to generate unique key prefix after " + RETRY_KEY_CREATION + " retries.");
    }
    return secret;
}
Also used : Secret(io.hops.hopsworks.common.security.utils.Secret) ApiKeyException(io.hops.hopsworks.exceptions.ApiKeyException)

Example 3 with ApiKeyException

use of io.hops.hopsworks.exceptions.ApiKeyException in project hopsworks by logicalclocks.

the class ApiKeyController method removeScope.

/**
 * @param user
 * @param keyName
 * @param scopes
 * @return
 * @throws ApiKeyException
 */
public ApiKey removeScope(Users user, String keyName, Set<ApiScope> scopes) throws ApiKeyException {
    ApiKey apiKey = validate(user, keyName, scopes);
    Collection<ApiKeyScope> oldScopes = apiKey.getApiKeyScopeCollection();
    List<ApiKeyScope> toRemove = new ArrayList<>();
    for (ApiScope scope : scopes) {
        for (ApiKeyScope apiKeyScope : oldScopes) {
            if (apiKeyScope.getScope().equals(scope)) {
                toRemove.add(apiKeyScope);
                break;
            }
        }
    }
    boolean removed = apiKey.getApiKeyScopeCollection().removeAll(toRemove);
    if (removed && !apiKey.getApiKeyScopeCollection().isEmpty()) {
        // this should not be necessary
        for (ApiKeyScope apiKeyScope : toRemove) {
            apiKeyScopeFacade.remove(apiKeyScope);
        }
        apiKey.setModified(new Date());
        apiKey = apiKeyFacade.update(apiKey);
        // run api key update handlers
        ApiKeyHandler.runApiKeyDeleteHandlers(apiKeyHandlers, apiKey, toRemove);
    } else if (removed && apiKey.getApiKeyScopeCollection().isEmpty()) {
        throw new ApiKeyException(RESTCodes.ApiKeyErrorCode.KEY_SCOPE_EMPTY, Level.FINE);
    }
    return apiKey;
}
Also used : ApiKeyException(io.hops.hopsworks.exceptions.ApiKeyException) ApiKey(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey) ApiKeyScope(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKeyScope) ArrayList(java.util.ArrayList) ApiScope(io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiScope) Date(java.util.Date)

Example 4 with ApiKeyException

use of io.hops.hopsworks.exceptions.ApiKeyException in project hopsworks by logicalclocks.

the class InferenceController method infer.

/**
 * Makes an inference request to a running serving instance
 *
 * @param project the project where the serving is running
 * @param modelName the name of the serving
 * @param modelVersion the version of the serving
 * @param verb the predictiont type (predict, regress, or classify)
 * @param inferenceRequestJson the user-provided JSON payload for the inference request
 * @return a string representation of the inference result
 * @throws InferenceException
 */
public String infer(Project project, String username, String modelName, Integer modelVersion, InferenceVerb verb, String inferenceRequestJson, String authHeader) throws InferenceException, ApiKeyException {
    Serving serving = servingFacade.findByProjectAndName(project, modelName);
    if (serving == null) {
        throw new InferenceException(RESTCodes.InferenceErrorCode.SERVING_NOT_FOUND, Level.FINE, "name: " + modelName);
    }
    if (verb == null) {
        throw new InferenceException(RESTCodes.InferenceErrorCode.MISSING_VERB, Level.FINE);
    }
    if (modelVersion != null && modelVersion < 0) {
        throw new InferenceException(RESTCodes.InferenceErrorCode.BAD_REQUEST, Level.FINE, "Model version must be " + "positive");
    }
    // ServingInferenceController is either localhost or kubernetes inference controller
    Pair<Integer, String> inferenceResult = servingInferenceController.infer(username, serving, modelVersion, verb, inferenceRequestJson, authHeader);
    // Log the inference
    for (InferenceLogger inferenceLogger : inferenceLoggers) {
        try {
            inferenceLogger.logInferenceRequest(serving, inferenceRequestJson, inferenceResult.getL(), inferenceResult.getR());
        } catch (Exception e) {
            // We don't want to fill the logs with inference logging errors
            logger.log(Level.FINE, "Error logging inference for logger: " + inferenceLogger.getClassName(), e);
        }
    }
    // If the inference server returned something different than 200 then throw an exception to the user
    if (inferenceResult.getL() >= 500) {
        logger.log(Level.FINE, "Request error: " + inferenceResult.getL() + " - " + inferenceResult.getR());
        throw new InferenceException(RESTCodes.InferenceErrorCode.SERVING_INSTANCE_INTERNAL, Level.FINE, inferenceResult.getR());
    } else if (inferenceResult.getL() >= 400) {
        logger.log(Level.FINE, "Request error: " + inferenceResult.getL() + " - " + inferenceResult.getR());
        throw new InferenceException(RESTCodes.InferenceErrorCode.SERVING_INSTANCE_BAD_REQUEST, Level.FINE, inferenceResult.getR());
    }
    return inferenceResult.getR();
}
Also used : Serving(io.hops.hopsworks.persistence.entity.serving.Serving) InferenceLogger(io.hops.hopsworks.common.serving.inference.logger.InferenceLogger) InferenceException(io.hops.hopsworks.exceptions.InferenceException) InferenceException(io.hops.hopsworks.exceptions.InferenceException) ApiKeyException(io.hops.hopsworks.exceptions.ApiKeyException)

Example 5 with ApiKeyException

use of io.hops.hopsworks.exceptions.ApiKeyException 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)

Aggregations

ApiKeyException (io.hops.hopsworks.exceptions.ApiKeyException)9 ApiKey (io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKey)5 Secret (io.hops.hopsworks.common.security.utils.Secret)3 ApiScope (io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiScope)3 Users (io.hops.hopsworks.persistence.entity.user.Users)2 ApiKeyScope (io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiKeyScope)2 IOException (java.io.IOException)2 Date (java.util.Date)2 ServiceDiscoveryException (com.logicalclocks.servicediscoverclient.exceptions.ServiceDiscoveryException)1 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 InferenceLogger (io.hops.hopsworks.common.serving.inference.logger.InferenceLogger)1 InferenceException (io.hops.hopsworks.exceptions.InferenceException)1 ServiceException (io.hops.hopsworks.exceptions.ServiceException)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 Serving (io.hops.hopsworks.persistence.entity.serving.Serving)1 JsonResponse (io.hops.hopsworks.restutils.JsonResponse)1