use of io.pravega.auth.AuthException in project pravega by pravega.
the class StreamMetadataResourceImpl method listScopes.
/**
* Implementation of listScopes REST API.
*
* @param securityContext The security for API access.
* @param asyncResponse AsyncResponse provides means for asynchronous server side response processing.
*/
@Override
public void listScopes(final SecurityContext securityContext, final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "listScopes");
long requestId = requestIdGenerator.nextLong();
final Principal principal;
final List<String> authHeader = getAuthorizationHeader();
try {
principal = restAuthHelper.authenticate(authHeader);
restAuthHelper.authorize(authHeader, authorizationResource.ofScopes(), principal, READ);
} catch (AuthException e) {
log.warn(requestId, "Get scopes failed due to authentication failure.", e);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "listScopes", traceId);
return;
}
controllerService.listScopes(requestId).thenApply(scopesList -> {
ScopesList scopes = new ScopesList();
scopesList.forEach(scope -> {
try {
if (restAuthHelper.isAuthorized(authHeader, authorizationResource.ofScope(scope), principal, READ)) {
scopes.addScopesItem(new ScopeProperty().scopeName(scope));
}
} catch (AuthException e) {
log.warn(requestId, e.getMessage(), e);
// Ignore. This exception occurs under abnormal circumstances and not to determine
// whether the user is authorized. In case it does occur, we assume that the user
// is unauthorized.
}
});
return Response.status(Status.OK).entity(scopes).build();
}).exceptionally(exception -> {
log.warn(requestId, "listScopes failed with exception: ", exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}).thenApply(response -> {
asyncResponse.resume(response);
LoggerHelpers.traceLeave(log, "listScopes", traceId);
return response;
});
}
use of io.pravega.auth.AuthException in project pravega by pravega.
the class StreamMetadataResourceImpl method updateStream.
/**
* Implementation of updateStream REST API.
*
* @param scopeName The scope name of stream.
* @param streamName The name of stream.
* @param updateStreamRequest The object conforming to updateStreamConfig request json.
* @param securityContext The security for API access.
* @param asyncResponse AsyncResponse provides means for asynchronous server side response processing.
*/
@Override
public void updateStream(final String scopeName, final String streamName, final UpdateStreamRequest updateStreamRequest, final SecurityContext securityContext, final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "updateStream");
long requestId = requestIdGenerator.nextLong();
try {
restAuthHelper.authenticateAuthorize(getAuthorizationHeader(), authorizationResource.ofStreamInScope(scopeName, streamName), READ_UPDATE);
} catch (AuthException e) {
log.warn(requestId, "Update stream for {} failed due to authentication failure.", scopeName + "/" + streamName);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "Update stream", traceId);
return;
}
StreamConfiguration streamConfiguration = ModelHelper.getUpdateStreamConfig(updateStreamRequest);
controllerService.updateStream(scopeName, streamName, streamConfiguration, requestId).thenApply(streamStatus -> {
if (streamStatus.getStatus() == UpdateStreamStatus.Status.SUCCESS) {
log.info(requestId, "Successfully updated stream config for: {}/{}", scopeName, streamName);
return Response.status(Status.OK).entity(ModelHelper.encodeStreamResponse(scopeName, streamName, streamConfiguration)).build();
} else if (streamStatus.getStatus() == UpdateStreamStatus.Status.STREAM_NOT_FOUND || streamStatus.getStatus() == UpdateStreamStatus.Status.SCOPE_NOT_FOUND) {
log.warn(requestId, "Stream: {}/{} not found", scopeName, streamName);
return Response.status(Status.NOT_FOUND).build();
} else {
log.warn(requestId, "updateStream failed for {}/{}", scopeName, streamName);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}).exceptionally(exception -> {
log.warn(requestId, "updateStream for {}/{} failed with exception: {}", scopeName, streamName, exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}).thenApply(asyncResponse::resume).thenAccept(x -> LoggerHelpers.traceLeave(log, "updateStream", traceId));
}
use of io.pravega.auth.AuthException in project pravega by pravega.
the class StreamMetadataResourceImpl method createStream.
/**
* Implementation of createStream REST API.
*
* @param scopeName The scope name of stream.
* @param createStreamRequest The object conforming to createStream request json.
* @param securityContext The security for API access.
* @param asyncResponse AsyncResponse provides means for asynchronous server side response processing.
*/
@Override
public void createStream(final String scopeName, final CreateStreamRequest createStreamRequest, final SecurityContext securityContext, final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "createStream");
long requestId = requestIdGenerator.nextLong();
String streamName = createStreamRequest.getStreamName();
try {
NameUtils.validateUserStreamName(streamName);
} catch (IllegalArgumentException | NullPointerException e) {
log.warn(requestId, "Create stream failed due to invalid stream name {}", streamName);
asyncResponse.resume(Response.status(Status.BAD_REQUEST).build());
LoggerHelpers.traceLeave(log, "createStream", traceId);
return;
}
try {
restAuthHelper.authenticateAuthorize(getAuthorizationHeader(), authorizationResource.ofStreamsInScope(scopeName), READ_UPDATE);
} catch (AuthException e) {
log.warn(requestId, "Create stream for {} failed due to authentication failure.", streamName);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "createStream", traceId);
return;
}
StreamConfiguration streamConfiguration = ModelHelper.getCreateStreamConfig(createStreamRequest);
controllerService.createStream(scopeName, streamName, streamConfiguration, System.currentTimeMillis(), requestId).thenApply(streamStatus -> {
Response resp = null;
if (streamStatus.getStatus() == CreateStreamStatus.Status.SUCCESS) {
log.info(requestId, "Successfully created stream: {}/{}", scopeName, streamName);
resp = Response.status(Status.CREATED).entity(ModelHelper.encodeStreamResponse(scopeName, streamName, streamConfiguration)).build();
} else if (streamStatus.getStatus() == CreateStreamStatus.Status.STREAM_EXISTS) {
log.warn(requestId, "Stream already exists: {}/{}", scopeName, streamName);
resp = Response.status(Status.CONFLICT).build();
} else if (streamStatus.getStatus() == CreateStreamStatus.Status.SCOPE_NOT_FOUND) {
log.warn(requestId, "Scope not found: {}", scopeName);
resp = Response.status(Status.NOT_FOUND).build();
} else if (streamStatus.getStatus() == CreateStreamStatus.Status.INVALID_STREAM_NAME) {
log.warn(requestId, "Invalid stream name: {}", streamName);
resp = Response.status(Status.BAD_REQUEST).build();
} else {
log.warn(requestId, "createStream failed for : {}/{}", scopeName, streamName);
resp = Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
return resp;
}).exceptionally(exception -> {
log.warn(requestId, "createStream for {}/{} failed: ", scopeName, streamName, exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}).thenApply(asyncResponse::resume).thenAccept(x -> LoggerHelpers.traceLeave(log, "createStream", traceId));
}
use of io.pravega.auth.AuthException in project pravega by pravega.
the class AuthHandlerManager method authenticateAndAuthorize.
/**
* API to authenticate and authorize access to a given resource.
* @param resource The resource identifier for which the access needs to be controlled.
* @param credentials Credentials used for authentication.
* @param level Expected level of access.
* @return Returns true if the entity represented by the custom auth headers had given level of access to the resource.
* Returns false if the entity does not have access.
* @throws AuthenticationException if an authentication failure occurred.
*/
public boolean authenticateAndAuthorize(String resource, String credentials, AuthHandler.Permissions level) throws AuthenticationException {
Preconditions.checkNotNull(credentials, "credentials");
boolean retVal = false;
try {
String[] parts = extractMethodAndToken(credentials);
String method = parts[0];
String token = parts[1];
AuthHandler handler = getHandler(method);
Preconditions.checkNotNull(handler, "Can not find handler.");
Principal principal;
if ((principal = handler.authenticate(token)) == null) {
throw new AuthenticationException("Authentication failure");
}
retVal = handler.authorize(resource, principal).ordinal() >= level.ordinal();
} catch (AuthException e) {
throw new AuthenticationException("Authentication failure");
}
return retVal;
}
use of io.pravega.auth.AuthException in project pravega by pravega.
the class AuthInterceptor method interceptCall.
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
Context context = Context.current();
// The authorization header has the credentials (e.g., username and password for Basic Authentication).
// The form of the header is: <Method> <Token> (CustomMethod static-token, or Basic XYZ...., for example)
String credentials = headers.get(Metadata.Key.of(AuthConstants.AUTHORIZATION, Metadata.ASCII_STRING_MARSHALLER));
if (!Strings.isNullOrEmpty(credentials)) {
String[] parts = credentials.split("\\s+", 2);
if (parts.length == 2) {
String method = parts[0];
String token = parts[1];
if (!Strings.isNullOrEmpty(method)) {
if (method.equals(handler.getHandlerName())) {
log.debug("Handler [{}] successfully matched auth method [{}]", handler, method);
Principal principal;
try {
if ((principal = handler.authenticate(token)) == null) {
log.warn("Handler for method [{}] returned a null Principal upon authentication for the" + "given token", method);
call.close(Status.fromCode(Status.Code.UNAUTHENTICATED), headers);
return null;
}
} catch (AuthException e) {
log.warn("Authentication failed", e);
call.close(Status.fromCode(Status.Code.UNAUTHENTICATED), headers);
return null;
}
// Creates a new Context with the given key/value pairs.
context = context.withValues(PRINCIPAL_OBJECT_KEY, principal, AUTH_INTERCEPTOR_OBJECT_KEY, this);
}
} else {
log.debug("Credentials are present, but method [{}] is null or empty", method);
}
}
}
// reaching this point means that the handler wasn't applicable to this request.
return Contexts.interceptCall(context, call, headers, next);
}
Aggregations