Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(credentials): add credentials test endpoint #1432

Merged
merged 8 commits into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 53 additions & 36 deletions src/main/java/io/cryostat/net/AgentClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,10 @@
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.codec.BodyCodec;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.auth.InvalidCredentialsException;

class AgentClient {
public class AgentClient {
public static final String NULL_CREDENTIALS = "No credentials found for agent";

private final Vertx vertx;
private final Gson gson;
Expand Down Expand Up @@ -212,41 +214,56 @@ Future<List<String>> eventTemplates() {
private <T> Future<HttpResponse<T>> invoke(HttpMethod mtd, String path, BodyCodec<T> codec) {
return Future.fromCompletionStage(
CompletableFuture.supplyAsync(
() -> {
logger.info("{} {} {}", mtd, agentUri, path);
HttpRequest<T> req =
webClient
.request(
mtd,
agentUri.getPort(),
agentUri.getHost(),
path)
.ssl("https".equals(agentUri.getScheme()))
.timeout(Duration.ofSeconds(httpTimeout).toMillis())
.followRedirects(true)
.as(codec);
try {
Credentials credentials =
credentialsManager.getCredentialsByTargetId(
agentUri.toString());
req =
req.authentication(
new UsernamePasswordCredentials(
credentials.getUsername(),
credentials.getPassword()));
} catch (ScriptException e) {
logger.error(e);
throw new RuntimeException(e);
}

try {
return req.send().toCompletionStage().toCompletableFuture().get();
} catch (InterruptedException | ExecutionException e) {
logger.error(e);
throw new RuntimeException(e);
}
},
ForkJoinPool.commonPool()));
() -> {
logger.info("{} {} {}", mtd, agentUri, path);
HttpRequest<T> req =
webClient
.request(
mtd,
agentUri.getPort(),
agentUri.getHost(),
path)
.ssl("https".equals(agentUri.getScheme()))
.timeout(
Duration.ofSeconds(httpTimeout)
.toMillis())
.followRedirects(true)
.as(codec);
try {
Credentials credentials =
credentialsManager.getCredentialsByTargetId(
agentUri.toString());
if (credentials == null
|| credentials.getUsername() == null
|| credentials.getPassword() == null) {
throw new InvalidCredentialsException(
NULL_CREDENTIALS + " " + agentUri);
}
req =
req.authentication(
new UsernamePasswordCredentials(
credentials.getUsername(),
credentials.getPassword()));
} catch (ScriptException | InvalidCredentialsException e) {
logger.error(e);
throw new RuntimeException(e);
}

try {
return req.send()
.toCompletionStage()
.toCompletableFuture()
.get();
} catch (InterruptedException | ExecutionException e) {
logger.error(e);
throw new RuntimeException(e);
}
},
ForkJoinPool.commonPool())
.exceptionally(
t -> {
throw new RuntimeException(t);
}));
}

static class Factory {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package io.cryostat.net.web.http.api.beta;

import java.util.Set;

import javax.inject.Inject;

import io.cryostat.configuration.CredentialsManager;
import io.cryostat.core.log.Logger;
import io.cryostat.net.AuthManager;
import io.cryostat.net.security.ResourceAction;
import io.cryostat.net.web.http.AbstractAuthenticatedRequestHandler;
import io.cryostat.net.web.http.api.ApiVersion;

import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

public class CredentialTestPostBodyHandler extends AbstractAuthenticatedRequestHandler {

static final BodyHandler BODY_HANDLER = BodyHandler.create(true).setHandleFileUploads(false);

@Inject
CredentialTestPostBodyHandler(
AuthManager auth, CredentialsManager credentialsManager, Logger logger) {
super(auth, credentialsManager, logger);
}

@Override
public int getPriority() {
return DEFAULT_PRIORITY - 1;
}

@Override
public ApiVersion apiVersion() {
return ApiVersion.BETA;
}

@Override
public HttpMethod httpMethod() {
return HttpMethod.POST;
}

@Override
public Set<ResourceAction> resourceActions() {
return ResourceAction.NONE;
}

@Override
public String path() {
return basePath() + CredentialTestPostHandler.PATH;
}

@Override
public void handleAuthenticated(RoutingContext ctx) throws Exception {
BODY_HANDLER.handle(ctx);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
/*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.cryostat.net.web.http.api.beta;

import java.util.EnumSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import org.openjdk.jmc.rjmx.ConnectionException;

import io.cryostat.configuration.CredentialsManager;
import io.cryostat.core.net.Credentials;
import io.cryostat.net.AgentClient;
import io.cryostat.net.AuthManager;
import io.cryostat.net.ConnectionDescriptor;
import io.cryostat.net.TargetConnectionManager;
import io.cryostat.net.security.ResourceAction;
import io.cryostat.net.web.http.AbstractAuthenticatedRequestHandler;
import io.cryostat.net.web.http.HttpMimeType;
import io.cryostat.net.web.http.api.ApiVersion;
import io.cryostat.net.web.http.api.beta.CredentialTestPostHandler.CredentialTestResult;
import io.cryostat.net.web.http.api.v2.AbstractV2RequestHandler;
import io.cryostat.net.web.http.api.v2.ApiException;
import io.cryostat.net.web.http.api.v2.IntermediateResponse;
import io.cryostat.net.web.http.api.v2.RequestParameters;

import com.google.gson.Gson;
import io.vertx.core.http.HttpMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

public class CredentialTestPostHandler extends AbstractV2RequestHandler<CredentialTestResult> {

static final String PATH = "credentials/:targetId";

private final TargetConnectionManager tcm;

@Inject
CredentialTestPostHandler(
AuthManager auth,
CredentialsManager credentialsManager,
Gson gson,
TargetConnectionManager tcm) {
super(auth, credentialsManager, gson);
this.tcm = tcm;
}

@Override
public boolean requiresAuthentication() {
return true;
}

@Override
public ApiVersion apiVersion() {
return ApiVersion.BETA;
}

@Override
public HttpMethod httpMethod() {
return HttpMethod.POST;
}

@Override
public Set<ResourceAction> resourceActions() {
return EnumSet.of(ResourceAction.READ_TARGET);
}

@Override
public String path() {
return basePath() + PATH;
}

@Override
public List<HttpMimeType> produces() {
return List.of(HttpMimeType.JSON);
}

@Override
public boolean isAsync() {
return false;
}

@Override
public IntermediateResponse<CredentialTestResult> handle(RequestParameters params)
throws Exception {
String targetId = params.getPathParams().get("targetId");
String username = params.getFormAttributes().get("username");
String password = params.getFormAttributes().get("password");
if (StringUtils.isAnyBlank(targetId, username, password)) {
StringBuilder sb = new StringBuilder();
if (StringUtils.isBlank(targetId)) {
sb.append("\"targetId\" is required.");
}
if (StringUtils.isBlank(username)) {
sb.append("\"username\" is required.");
}
if (StringUtils.isBlank(password)) {
sb.append(" \"password\" is required.");
}

throw new ApiException(400, sb.toString().trim());
}
ConnectionDescriptor noCreds = new ConnectionDescriptor(targetId, null);

try {
return new IntermediateResponse<CredentialTestResult>()
.body(
tcm.executeConnectedTask(
noCreds,
(conn) -> {
conn.connect();
return CredentialTestResult.NA;
}));
} catch (Exception e1) {
if (AbstractAuthenticatedRequestHandler.isJmxAuthFailure(e1)
|| isAgentAuthFailure(e1)) {
ConnectionDescriptor creds =
new ConnectionDescriptor(targetId, new Credentials(username, password));
try {
return new IntermediateResponse<CredentialTestResult>()
.body(
tcm.executeConnectedTask(
creds,
(conn) -> {
conn.connect();
return CredentialTestResult.SUCCESS;
}));
} catch (Exception e2) {
if (AbstractAuthenticatedRequestHandler.isJmxAuthFailure(e2)
|| isAgentAuthFailure(e2)) {
return new IntermediateResponse<CredentialTestResult>()
.body(CredentialTestResult.FAILURE);
}
throw e2;
}
}
throw e1;
}
}

boolean isAgentAuthFailure(Exception e) {
int index = ExceptionUtils.indexOfType(e, ConnectionException.class);
if (index >= 0) {
Throwable ce = ExceptionUtils.getThrowableList(e).get(index);
return ce.getMessage().contains(AgentClient.NULL_CREDENTIALS);
}
return false;
}

static enum CredentialTestResult {
SUCCESS,
FAILURE,
NA;
}
}
Loading