8000 Keep Admin CLI v2 requests and their bearer token on the configured server by yasser-rafid · Pull Request #55797 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package org.keycloak.client.admin.cli.v2;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.Map;

Expand Down Expand Up @@ -32,7 +36,7 @@ public KcAdmV2CommandDescriptor loadForServer(String serverUrl) {
if (entry == null || entry.version == null) {
return null;
}
Path descriptorFile = descriptorPath(entry.version);
Path descriptorFile = descriptorPath(serverUrl, entry.version);
if (!Files.isRegularFile(descriptorFile)) {
return null;
}
Expand All @@ -59,34 +63,38 @@ public void save(String serverUrl, KcAdmV2CommandDescriptor descriptor) {
String oldVersion = versionForServer(registry, serverUrl);

try {
Path p = descriptorPath(newVersion);
Path p = descriptorPath(serverUrl, newVersion);
8000 IoUtil.ensureFile(p);
OutputUtil.MAPPER.writeValue(p.toFile(), descriptor);
} catch (IOException e) {
throw new RuntimeException("Failed to write descriptor: " + descriptorPath(newVersion), e);
throw new RuntimeException("Failed to write descriptor: " + descriptorPath(serverUrl, newVersion), e);
}

registry.servers.put(serverUrl, new ServerEntry(newVersion));
writeRegistry(registry);

if (oldVersion != null && !oldVersion.equals(newVersion)) {
deleteOrphanedDescriptor(registry, oldVersion);
}
}

private void deleteOrphanedDescriptor(Registry registry, String version) {
boolean stillReferenced = registry.servers.values().stream().anyMatch(e -> version.equals(e.version));
if (!stillReferenced) {
if (oldVersion != null && !descriptorPath(serverUrl, oldVersion).equals(descriptorPath(serverUrl, newVersion))) {
try {
Files.deleteIfExists(descriptorPath(version));
Files.deleteIfExists(descriptorPath(serverUrl, oldVersion));
} catch (IOException ignored) {
}
}
}

private Path descriptorPath(String version) {
// Descriptors are stored per server: a descriptor fetched for one server must never be
// used to build requests (and attach credentials) for another server that reports the same version.
private Path descriptorPath(String serverUrl, String version) {
String sanitized = version.replaceAll("[^a-zA-Z0-9_-]", "_");
return cacheDir.resolve(DESCRIPTOR_PREFIX + sanitized + ".json");
return cacheDir.resolve(DESCRIPTOR_PREFIX + sanitized + "-" + serverKey(serverUrl) + ".json");
}

private static String serverKey(String serverUrl) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(serverUrl.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest, 0, 16);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 not available", e);
}
}

private String versionForServer(Registry registry, String serverUrl) {
Expand Down
10000
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Expand All @@ -22,6 +24,7 @@
import org.keycloak.client.cli.config.FileConfigHandler;
import org.keycloak.client.cli.config.InMemoryConfigHandler;
import org.keycloak.client.cli.util.ConfigUtil;
import org.keycloak.client.cli.util.Header;
import org.keycloak.client.cli.util.Headers;
import org.keycloak.client.cli.util.HeadersBody;
import org.keycloak.client.cli.util.HeadersBodyStatus;
Expand Down Expand Up @@ -56,6 +59,7 @@ class KcAdmV2RequestExecutor extends AbstractTargetAuthOptionsCmd implements Run
protected final AbstractTargetAuthOptionsCmd root;
private final CommandDescriptor descriptor;
private final VariantDescriptor variant;
private String requestServerUrl;

KcAdmV2RequestExecutor(AbstractTargetAuthOptionsCmd root, CommandDescriptor descriptor, VariantDescriptor variant) {
super();
Expand Down Expand Up @@ -147,6 +151,7 @@ protected final RequestContext prepareRequest() {
requestRealm = DEFAULT_REALM;
}
configData.setRealm(requestRealm);
requestServerUrl = configData.getServerUrl();

return new RequestContext(configData, token);
}
Expand Down Expand Up @@ -198,6 +203,11 @@ public void run() {

protected final HeadersBodyStatus executeRequest(String method, String url, String token,
String body, String contentType) throws IOException {
if (requestServerUrl == null) {
throw new IllegalStateException("prepareRequest() must be called before executeRequest()");
}
verifyTargetsServer(requestServerUrl, url);

Headers headers = new Headers();
if (token != null) {
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
Expand All @@ -210,7 +220,15 @@ protected final HeadersBodyStatus executeRequest(String method, String url, Stri
bodyStream = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
}

HeadersBodyStatus response = HttpUtil.doRequest(method, url, new HeadersBody(headers, bodyStream), true);
// Redirects are not followed: the HTTP client would forward the Authorization header to the redirect target.
HeadersBodyStatus response = HttpUtil.doRequest(method, url, new HeadersBody(headers, bodyStream), true, false);
int status = response.getStatusCode();
if (status >= 300 && status < 400) {
Header location = response.getHeaders().get(HttpHeaders.LOCATION);
closeQuietly(response.getBody());
throw new RuntimeException("Request was unsuccessful as the server responded with a redirect to "
+ (location != null ? location.getValue() : "UNKNOWN") + " - please check that your server URL is correct.");
}
response.checkSuccess();
return response;
}
Expand All @@ -232,6 +250,111 @@ protected final String buildUrl(ConfigData configData, String body) {
return baseUrl + buildQueryString();
}

/**
* Ensures that a request URL built from a (possibly cached or externally supplied) descriptor still
* points at the configured server before any credentials are attached to it. The descriptor path is
* appended to the server URL as a string, so a path such as {@code @evil.example/...} or
* {@code .evil.example/...} would otherwise change the host the bearer token is sent to.
*/
static void verifyTargetsServer(String serverUrl, String requestUrl) {
String base = serverUrl;
while (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}

boolean valid = requestUrl.startsWith(base + "/");
if (valid) {
try {
URI server = new URI(serverUrl);
URI target = new URI(requestUrl);
String serverPath = server.getRawPath() == null ? "" : server.getRawPath();
while (serverPath.endsWith("/")) {
serverPath = serverPath.substring(0, serverPath.length() - 1);
}
valid = server.getRawAuthority() != null
&& server.getRawAuthority().equals(target.getRawAuthority())
&& target.getRawPath() != null
&& !containsDotSegment(target.getRawPath())
&& target.getRawPath().startsWith(serverPath + "/");
} catch (URISyntaxException e) {
valid = false;
}
}

if (!valid) {
throw new IllegalArgumentException("Refusing to send request to " + requestUrl
+ " because it is outside the configured server " + serverUrl
+ ". The cached command descriptor may be invalid; refresh it with 'config openapi'.");
}
}

private static final int MAX_DECODE_PASSES = 10;

/**
* Returns true if any path segment could be read as {@code .} or {@code ..} by the server or a proxy in
* front of it. Each segment is percent-decoded repeatedly (catching {@code %2e} and {@code %252e}),
* up to a fixed number of passes, so that the work stays linear in the path length; a segment that is still
* changing after the last pass is treated as a dot segment.
* split on any decoded {@code /} or {@code \}, and cut at {@code ;} path parameters. Control characters
* and whitespace are ignored. Admin API paths never contain such segments, so they are rejected rather
* than resolved.
*/
static boolean containsDotSegment(String rawPath) {
for (String segment : rawPath.split("/", -1)) {
String decoded = segment;
int passes = 0;
while (true) {
String next = percentDecode(decoded);
if (next.equals(decoded)) {
break;
}
Comment thread
Copilot marked this conversation as resolved.
Resolved
if (++passes > MAX_DECODE_PASSES) {
// still changing after the limit: fail closed rather than check a partially decoded path
return true;
}
decoded = next;
}
for (String part : decoded.split("[/\\\\]", -1)) {
int semicolon = part.indexOf(';');
String name = (semicolon >= 0 ? part.substring(0, semicolon) : part)
.replaceAll("[\\p{Cntrl}\\s]", "");
if (name.equals(".") || name.equals("..")) {
return true;
}
}
}
return false;
}

private static void closeQuietly(InputStream body) {
if (body == null) {
return;
}
try {
body.close();
} catch (IOException ignored) {
// the request has already failed; nothing more to release
}
}

private static String percentDecode(String value) {
StringBuilder out = new StringBuilder(value.length());
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '%' && i + 2 < value.length()) {
int hi = Character.digit(value.charAt(i + 1), 16);
int lo = Character.digit(value.charAt(i + 2), 16);
if (hi >= 0 && lo >= 0) {
out.append((char) (hi * 16 + lo));
i += 2;
continue;
}
}
out.append(c);
}
return out.toString();
}

private String buildQueryString() {
List<OptionDescriptor> options = descriptor.getOptions();
if (options == null || options.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
Expand Down Expand Up @@ -126,6 +127,11 @@ public static HeadersBodyStatus doRequest(String type, String url, HeadersBody r
}

public static HeadersBodyStatus doRequest(String type, String url, HeadersBody request, boolean allowJakartaValidation) throws IOException {
return doRequest(type, url, request, allowJakartaValidation, true);
}

public static HeadersBodyStatus doRequest(String type, String url, HeadersBody request, boolean allowJakartaValidation,
boolean followRedirects) throws IOException {
HttpRequestBase req;
switch (type) {
case "get":
Expand Down Expand Up @@ -153,6 +159,9 @@ public static HeadersBodyStatus doRequest(String type, String url, HeadersBody r
throw new RuntimeException("Method not supported: " + type);
}
addHeaders(req, request.getHeaders());
if (!followRedirects) {
req.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
}

if (request.getBody() != null) {
if (req instanceof HttpEntityEnclosingRequestBase == false) {
Expand Down
Loading
0