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(auth): Add OAuth logout #786

Merged
merged 17 commits into from
Jan 18, 2022
4 changes: 4 additions & 0 deletions src/main/java/io/cryostat/net/AuthManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
*/
package io.cryostat.net;

import java.io.IOException;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
Expand All @@ -55,6 +56,9 @@ Optional<String> getLoginRedirectUrl(
Supplier<String> headerProvider, Set<ResourceAction> resourceActions)
throws ExecutionException, InterruptedException;

Optional<String> logout(Supplier<String> httpHeaderProvider)
throws ExecutionException, InterruptedException, IOException, TokenNotFoundException;

Future<Boolean> validateToken(
Supplier<String> tokenProvider, Set<ResourceAction> resourceActions);

Expand Down
5 changes: 5 additions & 0 deletions src/main/java/io/cryostat/net/BasicAuthManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,11 @@ public Future<Boolean> validateWebSocketSubProtocol(
}
}

@Override
public Optional<String> logout(Supplier<String> httpHeaderProvider) {
return Optional.empty();
}

private Pair<String, String> splitCredentials(String credentials) {
if (credentials == null) {
return null;
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/io/cryostat/net/NoopAuthManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,9 @@ public Future<Boolean> validateWebSocketSubProtocol(
Supplier<String> subProtocolProvider, Set<ResourceAction> resourceActions) {
return CompletableFuture.completedFuture(true);
}

@Override
public Optional<String> logout(Supplier<String> httpHeaderProvider) {
return Optional.empty();
}
}
159 changes: 114 additions & 45 deletions src/main/java/io/cryostat/net/OpenShiftAuthManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
Expand Down Expand Up @@ -80,6 +79,7 @@
import jdk.jfr.Event;
import jdk.jfr.Label;
import jdk.jfr.Name;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URIBuilder;

Expand All @@ -89,15 +89,19 @@ public class OpenShiftAuthManager extends AbstractAuthManager {
Set.of(GroupResource.PERMISSION_NOT_REQUIRED);
private static final String OAUTH_WELL_KNOWN_HOST = "openshift.default.svc";
private static final String WELL_KNOWN_PATH = "/.well-known/oauth-authorization-server";
private static final String OAUTH_ENDPOINT_KEY = "authorization_endpoint";
private static final String BASE_URL = "issuer";
private static final String AUTHORIZATION_URL_KEY = "authorization_endpoint";
private static final String LOGOUT_URL_KEY = "logout";
private static final String OAUTH_METADATA_KEY = "oauth_metadata";
private static final String CRYOSTAT_OAUTH_CLIENT_ID = "CRYOSTAT_OAUTH_CLIENT_ID";
private static final String CRYOSTAT_OAUTH_ROLE = "CRYOSTAT_OAUTH_ROLE";

private final Environment env;
private final FileSystem fs;
private final Function<String, OpenShiftClient> clientProvider;
private final WebClient webClient;
private final ConcurrentHashMap<String, CompletableFuture<String>> authorizationUrl;
private final ConcurrentHashMap<String, CompletableFuture<String>> oauthUrls;
private final ConcurrentHashMap<String, CompletableFuture<JsonObject>> oauthMetadata;

OpenShiftAuthManager(
Environment env,
Expand All @@ -110,7 +114,8 @@ public class OpenShiftAuthManager extends AbstractAuthManager {
this.fs = fs;
this.clientProvider = clientProvider;
this.webClient = webClient;
this.authorizationUrl = new ConcurrentHashMap<>(1);
this.oauthUrls = new ConcurrentHashMap<>(2);
this.oauthMetadata = new ConcurrentHashMap<>(1);
}

@Override
Expand Down Expand Up @@ -159,6 +164,16 @@ public Optional<String> getLoginRedirectUrl(
}
}

@Override
public Optional<String> logout(Supplier<String> httpHeaderProvider)
throws ExecutionException, InterruptedException, IOException, TokenNotFoundException {

String token = getTokenFromHttpHeader(httpHeaderProvider.get());
deleteToken(token);

return Optional.of(this.computeLogoutRedirectEndpoint().get());
}

@Override
public Future<Boolean> validateToken(
Supplier<String> tokenProvider, Set<ResourceAction> resourceActions) {
Expand Down Expand Up @@ -296,6 +311,23 @@ public Future<Boolean> validateWebSocketSubProtocol(
}
}

private Boolean deleteToken(String token) throws IOException, TokenNotFoundException {
andrewazores marked this conversation as resolved.
Show resolved Hide resolved
try (OpenShiftClient client = clientProvider.apply(getServiceAccountToken())) {
Boolean deleted =
Optional.ofNullable(
client.oAuthAccessTokens()
.withName(this.getOauthAccessTokenName(token))
.delete())
.orElseThrow(TokenNotFoundException::new);

if (Boolean.FALSE.equals(deleted)) {
throw new TokenNotFoundException();
}

return deleted;
}
}

private String getTokenFromHttpHeader(String rawHttpHeader) {
if (StringUtils.isBlank(rawHttpHeader)) {
return null;
Expand Down Expand Up @@ -334,67 +366,104 @@ private Future<TokenReviewStatus> performTokenReview(String token) {
}

private CompletableFuture<String> computeAuthorizationEndpoint() {
return authorizationUrl.computeIfAbsent(
OAUTH_ENDPOINT_KEY,

return oauthUrls.computeIfAbsent(
AUTHORIZATION_URL_KEY,
key -> {
CompletableFuture<JsonObject> oauthMetadata = new CompletableFuture<>();
try {
String namespace = this.getNamespace();
Optional<String> clientId =
Optional.ofNullable(env.getEnv(CRYOSTAT_OAUTH_CLIENT_ID));
Optional<String> roleScope =
Optional.ofNullable(env.getEnv(CRYOSTAT_OAUTH_ROLE));

String serviceAccountAsOAuthClient =
String.format(
"system:serviceaccount:%s:%s",
namespace,
clientId.orElseThrow(
() ->
new MissingEnvironmentVariableException(
CRYOSTAT_OAUTH_CLIENT_ID)));

String scope =
String.format(
"user:check-access role:%s:%s",
roleScope.orElseThrow(
() ->
new MissingEnvironmentVariableException(
CRYOSTAT_OAUTH_ROLE)),
namespace);
String oauthClient = this.getServiceAccountName();
String tokenScope = this.getTokenScope();

webClient
.get(443, OAUTH_WELL_KNOWN_HOST, WELL_KNOWN_PATH)
.putHeader("Accept", "application/json")
.send(
ar -> {
if (ar.failed()) {
oauthMetadata.completeExceptionally(ar.cause());
return;
}
oauthMetadata.complete(ar.result().bodyAsJsonObject());
});
CompletableFuture<JsonObject> oauthMetadata = this.computeOauthMetadata();

String authorizeEndpoint =
oauthMetadata.get().getString(OAUTH_ENDPOINT_KEY);
oauthMetadata.get().getString(AUTHORIZATION_URL_KEY);

URIBuilder builder = new URIBuilder(authorizeEndpoint);
builder.addParameter("client_id", serviceAccountAsOAuthClient);
builder.addParameter("client_id", oauthClient);
builder.addParameter("response_type", "token");
builder.addParameter("response_mode", "fragment");
builder.addParameter("scope", scope);
builder.addParameter("scope", tokenScope);

return CompletableFuture.completedFuture(builder.build().toString());
} catch (ExecutionException
| InterruptedException
| URISyntaxException
| IOException
| MissingEnvironmentVariableException e) {
throw new CompletionException(e);
return CompletableFuture.failedFuture(e);
}
});
}

private CompletableFuture<String> computeLogoutRedirectEndpoint() {
jan-law marked this conversation as resolved.
Show resolved Hide resolved
return oauthUrls.computeIfAbsent(
LOGOUT_URL_KEY,
key -> {
try {
CompletableFuture<JsonObject> oauthMetadata = this.computeOauthMetadata();
String baseUrl = oauthMetadata.get().getString(BASE_URL);

return CompletableFuture.completedFuture(
String.format("%s/logout", baseUrl));
} catch (ExecutionException | InterruptedException e) {
return CompletableFuture.failedFuture(e);
}
});
}

private CompletableFuture<JsonObject> computeOauthMetadata() {
return oauthMetadata.computeIfAbsent(
OAUTH_METADATA_KEY,
key -> {
CompletableFuture<JsonObject> oauthMetadata = new CompletableFuture<>();
try {
webClient
.get(443, OAUTH_WELL_KNOWN_HOST, WELL_KNOWN_PATH)
.putHeader("Accept", "application/json")
.send(
ar -> {
if (ar.failed()) {
oauthMetadata.completeExceptionally(ar.cause());
return;
}
oauthMetadata.complete(ar.result().bodyAsJsonObject());
});
return CompletableFuture.completedFuture(oauthMetadata.get());
} catch (ExecutionException | InterruptedException e) {
return CompletableFuture.failedFuture(e);
}
});
}

private String getServiceAccountName() throws MissingEnvironmentVariableException, IOException {
Optional<String> clientId = Optional.ofNullable(env.getEnv(CRYOSTAT_OAUTH_CLIENT_ID));
return String.format(
"system:serviceaccount:%s:%s",
this.getNamespace(),
clientId.orElseThrow(
() -> new MissingEnvironmentVariableException(CRYOSTAT_OAUTH_CLIENT_ID)));
}

private String getTokenScope() throws MissingEnvironmentVariableException, IOException {
Optional<String> tokenScope = Optional.ofNullable(env.getEnv(CRYOSTAT_OAUTH_ROLE));
return String.format(
"user:check-access role:%s:%s",
tokenScope.orElseThrow(
() -> new MissingEnvironmentVariableException(CRYOSTAT_OAUTH_ROLE)),
this.getNamespace());
}

private String getOauthAccessTokenName(String token) {
String sha256Prefix = "sha256~";
String rawToken = StringUtils.removeStart(token, sha256Prefix);
byte[] checksum = DigestUtils.sha256(rawToken);
String encodedTokenHash =
new String(Base64.getUrlEncoder().encode(checksum), StandardCharsets.UTF_8).trim();

return sha256Prefix + StringUtils.removeEnd(encodedTokenHash, "=");
}

@SuppressFBWarnings(
value = "DMI_HARDCODED_ABSOLUTE_FILENAME",
justification = "Kubernetes namespace file path is well-known and absolute")
Expand Down
44 changes: 44 additions & 0 deletions src/main/java/io/cryostat/net/TokenNotFoundException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* 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;

public class TokenNotFoundException extends Exception {
public TokenNotFoundException() {
super(String.format("Token not found"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ public abstract class HttpApiV2Module {
@IntoSet
abstract RequestHandler bindAuthPostHandler(AuthPostHandler handler);

@Binds
@IntoSet
abstract RequestHandler bindLogoutPostHandler(LogoutPostHandler handler);

@Binds
@IntoSet
abstract RequestHandler bindApiGetHandler(ApiGetHandler handler);
Expand Down
Loading