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

fix(credentials): store JMX session credentials in ThreadLocal #1388

Merged
8 changes: 4 additions & 4 deletions repeated-integration-tests.bash
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fi

getPomProperty() {
if command -v xpath > /dev/null 2>&1 ; then
xpath -q -e "project/properties/$1/text()" pom.xml
xpath -q -e "project/$1/text()" pom.xml
elif command -v mvnd > /dev/null 2>&1 ; then
mvnd help:evaluate -o -B -q -DforceStdout -Dexpression="$1"
else
Expand All @@ -26,15 +26,15 @@ getPomProperty() {
}

if [ -z "${POD_NAME}" ]; then
POD_NAME="$(getPomProperty cryostat.itest.podName)"
POD_NAME="$(getPomProperty properties/cryostat.itest.podName)"
fi

if [ -z "${CONTAINER_NAME}" ]; then
CONTAINER_NAME="$(getPomProperty cryostat.itest.containerName)"
CONTAINER_NAME="$(getPomProperty properties/cryostat.itest.containerName)"
fi

if [ -z "${ITEST_IMG_VERSION}" ]; then
ITEST_IMG_VERSION="$(getPomProperty project.version)"
ITEST_IMG_VERSION="$(getPomProperty version)"
ITEST_IMG_VERSION="${ITEST_IMG_VERSION,,}" # lowercase
fi

Expand Down
24 changes: 24 additions & 0 deletions src/main/java/io/cryostat/configuration/CredentialsManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ public class CredentialsManager
private final Gson gson;
private final Logger logger;

public static final ThreadLocal<Map<String, Credentials>> SESSION_CREDENTIALS =
ThreadLocal.withInitial(() -> new HashMap<>());

CredentialsManager(
Path credentialsDir,
MatchExpressionValidator matchExpressionValidator,
Expand Down Expand Up @@ -181,7 +184,23 @@ public int removeCredentials(String matchExpression) throws MatchExpressionValid
return -1;
}

public void setSessionCredentials(String targetId, Credentials credentials) {
if (credentials == null) {
SESSION_CREDENTIALS.get().remove(targetId);
} else {
SESSION_CREDENTIALS.get().put(targetId, credentials);
}
}

public Credentials getSessionCredentials(String targetId) {
return SESSION_CREDENTIALS.get().get(targetId);
}

public Credentials getCredentialsByTargetId(String targetId) throws ScriptException {
Credentials sessionCredentials = getSessionCredentials(targetId);
if (sessionCredentials != null) {
return sessionCredentials;
}
for (ServiceRef service : this.platformClient.listDiscoverableServices()) {
if (Objects.equals(targetId, service.getServiceUri().toString())) {
return getCredentials(service);
Expand All @@ -191,6 +210,11 @@ public Credentials getCredentialsByTargetId(String targetId) throws ScriptExcept
}

public Credentials getCredentials(ServiceRef serviceRef) throws ScriptException {
Credentials sessionCredentials =
getSessionCredentials(serviceRef.getServiceUri().toString());
if (sessionCredentials != null) {
return sessionCredentials;
}
for (StoredCredentials sc : dao.getAll()) {
if (matchExpressionEvaluator.get().applies(sc.getMatchExpression(), serviceRef)) {
return sc.getCredentials();
Expand Down
12 changes: 10 additions & 2 deletions src/main/java/io/cryostat/net/ConnectionDescriptor.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@

import java.util.Optional;

import io.cryostat.configuration.CredentialsManager;
import io.cryostat.core.net.Credentials;
import io.cryostat.platform.ServiceRef;

Expand All @@ -54,12 +55,19 @@ public ConnectionDescriptor(ServiceRef serviceRef) {
this(serviceRef.getServiceUri().toString());
}

// TODO remove this constructor, all descriptors should explicitly specify any credentials
public ConnectionDescriptor(String targetId) {
this(targetId, null);
this(targetId, CredentialsManager.SESSION_CREDENTIALS.get().get(targetId));
}

public ConnectionDescriptor(ServiceRef serviceRef, Credentials credentials) {
this(serviceRef.getServiceUri().toString(), credentials);
this(
serviceRef.getServiceUri().toString(),
Optional.ofNullable(
CredentialsManager.SESSION_CREDENTIALS
.get()
.get(serviceRef.getServiceUri().toString()))
.orElse(credentials));
}

public ConnectionDescriptor(String targetId, Credentials credentials) {
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/io/cryostat/net/NetworkModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.time.Duration;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ExecutorService;

import javax.inject.Named;
import javax.inject.Singleton;
Expand Down Expand Up @@ -132,12 +132,13 @@ static TargetConnectionManager provideTargetConnectionManager(
DiscoveryStorage storage,
@Named(Variables.TARGET_CACHE_TTL) Duration maxTargetTtl,
@Named(Variables.TARGET_MAX_CONCURRENT_CONNECTIONS) int maxTargetConnections,
@Named(WebModule.VERTX_EXECUTOR) ExecutorService executor,
Logger logger) {
return new TargetConnectionManager(
connectionToolkit,
agentConnectionFactory,
storage,
ForkJoinPool.commonPool(),
executor,
Scheduler.systemScheduler(),
maxTargetTtl,
maxTargetConnections,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@

import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;

import javax.inject.Named;
Expand All @@ -49,6 +49,7 @@
import io.cryostat.core.sys.Environment;
import io.cryostat.core.sys.FileSystem;
import io.cryostat.net.AuthManager;
import io.cryostat.net.web.WebModule;
import io.cryostat.util.resource.ClassPropertiesLoader;

import com.github.benmanes.caffeine.cache.Scheduler;
Expand Down Expand Up @@ -128,6 +129,7 @@ static OpenShiftClient provideServiceAccountClient(
@Singleton
static OpenShiftAuthManager provideOpenShiftAuthManager(
Environment env,
@Named(WebModule.VERTX_EXECUTOR) ExecutorService executor,
@Named(OPENSHIFT_NAMESPACE) Lazy<String> namespace,
Lazy<OpenShiftClient> serviceAccountClient,
@Named(TOKENED_CLIENT) Function<String, OpenShiftClient> clientProvider,
Expand All @@ -141,7 +143,7 @@ static OpenShiftAuthManager provideOpenShiftAuthManager(
clientProvider,
classPropertiesLoader,
gson,
ForkJoinPool.commonPool(),
executor,
Scheduler.systemScheduler(),
logger);
}
Expand Down
99 changes: 99 additions & 0 deletions src/main/java/io/cryostat/net/web/Vertexecutor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package io.cryostat.net.web;
/*
* 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.
*/

import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;

import io.cryostat.core.log.Logger;

import io.vertx.core.Vertx;

public class Vertexecutor extends AbstractExecutorService {

private final Vertx vertx;
private final Logger logger;

Vertexecutor(Vertx vertx, Logger logger) {
this.vertx = vertx;
this.logger = logger;
}

@Override
public void execute(Runnable command) {
vertx.executeBlocking(
promise -> {
try {
command.run();
promise.complete();
} catch (Exception e) {
promise.fail(e);
}
},
false,
ar -> {
if (ar.failed()) {
logger.warn("Async task failure", ar.cause());
}
});
}

@Override
public void shutdown() {}

@Override
public List<Runnable> shutdownNow() {
return List.of();
}

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

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

@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return false;
}
}
10 changes: 10 additions & 0 deletions src/main/java/io/cryostat/net/web/WebModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import java.io.IOException;
import java.nio.file.Path;
import java.util.Set;
import java.util.concurrent.ExecutorService;

import javax.inject.Named;
import javax.inject.Singleton;
Expand All @@ -56,10 +57,12 @@
import com.google.gson.Gson;
import dagger.Module;
import dagger.Provides;
import io.vertx.core.Vertx;

@Module(includes = {HttpModule.class})
public abstract class WebModule {
public static final String WEBSERVER_TEMP_DIR_PATH = "WEBSERVER_TEMP_DIR_PATH";
public static final String VERTX_EXECUTOR = "VERTX_EXECUTOR";

@Provides
static WebServer provideWebServer(
Expand Down Expand Up @@ -90,4 +93,11 @@ static Path provideWebServerTempDirPath(FileSystem fs) {
throw new RuntimeException(ioe);
}
}

@Provides
@Singleton
@Named(VERTX_EXECUTOR)
static ExecutorService provideVertexecutor(Vertx vertx, Logger logger) {
return new Vertexecutor(vertx, logger);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ protected ConnectionDescriptor getConnectionDescriptorFromContext(RoutingContext
427, "Unrecognized " + JMX_AUTHORIZATION_HEADER + " credential format");
}
credentials = new Credentials(parts[0], parts[1]);
credentialsManager.setSessionCredentials(targetId, credentials);
ctx.addEndHandler(
unused -> credentialsManager.setSessionCredentials(targetId, null));
} else {
credentials = credentialsManager.getCredentialsByTargetId(targetId);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ public abstract IntermediateResponse<T> handle(RequestParameters requestParams)
@Override
public final void handle(RoutingContext ctx) {
RequestParameters requestParams = RequestParameters.from(ctx);
String targetId = requestParams.getPathParams().get("targetId");
if (targetId != null) {
ctx.addEndHandler(unused -> credentialsManager.setSessionCredentials(targetId, null));
}
try {
if (requiresAuthentication()) {
boolean permissionGranted =
Expand Down Expand Up @@ -164,6 +168,7 @@ protected ConnectionDescriptor getConnectionDescriptorFromParams(RequestParamete
+ " credential format");
}
credentials = new Credentials(parts[0], parts[1]);
credentialsManager.setSessionCredentials(targetId, credentials);
}
}
} else {
Expand Down
Loading