From 4ead6eee359a435563c35b39c2006705536c4fd5 Mon Sep 17 00:00:00 2001 From: Yasir Alnuwasir <68956108+yasser-rafid@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:12:27 +0300 Subject: [PATCH 1/4] Keep Admin CLI v2 requests and their bearer token on the configured server The v2 Admin CLI appends the command descriptor's path to the configured server URL. A descriptor fetched from a separate OpenAPI endpoint or read from the cache could therefore change the host the admin token is sent to, for example with a path starting with "@other.host/" or ".other.host/". - Check the final request URL in executeRequest, before the token is attached: it must start with the configured server URL, keep the same authority and stay under the server's context path once dot segments (including %2e and ;-parameters) are resolved. - Do not follow redirects for v2 requests, since the HTTP client copies the Authorization header to the redirect target; report them instead. - Store cached descriptors per server, so servers that report the same version no longer share one descriptor file. Closes #55552 Signed-off-by: Yasir Alnuwasir <68956108+yasser-rafid@users.noreply.github.com> --- .../admin/cli/v2/KcAdmV2DescriptorCache.java | 36 ++- .../admin/cli/v2/KcAdmV2RequestExecutor.java | 72 ++++- .../keycloak/client/cli/util/HttpUtil.java | 9 + .../v2/KcAdmV2DescriptorCacheTest.java | 165 ++++++++++-- .../v2/KcAdmV2RequestTargetCliTest.java | 245 ++++++++++++++++++ .../cli/v2/KcAdmV2RequestTargetTest.java | 163 ++++++++++++ .../client/cli/util/HttpUtilRedirectTest.java | 166 ++++++++++++ 7 files changed, 816 insertions(+), 40 deletions(-) create mode 100644 integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2RequestTargetCliTest.java create mode 100644 integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java create mode 100644 integration/client-cli/admin-cli/src/test/java/org/keycloak/client/cli/util/HttpUtilRedirectTest.java diff --git a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2DescriptorCache.java b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2DescriptorCache.java index e72fbc960f5f..f3e26ca88d86 100644 --- a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2DescriptorCache.java +++ b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2DescriptorCache.java @@ -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; @@ -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; } @@ -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); 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) { diff --git a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java index d0e54facefc8..0e9003d46c49 100644 --- a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java +++ b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java @@ -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; @@ -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; @@ -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(); @@ -147,6 +151,7 @@ protected final RequestContext prepareRequest() { requestRealm = DEFAULT_REALM; } configData.setRealm(requestRealm); + requestServerUrl = configData.getServerUrl(); return new RequestContext(configData, token); } @@ -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); @@ -210,7 +220,14 @@ 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); + 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; } @@ -232,6 +249,59 @@ 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 + && resolveDotSegments(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'."); + } + } + + /** + * Resolves dot segments the way a server or proxy may see them: percent-encoded dots ({@code %2e}) are + * decoded and path parameters ({@code ;...}) are ignored before {@code .} and {@code ..} are removed. + */ + private static String resolveDotSegments(String rawPath) { + String[] segments = rawPath.split("/", -1); + for (int i = 0; i < segments.length; i++) { + int semicolon = segments[i].indexOf(';'); + String name = (semicolon >= 0 ? segments[i].substring(0, semicolon) : segments[i]).replaceAll("(?i)%2e", "."); + if (name.equals(".") || name.equals("..")) { + segments[i] = name; + } + } + return URI.create(String.join("/", segments)).normalize().getRawPath(); + } + private String buildQueryString() { List options = descriptor.getOptions(); if (options == null || options.isEmpty()) { diff --git a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/util/HttpUtil.java b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/util/HttpUtil.java index c0958f641e79..8cf8093decf0 100644 --- a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/util/HttpUtil.java +++ b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/util/HttpUtil.java @@ -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; @@ -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": @@ -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) { diff --git a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2DescriptorCacheTest.java b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2DescriptorCacheTest.java index b27ee1801d13..105a89f1cc73 100644 --- a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2DescriptorCacheTest.java +++ b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2DescriptorCacheTest.java @@ -20,9 +20,9 @@ import static org.keycloak.client.admin.cli.v2.KcAdmV2DescriptorCache.DESCRIPTOR_PREFIX; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; public class KcAdmV2DescriptorCacheTest { @@ -66,22 +66,19 @@ public void saveAndLoadRoundTrip() { } @Test - public void twoServersWithSameVersionShareOneDescriptorFile() { - KcAdmV2CommandDescriptor descriptor = descriptorWithVersion("26.0.0"); - - cache.save("http://server-a:8080", descriptor); - cache.save("http://server-b:8080", descriptor); - - KcAdmV2CommandDescriptor loadedA = cache.loadForServer("http://server-a:8080"); - KcAdmV2CommandDescriptor loadedB = cache.loadForServer("http://server-b:8080"); - assertNotNull(loadedA); - assertNotNull(loadedB); - assertEquals("26.0.0", loadedA.getVersion()); - assertEquals("26.0.0", loadedB.getVersion()); - - long descriptorFileCount = countDescriptorFiles(); - assertEquals("two servers of same version should share one descriptor file", - 1, descriptorFileCount); + public void twoServersWithSameVersionUseSeparateDescriptorFiles() { + KcAdmV2CommandDescriptor descriptorA = descriptorWithVersion("26.0.0"); + KcAdmV2CommandDescriptor descriptorB = descriptorWithVersion("26.0.0"); + descriptorB.getResources().get(0).getCommands().get(0).setPath("/other/{realmName}/clients"); + + cache.save("http://server-a:8080", descriptorA); + cache.save("http://server-b:8080", descriptorB); + + assertEquals("servers of the same version must not share a descriptor file", 2, countDescriptorFiles()); + assertEquals("/admin/api/{realmName}/clients/{version}", + cache.loadForServer("http://server-a:8080").getResources().get(0).getCommands().get(0).getPath()); + assertEquals("/other/{realmName}/clients", + cache.loadForServer("http://server-b:8080").getResources().get(0).getCommands().get(0).getPath()); } @Test @@ -107,26 +104,36 @@ public void saveUpdatesVersionWhenServerUpgraded() { } @Test - public void saveKeepsOldDescriptorIfReferencedByOtherServer() { + public void upgradingOneServerKeepsOtherServersDescriptor() { cache.save("http://server-a:8080", descriptorWithVersion("26.0.0")); cache.save("http://server-b:8080", descriptorWithVersion("26.0.0")); - assertEquals(1, countDescriptorFiles()); + assertEquals(2, countDescriptorFiles()); cache.save("http://server-a:8080", descriptorWithVersion("27.0.0")); - assertEquals("old descriptor kept because server-b still uses it", - 2, countDescriptorFiles()); + assertEquals("server-a's old descriptor removed, server-b's kept", 2, countDescriptorFiles()); + assertEquals("27.0.0", cache.loadForServer("http://server-a:8080").getVersion()); + assertEquals("26.0.0", cache.loadForServer("http://server-b:8080").getVersion()); + } + + @Test + public void descriptorIsNotLoadedForAnotherServer() { + cache.save("http://server-a:8080", descriptorWithVersion("26.0.0")); + + assertNull(cache.loadForServer("http://server-b:8080")); } @Test public void versionIsSanitizedInFilename() { String maliciousVersion = "../../etc/passwd"; - Path sanitizedFile = tempDir.resolve(DESCRIPTOR_PREFIX + "______etc_passwd.json"); - - assertFalse("sanitized file should not exist before save", Files.exists(sanitizedFile)); cache.save("http://localhost:8080", descriptorWithVersion(maliciousVersion)); - assertTrue("descriptor should be saved with sanitized filename", Files.exists(sanitizedFile)); + try (var files = Files.list(tempDir)) { + assertTrue("descriptor should be saved with sanitized filename inside the cache dir", + files.anyMatch(p -> p.getFileName().toString().startsWith(DESCRIPTOR_PREFIX + "______etc_passwd-"))); + } catch (IOException e) { + throw new RuntimeException(e); + } assertNotNull(cache.loadForServer("http://localhost:8080")); } @@ -148,6 +155,104 @@ public void saveCreatesDirectoryIfNeeded() { assertNotNull(nestedCache.loadForServer("http://localhost:8080")); } + @Test + public void descriptorFileNameIsVersionFollowedByServerHash() { + cache.save("http://localhost:8080", descriptorWithVersion("26.0.0")); + + assertEquals(List.of(), descriptorFileNames().stream() + .filter(n -> !n.matches(DESCRIPTOR_PREFIX + "26_0_0-[0-9a-f]{32}\\.json")).toList()); + assertEquals(1, countDescriptorFiles()); + } + + @Test + public void upgradeBetweenVersionsThatSanitizeToTheSameNameKeepsLiveDescriptor() { + cache.save("http://localhost:8080", descriptorWithVersion("26.0")); + + cache.save("http://localhost:8080", descriptorWithVersion("26_0")); + + KcAdmV2CommandDescriptor loaded = cache.loadForServer("http://localhost:8080"); + assertNotNull("the old version's cleanup must not delete the file the new version was just written to", loaded); + assertEquals("26_0", loaded.getVersion()); + assertEquals(1, countDescriptorFiles()); + } + + @Test + public void resavingTheSameVersionKeepsDescriptor() { + cache.save("http://localhost:8080", descriptorWithVersion("26.0.0")); + + cache.save("http://localhost:8080", descriptorWithVersion("26.0.0")); + + assertNotNull(cache.loadForServer("http://localhost:8080")); + assertEquals(1, countDescriptorFiles()); + } + + @Test + public void serverUrlsDifferingOnlyByTrailingSlashDoNotDeleteEachOthersDescriptor() { + cache.save("http://localhost:8080", descriptorWithVersion("26.0.0")); + cache.save("http://localhost:8080/", descriptorWithVersion("26.0.0")); + + cache.save("http://localhost:8080", descriptorWithVersion("27.0.0")); + + assertEquals("27.0.0", cache.loadForServer("http://localhost:8080").getVersion()); + assertEquals("26.0.0", cache.loadForServer("http://localhost:8080/").getVersion()); + } + + @Test + public void upgradingOneServerKeepsOtherServerOnTheOldVersionLoadable() { + cache.save("http://server-a:8080", descriptorWithVersion("26.0.0")); + cache.save("http://server-b:8080", descriptorWithVersion("26.0.0")); + + cache.save("http://server-a:8080", descriptorWithVersion("27.0.0")); + cache.save("http://server-a:8080", descriptorWithVersion("28.0.0")); + + assertEquals("26.0.0", cache.loadForServer("http://server-b:8080").getVersion()); + assertEquals("28.0.0", cache.loadForServer("http://server-a:8080").getVersion()); + assertEquals(2, countDescriptorFiles()); + } + + @Test + public void descriptorWrittenByPreviousReleaseIsTreatedAsCacheMiss() throws IOException { + // Before descriptors were keyed by server, the file was named after the version only. + Files.writeString(tempDir.resolve(KcAdmV2DescriptorCache.REGISTRY_FILENAME), + "{\"servers\":{\"http://localhost:8080\":{\"version\":\"26.0.0\"}}}"); + Files.writeString(tempDir.resolve(DESCRIPTOR_PREFIX + "26_0_0.json"), "{\"version\":\"26.0.0\",\"resources\":[]}"); + + assertNull(cache.loadForServer("http://localhost:8080")); + } + + @Test + public void registryFromPreviousReleaseAcceptsNewSave() throws IOException { + Files.writeString(tempDir.resolve(KcAdmV2DescriptorCache.REGISTRY_FILENAME), + "{\"servers\":{\"http://localhost:8080\":{\"version\":\"26.0.0\"}}}"); + + cache.save("http://localhost:8080", descriptorWithVersion("27.0.0")); + + assertEquals("27.0.0", cache.loadForServer("http://localhost:8080").getVersion()); + } + + @Test + public void corruptRegistryIsTreatedAsEmptyAndRecoveredBySave() throws IOException { + Files.writeString(tempDir.resolve(KcAdmV2DescriptorCache.REGISTRY_FILENAME), "{not json"); + + assertNull(cache.loadForServer("http://localhost:8080")); + + cache.save("http://localhost:8080", descriptorWithVersion("26.0.0")); + assertEquals("26.0.0", cache.loadForServer("http://localhost:8080").getVersion()); + } + + @Test + public void corruptDescriptorFileIsTreatedAsCacheMiss() throws IOException { + cache.save("http://localhost:8080", descriptorWithVersion("26.0.0")); + Files.writeString(tempDir.resolve(descriptorFileNames().get(0)), "{not json"); + + assertNull(cache.loadForServer("http://localhost:8080")); + } + + @Test + public void blankVersionIsRefused() { + assertThrows(IllegalArgumentException.class, () -> cache.save("http://localhost:8080", descriptorWithVersion(" "))); + } + private KcAdmV2CommandDescriptor descriptorWithVersion(String version) { CommandDescriptor cmd = new CommandDescriptor(); cmd.setName("list"); @@ -167,6 +272,16 @@ private KcAdmV2CommandDescriptor descriptorWithVersion(String version) { return descriptor; } + private List descriptorFileNames() { + try (var files = Files.list(tempDir)) { + return files.map(p -> p.getFileName().toString()) + .filter(n -> n.startsWith(DESCRIPTOR_PREFIX)) + .toList(); + } catch (IOException e) { + throw new RuntimeException("Failed to list descriptor files", e); + } + } + private long countDescriptorFiles() { try (var files = Files.list(tempDir)) { return files diff --git a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2RequestTargetCliTest.java b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2RequestTargetCliTest.java new file mode 100644 index 000000000000..b9aa2e2f95f1 --- /dev/null +++ b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2RequestTargetCliTest.java @@ -0,0 +1,245 @@ +package org.keycloak.client.admin.cli.commands.v2; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.keycloak.client.admin.cli.KcAdmMain; +import org.keycloak.client.admin.cli.v2.KcAdmV2Cmd; +import org.keycloak.client.admin.cli.v2.KcAdmV2CommandDescriptor; +import org.keycloak.client.admin.cli.v2.KcAdmV2CommandDescriptor.CommandDescriptor; +import org.keycloak.client.admin.cli.v2.KcAdmV2CommandDescriptor.OptionDescriptor; +import org.keycloak.client.admin.cli.v2.KcAdmV2CommandDescriptor.ResourceDescriptor; +import org.keycloak.client.admin.cli.v2.KcAdmV2DescriptorCache; +import org.keycloak.client.cli.common.Globals; +import org.keycloak.client.cli.config.ConfigData; +import org.keycloak.client.cli.config.FileConfigHandler; +import org.keycloak.client.cli.util.ConfigUtil; +import org.keycloak.client.cli.util.HttpUtil; +import org.keycloak.util.JsonSerialization; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.apache.http.HttpHeaders; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import picocli.CommandLine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +/** + * Runs v2 commands end to end against loopback servers, so that the request-target check and the + * redirect refusal are exercised through the real command path rather than only through the helpers. + * The "keycloak" server listens on 127.0.0.1 and the "elsewhere" server on localhost, so the two are + * different hosts as far as the HTTP client is concerned. + */ +public class KcAdmV2RequestTargetCliTest { + + private static final String TOKEN = "secret-token"; + private static final String CONFIG_FILE_NAME = Path.of(KcAdmMain.DEFAULT_CONFIG_FILE_PATH).getFileName().toString(); + + private Path cacheDir; + private HttpServer keycloak; + private HttpServer elsewhere; + private final List keycloakRequests = new CopyOnWriteArrayList<>(); + private final List elsewhereRequests = new CopyOnWriteArrayList<>(); + private volatile int keycloakStatus = 200; + private volatile String keycloakLocation; + private String serverUrl; + + @Before + public void setUp() throws IOException { + HttpUtil.clearHttpClient(); + ConfigUtil.setHandler(null); + FileConfigHandler.setConfigFile(null); + cacheDir = Files.createTempDirectory("kcadm-target-cli-test"); + InetAddress loopback = InetAddress.getLoopbackAddress(); + + elsewhere = HttpServer.create(new InetSocketAddress(loopback, 0), 0); + elsewhere.createContext("/", exchange -> record(exchange, elsewhereRequests, 200, null)); + elsewhere.start(); + + keycloak = HttpServer.create(new InetSocketAddress(loopback, 0), 0); + keycloak.createContext("/", exchange -> record(exchange, keycloakRequests, keycloakStatus, keycloakLocation)); + keycloak.start(); + + serverUrl = "http://127.0.0.1:" + keycloak.getAddress().getPort(); + } + + @After + public void tearDown() throws IOException { + keycloak.stop(0); + elsewhere.stop(0); + HttpUtil.clearHttpClient(); + ConfigUtil.setHandler(null); + FileConfigHandler.setConfigFile(null); + try (var paths = Files.walk(cacheDir)) { + paths.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); + } + } + + @Test + public void requestOnConfiguredServerCarriesToken() throws IOException { + cacheDescriptor("/admin/api/{realmName}/widgets/{version}"); + + int exitCode = run(serverUrl, "widget", "list"); + + assertEquals(0, exitCode); + assertEquals(List.of("GET /admin/api/master/widgets/v2 Bearer " + TOKEN), keycloakRequests); + } + + @Test + public void serverUrlWithTrailingSlashIsStillAccepted() throws IOException { + cacheDescriptor(serverUrl + "/", "/admin/api/{realmName}/widgets/{version}"); + + int exitCode = run(serverUrl + "/", "widget", "list"); + + assertEquals(0, exitCode); + assertEquals(1, keycloakRequests.size()); + } + + @Test + public void descriptorPathInjectingUserInfoIsRefusedBeforeAnyRequest() throws IOException { + // Appended to the server URL as a string, "@localhost:" turns "127.0.0.1:" into user-info + // and sends the request, with the bearer token, to the other host. + cacheDescriptor("@localhost:" + elsewhere.getAddress().getPort() + "/admin/api/{realmName}/widgets/{version}"); + StringWriter err = new StringWriter(); + + int exitCode = run(serverUrl, err, "widget", "list"); + + assertNotEquals(0, exitCode); + assertTrue("error should explain the refusal but was: " + err, err.toString().contains("outside the configured server")); + assertEquals(List.of(), elsewhereRequests); + assertEquals(List.of(), keycloakRequests); + } + + @Test + public void getRedirectToAnotherHostIsNotFollowed() throws IOException { + cacheDescriptor("/admin/api/{realmName}/widgets/{version}"); + String location = "http://localhost:" + elsewhere.getAddress().getPort() + "/stolen"; + keycloakStatus = 302; + keycloakLocation = location; + StringWriter err = new StringWriter(); + + int exitCode = run(serverUrl, err, "widget", "list"); + + assertNotEquals(0, exitCode); + assertTrue("error should name the redirect target but was: " + err, err.toString().contains(location)); + assertEquals(List.of(), elsewhereRequests); + } + + @Test + public void postSeeOtherRedirectIsNotFollowed() throws IOException { + // The client's default strategy does not follow redirects for a POST, so this only fails if that + // changes; the GET case above is the one that leaked the token before the fix. + cacheDescriptor("/admin/api/{realmName}/widgets/{version}"); + keycloakStatus = 303; + keycloakLocation = "http://localhost:" + elsewhere.getAddress().getPort() + "/stolen"; + + int exitCode = run(serverUrl, "widget", "create", "--widget-name", "w1"); + + assertNotEquals(0, exitCode); + assertEquals(1, keycloakRequests.size()); + assertTrue(keycloakRequests.get(0).startsWith("POST ")); + assertEquals(List.of(), elsewhereRequests); + } + + @Test + public void redirectWithinTheSameServerIsAlsoReportedRatherThanFollowed() throws IOException { + cacheDescriptor("/admin/api/{realmName}/widgets/{version}"); + keycloakStatus = 301; + keycloakLocation = serverUrl + "/moved"; + StringWriter err = new StringWriter(); + + int exitCode = run(serverUrl, err, "widget", "list"); + + assertNotEquals(0, exitCode); + assertTrue("error should name the redirect target but was: " + err, err.toString().contains(serverUrl + "/moved")); + assertEquals(1, keycloakRequests.size()); + } + + private int run(String server, String... command) { + return run(server, new StringWriter(), command); + } + + private int run(String server, StringWriter err, String... command) { + CommandLine cli = Globals.createCommandLine(new KcAdmV2Cmd(cacheDir), KcAdmMain.CMD, new PrintWriter(err, true)); + cli.setOut(new PrintWriter(new StringWriter())); + cli.setErr(new PrintWriter(err, true)); + String[] connection = {"--config", cacheDir.resolve(CONFIG_FILE_NAME).toString(), "--server", server, "--token", TOKEN}; + String[] args = new String[connection.length + command.length]; + System.arraycopy(connection, 0, args, 0, connection.length); + System.arraycopy(command, 0, args, connection.length, command.length); + return cli.execute(args); + } + + private void cacheDescriptor(String path) throws IOException { + cacheDescriptor(serverUrl, path); + } + + private void cacheDescriptor(String configuredServerUrl, String path) throws IOException { + ConfigData config = new ConfigData(); + config.setServerUrl(configuredServerUrl); + Files.writeString(cacheDir.resolve(CONFIG_FILE_NAME), JsonSerialization.writeValueAsPrettyString(config)); + new KcAdmV2DescriptorCache(cacheDir).save(configuredServerUrl, widgetDescriptor(path)); + } + + private static void record(HttpExchange exchange, List requests, int status, String location) throws IOException { + exchange.getRequestBody().readAllBytes(); + requests.add(exchange.getRequestMethod() + " " + exchange.getRequestURI().getRawPath() + " " + + exchange.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION)); + if (location != null) { + exchange.getResponseHeaders().add(HttpHeaders.LOCATION, location); + } + byte[] body = status == 200 ? "[]".getBytes() : new byte[0]; + exchange.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json"); + exchange.sendResponseHeaders(status, body.length == 0 ? -1 : body.length); + if (body.length > 0) { + exchange.getResponseBody().write(body); + } + exchange.close(); + } + + private static KcAdmV2CommandDescriptor widgetDescriptor(String path) { + CommandDescriptor listCmd = new CommandDescriptor(); + listCmd.setName("list"); + listCmd.setResourceName("widget"); + listCmd.setHttpMethod("GET"); + listCmd.setPath(path); + listCmd.setDescription("List widgets"); + listCmd.setOptions(List.of()); + + OptionDescriptor nameOption = new OptionDescriptor(); + nameOption.setName("widget-name"); + nameOption.setFieldName("widgetName"); + nameOption.setType(OptionDescriptor.TYPE_STRING); + nameOption.setDescription("Name of the widget"); + + CommandDescriptor createCmd = new CommandDescriptor(); + createCmd.setName("create"); + createCmd.setResourceName("widget"); + createCmd.setHttpMethod("POST"); + createCmd.setPath(path); + createCmd.setDescription("Create a widget"); + createCmd.setOptions(List.of(nameOption)); + + ResourceDescriptor resource = new ResourceDescriptor(); + resource.setName("widget"); + resource.setCommands(List.of(listCmd, createCmd)); + + KcAdmV2CommandDescriptor descriptor = new KcAdmV2CommandDescriptor(); + descriptor.setVersion("99.0.0"); + descriptor.setResources(List.of(resource)); + return descriptor; + } +} diff --git a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java new file mode 100644 index 000000000000..94bea339349c --- /dev/null +++ b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java @@ -0,0 +1,163 @@ +package org.keycloak.client.admin.cli.v2; + +import org.junit.Test; + +import static org.junit.Assert.assertThrows; + +public class KcAdmV2RequestTargetTest { + + private static void allowed(String server, String url) { + KcAdmV2RequestExecutor.verifyTargetsServer(server, url); + } + + private static void rejected(String server, String url) { + assertThrows(IllegalArgumentException.class, () -> KcAdmV2RequestExecutor.verifyTargetsServer(server, url)); + } + + @Test + public void acceptsRequestsOnConfiguredServer() { + allowed("http://localhost:8080", "http://localhost:8080/admin/api/master/clients/v2"); + allowed("https://kc.example.com", "https://kc.example.com/admin/api/master/clients/v2?first=0&max=10"); + allowed("https://kc.example.com/", "https://kc.example.com//admin/api/master/clients/v2"); + allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/master/clients/v2"); + allowed("https://kc.example.com:8443", "https://kc.example.com:8443/admin/api/master/clients/v2"); + allowed("http://[::1]:8080", "http://[::1]:8080/admin/api/master/clients/v2"); + } + + @Test + public void acceptsHostsThatJavaUriTreatsAsRegistryBased() { + allowed("http://my_keycloak:8080", "http://my_keycloak:8080/admin/api/master/clients/v2"); + allowed("http://keycloak_1", "http://keycloak_1/admin/api/master/clients/v2"); + } + + @Test + public void rejectsPathThatInjectsUserInfo() { + rejected("https://kc.example.com", "https://kc.example.com@evil.example/admin/api/master/clients/v2"); + } + + @Test + public void rejectsPathThatExtendsHost() { + rejected("https://kc.example.com", "https://kc.example.com.evil.example/admin/api/master/clients/v2"); + } + + @Test + public void rejectsPathThatChangesPort() { + rejected("http://localhost:8080", "http://localhost:80801/admin/api/master/clients/v2"); + rejected("http://localhost:8080", "http://localhost:8080:9090/admin"); + } + + @Test + public void rejectsPathOutsideServerContextPath() { + rejected("https://kc.example.com/auth", "https://kc.example.com/authx/admin/api/master/clients/v2"); + rejected("https://kc.example.com", "https://kc.example.com"); + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/../admin/api/master/clients/v2"); + } + + @Test + public void rejectsRegistryBasedHostChange() { + rejected("http://my_keycloak:8080", "http://my_keycloak:8080@evil.example/admin"); + rejected("http://my_keycloak", "http://my_keycloak.evil.example/admin"); + } + + @Test + public void rejectsDifferentScheme() { + rejected("https://kc.example.com", "http://kc.example.com/admin/api/master/clients/v2"); + } + + @Test + public void rejectsMalformedUrl() { + rejected("https://kc.example.com", "https://kc.example.com/admin/{bad}"); + } + + @Test + public void acceptsQueryStringContainingAtSignAndSlashes() { + allowed("https://kc.example.com", "https://kc.example.com/admin/api/master/users/v2?email=a@evil.example/x"); + } + + @Test + public void acceptsFragmentContainingAtSign() { + allowed("https://kc.example.com", "https://kc.example.com/admin/api/master/clients/v2#@evil.example"); + } + + @Test + public void acceptsPercentEncodedCharactersInPath() { + allowed("https://kc.example.com", "https://kc.example.com/admin/api/my%20realm/clients/v2/a%2Fb%40c"); + } + + @Test + public void acceptsServerUrlWithSeveralTrailingSlashes() { + allowed("http://localhost:8080//", "http://localhost:8080///admin/api/master/clients/v2"); + } + + @Test + public void acceptsContextPathWithTrailingSlash() { + allowed("https://kc.example.com/auth/", "https://kc.example.com/auth//admin/api/master/clients/v2"); + } + + @Test + public void acceptsRootPathOnServerWithoutContextPath() { + allowed("http://localhost:8080", "http://localhost:8080/"); + } + + @Test + public void acceptsDotSegmentThatStaysInsideContextPath() { + allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/../api/master/clients/v2"); + } + + @Test + public void rejectsQueryStringImmediatelyAfterAuthority() { + rejected("https://kc.example.com", "https://kc.example.com?@evil.example/admin"); + } + + @Test + public void rejectsFragmentImmediatelyAfterAuthority() { + rejected("https://kc.example.com", "https://kc.example.com#@evil.example/admin"); + } + + @Test + public void rejectsBackslashThatBrowsersTreatAsPathSeparator() { + rejected("https://kc.example.com", "https://kc.example.com/\\@evil.example/admin"); + } + + @Test + public void rejectsIpv6PortExtension() { + rejected("http://[::1]:8080", "http://[::1]:80801/admin/api/master/clients/v2"); + } + + @Test + public void rejectsIpv6UserInfoInjection() { + rejected("http://[::1]:8080", "http://[::1]:8080@evil.example/admin/api/master/clients/v2"); + } + + @Test + public void rejectsSchemeThatDiffersOnlyInCase() { + // Fail closed: the request URL is always built from the server URL, so a mismatch means something rewrote it. + rejected("https://kc.example.com", "HTTPS://kc.example.com/admin/api/master/clients/v2"); + } + + @Test + public void rejectsExplicitDefaultPortThatTheServerUrlOmits() { + rejected("https://kc.example.com", "https://kc.example.com:443/admin/api/master/clients/v2"); + } + + @Test + public void rejectsDotSegmentsThatClimbAboveContextPathAfterSeveralLevels() { + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/admin/../../other/secret"); + } + + @Test + public void rejectsSingleDotThenDotDotOutOfContextPath() { + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/./../other"); + } + + // "%2e" is equivalent to "." (RFC 3986 section 6.2.2.2) and servlet containers ignore ";" path parameters, + // so both must be resolved before checking that the request stays under the server's context path. + @Test + public void rejectsPercentEncodedDotSegmentsOutOfContextPath() { + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/%2e%2e/other/secret"); + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/%2E./other/secret"); + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/..;/other/secret"); + allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/%2e%2e/admin/api/master/clients/v2"); + } + +} diff --git a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/cli/util/HttpUtilRedirectTest.java b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/cli/util/HttpUtilRedirectTest.java new file mode 100644 index 000000000000..184f48698d0c --- /dev/null +++ b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/cli/util/HttpUtilRedirectTest.java @@ -0,0 +1,166 @@ +package org.keycloak.client.cli.util; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicReference; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.apache.http.HttpHeaders; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; + +public class HttpUtilRedirectTest { + + private HttpServer origin; + private HttpServer other; + private final AtomicReference authorizationSeenByOther = new AtomicReference<>(); + private volatile boolean otherWasCalled; + + @Before + public void setUp() throws IOException { + HttpUtil.clearHttpClient(); + InetAddress loopback = InetAddress.getLoopbackAddress(); + + other = HttpServer.create(new InetSocketAddress(loopback, 0), 0); + other.createContext("/", exchange -> { + otherWasCalled = true; + authorizationSeenByOther.set(exchange.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION)); + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + other.start(); + + origin = HttpServer.create(new InetSocketAddress(loopback, 0), 0); + origin.createContext("/", exchange -> { + exchange.getResponseHeaders().add(HttpHeaders.LOCATION, + "http://localhost:" + other.getAddress().getPort() + "/stolen"); + exchange.sendResponseHeaders(302, -1); + exchange.close(); + }); + origin.createContext("/see-other", exchange -> redirectToOther(exchange, 303)); + origin.createContext("/temporary", exchange -> redirectToOther(exchange, 307)); + origin.createContext("/permanent", exchange -> redirectToOther(exchange, 308)); + origin.createContext("/same-host", exchange -> { + exchange.getResponseHeaders().add(HttpHeaders.LOCATION, originUrl("/final")); + exchange.sendResponseHeaders(302, -1); + exchange.close(); + }); + origin.createContext("/final", exchange -> { + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + origin.start(); + } + + @After + public void tearDown() { + origin.stop(0); + other.stop(0); + HttpUtil.clearHttpClient(); + } + + @Test + public void redirectIsNotFollowedWhenDisabled() throws IOException { + Headers headers = new Headers(); + headers.add(HttpHeaders.AUTHORIZATION, "Bearer secret-token"); + String url = "http://127.0.0.1:" + origin.getAddress().getPort() + "/admin"; + + HeadersBodyStatus response = HttpUtil.doRequest("get", url, new HeadersBody(headers), true, false); + + assertEquals(302, response.getStatusCode()); + assertFalse(otherWasCalled); + assertNull(authorizationSeenByOther.get()); + } + + @Test + public void postSeeOtherIsNotFollowedWhenDisabled() throws IOException { + // The client's default strategy only follows redirects for GET and HEAD, so this guards against a later + // switch to a lax strategy or another client rather than against today's behaviour. + HeadersBodyStatus response = HttpUtil.doRequest("post", originUrl("/see-other"), withTokenAndBody(), true, false); + + assertEquals(303, response.getStatusCode()); + assertFalse(otherWasCalled); + } + + @Test + public void putTemporaryRedirectIsNotFollowedWhenDisabled() throws IOException { + // Like the POST case, this only fails if the client starts following redirects for unsafe methods. + HeadersBodyStatus response = HttpUtil.doRequest("put", originUrl("/temporary"), withTokenAndBody(), true, false); + + assertEquals(307, response.getStatusCode()); + assertFalse(otherWasCalled); + } + + @Test + public void getTemporaryRedirectIsNotFollowedWhenDisabled() throws IOException { + HeadersBodyStatus response = HttpUtil.doRequest("get", originUrl("/temporary"), new HeadersBody(withToken()), true, false); + + assertEquals(307, response.getStatusCode()); + assertFalse(otherWasCalled); + } + + @Test + public void getPermanentRedirectIsNotFollowedWhenDisabled() throws IOException { + HeadersBodyStatus response = HttpUtil.doRequest("get", originUrl("/permanent"), new HeadersBody(withToken()), true, false); + + assertEquals(308, response.getStatusCode()); + assertFalse(otherWasCalled); + } + + @Test + public void redirectLocationIsReturnedWhenNotFollowed() throws IOException { + HeadersBodyStatus response = HttpUtil.doRequest("get", originUrl("/admin"), new HeadersBody(withToken()), true, false); + + assertEquals("http://localhost:" + other.getAddress().getPort() + "/stolen", + response.getHeaders().get(HttpHeaders.LOCATION).getValue()); + } + + @Test + public void defaultRequestStillFollowsSameHostRedirect() throws IOException { + // The v1 commands rely on the original behaviour, so the four-argument overload must keep following. + HeadersBodyStatus response = HttpUtil.doRequest("get", originUrl("/same-host"), new HeadersBody(new Headers()), true); + + assertEquals(200, response.getStatusCode()); + } + + @Test + public void disablingRedirectsForOneRequestDoesNotAffectTheSharedClient() throws IOException { + HttpUtil.doRequest("get", originUrl("/same-host"), new HeadersBody(new Headers()), true, false); + + HeadersBodyStatus response = HttpUtil.doRequest("get", originUrl("/same-host"), new HeadersBody(new Headers())); + + assertEquals(200, response.getStatusCode()); + } + + private String originUrl(String path) { + return "http://127.0.0.1:" + origin.getAddress().getPort() + path; + } + + private void redirectToOther(HttpExchange exchange, int status) throws IOException { + exchange.getRequestBody().readAllBytes(); + exchange.getResponseHeaders().add(HttpHeaders.LOCATION, "http://localhost:" + other.getAddress().getPort() + "/stolen"); + exchange.sendResponseHeaders(status, -1); + exchange.close(); + } + + private static Headers withToken() { + Headers headers = new Headers(); + headers.add(HttpHeaders.AUTHORIZATION, "Bearer secret-token"); + return headers; + } + + private static HeadersBody withTokenAndBody() { + Headers headers = withToken(); + headers.add(HttpHeaders.CONTENT_TYPE, "application/json"); + return new HeadersBody(headers, new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8))); + } +} From dcfdadb0403a19c8100aa09fb6395fadc46164b8 Mon Sep 17 00:00:00 2001 From: Yasir Alnuwasir <68956108+yasser-rafid@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:22:30 +0300 Subject: [PATCH 2/4] Reject encoded dot segments in Admin CLI v2 request paths Signed-off-by: Yasir Alnuwasir <68956108+yasser-rafid@users.noreply.github.com> --- .../admin/cli/v2/KcAdmV2RequestExecutor.java | 54 +++++++++++++++---- .../cli/v2/KcAdmV2RequestTargetTest.java | 35 ++++++++++-- 2 files changed, 73 insertions(+), 16 deletions(-) diff --git a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java index 0e9003d46c49..c0ec0530fedb 100644 --- a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java +++ b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java @@ -273,7 +273,8 @@ static void verifyTargetsServer(String serverUrl, String requestUrl) { valid = server.getRawAuthority() != null && server.getRawAuthority().equals(target.getRawAuthority()) && target.getRawPath() != null - && resolveDotSegments(target.getRawPath()).startsWith(serverPath + "/"); + && !containsDotSegment(target.getRawPath()) + && target.getRawPath().startsWith(serverPath + "/"); } catch (URISyntaxException e) { valid = false; } @@ -287,19 +288,50 @@ static void verifyTargetsServer(String serverUrl, String requestUrl) { } /** - * Resolves dot segments the way a server or proxy may see them: percent-encoded dots ({@code %2e}) are - * decoded and path parameters ({@code ;...}) are ignored before {@code .} and {@code ..} are removed. + * 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}), + * 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. */ - private static String resolveDotSegments(String rawPath) { - String[] segments = rawPath.split("/", -1); - for (int i = 0; i < segments.length; i++) { - int semicolon = segments[i].indexOf(';'); - String name = (semicolon >= 0 ? segments[i].substring(0, semicolon) : segments[i]).replaceAll("(?i)%2e", "."); - if (name.equals(".") || name.equals("..")) { - segments[i] = name; + static boolean containsDotSegment(String rawPath) { + for (String segment : rawPath.split("/", -1)) { + String decoded = segment; + for (int i = 0; i < 5; i++) { + String next = percentDecode(decoded); + if (next.equals(decoded)) { + break; + } + 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 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 URI.create(String.join("/", segments)).normalize().getRawPath(); + return out.toString(); } private String buildQueryString() { diff --git a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java index 94bea339349c..79e65c9a7f0c 100644 --- a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java +++ b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java @@ -100,8 +100,8 @@ public void acceptsRootPathOnServerWithoutContextPath() { } @Test - public void acceptsDotSegmentThatStaysInsideContextPath() { - allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/../api/master/clients/v2"); + public void rejectsDotSegmentEvenInsideContextPath() { + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/../api/master/clients/v2"); } @Test @@ -151,13 +151,38 @@ public void rejectsSingleDotThenDotDotOutOfContextPath() { } // "%2e" is equivalent to "." (RFC 3986 section 6.2.2.2) and servlet containers ignore ";" path parameters, - // so both must be resolved before checking that the request stays under the server's context path. + // so a server or proxy may resolve these segments. Admin API paths never contain dot segments, so any + // path with one is rejected, even if it would resolve back under the context path. @Test - public void rejectsPercentEncodedDotSegmentsOutOfContextPath() { + public void rejectsPercentEncodedDotSegments() { rejected("https://kc.example.com/auth", "https://kc.example.com/auth/%2e%2e/other/secret"); rejected("https://kc.example.com/auth", "https://kc.example.com/auth/%2E./other/secret"); rejected("https://kc.example.com/auth", "https://kc.example.com/auth/..;/other/secret"); - allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/%2e%2e/admin/api/master/clients/v2"); + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/admin/%2e%2e/admin/api/master/clients/v2"); + } + + // Encoded separators and terminators, matching the variants RedirectUtilsTest covers. + @Test + public void rejectsEncodedSeparatorsAndTerminatorsAroundDotSegments() { + String server = "https://kc.example.com/auth"; + for (String path : new String[] { + "/auth/..%3b/other", "/auth/..%3B/other", "/auth/..%3Bsomething/other", + "/auth/%2e%2e%2fother", "/auth/%2E%2E%2Fother", "/auth/%2F%2E%2E%2Fother", + "/auth/x%2f%2E%2e%2F", "/auth/x%5C%2E.%5c", "/auth/x%5C..", "/auth/x%5C..;/", + "/auth/%2e%2e;param=value/other", + "/auth/..%09/other", "/auth/..%0A/other", "/auth/..%0D/other", "/auth/..%00/other", + "/auth/%252E%252E/other", "/auth/%25252e%25252e/other", + "/auth/.", "/auth/%2e" }) { + rejected(server, "https://kc.example.com" + path); + } + } + + @Test + public void acceptsDotsThatAreNotDotSegments() { + allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/master/clients/v2/my.client"); + allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/master/clients/v2/..."); + allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/master/clients/v2/a..b"); + allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/master/clients/v2/a%2Eb"); } } From 5e6b35ddff2b0c047d1048b83ad047a93341b6ce Mon Sep 17 00:00:00 2001 From: Yasir Alnuwasir <68956108+yasser-rafid@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:28:22 +0300 Subject: [PATCH 3/4] Refactor containsDotSegment to use while loop Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Yasir Alnuwasir <68956108+yasser-rafid@users.noreply.github.com> --- .../keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java index c0ec0530fedb..763d2f2dad00 100644 --- a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java +++ b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java @@ -297,7 +297,7 @@ static void verifyTargetsServer(String serverUrl, String requestUrl) { static boolean containsDotSegment(String rawPath) { for (String segment : rawPath.split("/", -1)) { String decoded = segment; - for (int i = 0; i < 5; i++) { + while (true) { String next = percentDecode(decoded); if (next.equals(decoded)) { break; From 11460ddac1770936a293173219ab4fcb14726100 Mon Sep 17 00:00:00 2001 From: Yasir Alnuwasir <68956108+yasser-rafid@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:38:50 +0300 Subject: [PATCH 4/4] Bound path decoding, close refused redirect bodies, bind test servers to IPv4 Signed-off-by: Yasir Alnuwasir <68956108+yasser-rafid@users.noreply.github.com> --- .../admin/cli/v2/KcAdmV2RequestExecutor.java | 21 +++++++++++++++++++ .../v2/KcAdmV2RequestTargetCliTest.java | 3 ++- .../cli/v2/KcAdmV2RequestTargetTest.java | 13 ++++++++++++ .../client/cli/util/HttpUtilRedirectTest.java | 3 ++- 4 files changed, 38 insertions(+), 2 deletions(-) diff --git a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java index 763d2f2dad00..187516399204 100644 --- a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java +++ b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestExecutor.java @@ -225,6 +225,7 @@ protected final HeadersBodyStatus executeRequest(String method, String url, Stri 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."); } @@ -287,9 +288,13 @@ static void verifyTargetsServer(String serverUrl, String requestUrl) { } } + 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. @@ -297,11 +302,16 @@ static void verifyTargetsServer(String serverUrl, String requestUrl) { 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; } + 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)) { @@ -316,6 +326,17 @@ static boolean containsDotSegment(String rawPath) { 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++) { diff --git a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2RequestTargetCliTest.java b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2RequestTargetCliTest.java index b9aa2e2f95f1..2fdf325c2dce 100644 --- a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2RequestTargetCliTest.java +++ b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/commands/v2/KcAdmV2RequestTargetCliTest.java @@ -63,7 +63,8 @@ public void setUp() throws IOException { ConfigUtil.setHandler(null); FileConfigHandler.setConfigFile(null); cacheDir = Files.createTempDirectory("kcadm-target-cli-test"); - InetAddress loopback = InetAddress.getLoopbackAddress(); + // IPv4 explicitly, to match the 127.0.0.1 request URLs even when the JVM prefers IPv6 + InetAddress loopback = InetAddress.getByName("127.0.0.1"); elsewhere = HttpServer.create(new InetSocketAddress(loopback, 0), 0); elsewhere.createContext("/", exchange -> record(exchange, elsewhereRequests, 200, null)); diff --git a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java index 79e65c9a7f0c..9eb14d98153a 100644 --- a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java +++ b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/admin/cli/v2/KcAdmV2RequestTargetTest.java @@ -177,6 +177,19 @@ public void rejectsEncodedSeparatorsAndTerminatorsAroundDotSegments() { } } + @Test + public void rejectsDeeplyEncodedDotSegments() { + // six levels of encoding, still a ".." segment once fully decoded + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/%25252525252e%25252525252e/other"); + } + + @Test(timeout = 5000) + public void rejectsLongEncodingChainsWithoutQuadraticWork() { + // "%" followed by many "25" pairs and "2e" would take one decoding pass per pair if decoding were unbounded + String segment = "%" + "25".repeat(200_000) + "2e"; + rejected("https://kc.example.com/auth", "https://kc.example.com/auth/" + segment + "/admin/api/master/clients/v2"); + } + @Test public void acceptsDotsThatAreNotDotSegments() { allowed("https://kc.example.com/auth", "https://kc.example.com/auth/admin/api/master/clients/v2/my.client"); diff --git a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/cli/util/HttpUtilRedirectTest.java b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/cli/util/HttpUtilRedirectTest.java index 184f48698d0c..74a5a4e1bffe 100644 --- a/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/cli/util/HttpUtilRedirectTest.java +++ b/integration/client-cli/admin-cli/src/test/java/org/keycloak/client/cli/util/HttpUtilRedirectTest.java @@ -28,7 +28,8 @@ public class HttpUtilRedirectTest { @Before public void setUp() throws IOException { HttpUtil.clearHttpClient(); - InetAddress loopback = InetAddress.getLoopbackAddress(); + // IPv4 explicitly, to match the 127.0.0.1 request URLs even when the JVM prefers IPv6 + InetAddress loopback = InetAddress.getByName("127.0.0.1"); other = HttpServer.create(new InetSocketAddress(loopback, 0), 0); other.createContext("/", exchange -> {