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