8000 fix: relaxes the admin root redirect check by shawkins · Pull Request #39095 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Breaking changes are identified as requiring changes from existing users to their configurations.

=== local admin deprecated for removal
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The heading should provide more context, for example:

Suggested change
=== local admin deprecated for removal
=== Java enum `UrlType.LOCAL_ADMIN` deprecated for removal

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's both the enum and the template variable that are being deprecated.


`UrlType.LOCAL_ADMIN` and the corresponding welcome theme variable `localAdminUrl` have been deprecated for eventual removal. The default welcome resource will now simply mention localhost rather than providing a URL when an admin user has yet to be created.

=== Deprecated for removal the Instagram Identity Broker

In this release, the Instagram Identity Broker is deprecated for removal and is not enabled by default.
Expand Down
7 changes: 6 additions & 1 deletion server-spi/src/main/java/org/keycloak/urls/UrlType.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

public enum UrlType {

FRONTEND, BACKEND, ADMIN, LOCAL_ADMIN
FRONTEND, BACKEND, ADMIN,
/**
* @deprecated to be removed
*/
@Deprecated
LOCAL_ADMIN

}
8000
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public Response createUser() {
if (!shouldBootstrap()) {
return createWelcomePage(null, null);
} else {
if (!isLocal()) {
if (!isLocal(session)) {
ServicesLogger.LOGGER.rejectedNonLocalAttemptToCreateInitialUser(session.getContext().getConnection().getRemoteHost());
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
Expand Down Expand Up @@ -210,7 +210,7 @@ private Response createWelcomePage(String successMessage, String errorMessage) {
map.put("resourcesPath", "resources/" + Version.RESOURCES_VERSION + "/" + theme.getType().toString().toLowerCase() +"/" + theme.getName());
map.put("resourcesCommonPath", "resources/" + Version.RESOURCES_VERSION + "/" + commonPath);

boolean isLocal = isLocal();
boolean isLocal = isLocal(session);
map.put("localUser", isLocal);

if (bootstrap) {
Expand Down Expand Up @@ -269,15 +269,15 @@ private boolean shouldBootstrap() {
return shouldBootstrap.get();
}

private boolean isLocal() {
public static boolean isLocal(KeycloakSession session) {
Comment thread
vmuzikar marked this conversation as resolved.
Resolved
ClientConnection clientConnection = session.getContext().getConnection();
String remoteAddress = clientConnection.getRemoteAddr();
String localAddress = clientConnection.getLocalAddr();
HttpRequest request = session.getContext().getHttpRequest();
HttpHeaders headers = request.getHttpHeaders();
String xForwardedFor = headers.getHeaderString("X-Forwarded-For");
String forwarded = headers.getHeaderString("Forwarded");
logger.debugf("Checking WelcomePage. Remote address: %s, Local address: %s, X-Forwarded-For header: %s, Forwarded header: %s", remoteAddress, localAddress, xForwardedFor, forwarded);
logger.debugf("Checking isLocal. Remote address: %s, Local address: %s, X-Forwarded-For header: %s, Forwarded header: %s", remoteAddress, localAddress, xForwardedFor, forwarded);

// Consider that welcome page accessed locally just if it was accessed really through "localhost" URL and without loadbalancer (x-forwarded-for and forwarded header is empty).
return xForwardedFor == null && forwarded == null && SecureContextResolver.isLocalAddress(remoteAddress) && SecureContextResolver.isLocalAddress(localAddress);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.jboss.logging.Logger;
import org.keycloak.http.HttpRequest;
import org.keycloak.http.HttpResponse;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.NotAuthorizedException;
import org.keycloak.common.Profile;
Expand All @@ -35,6 +34,7 @@
import org.keycloak.services.managers.AppAuthManager;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.resources.WelcomeResource;
import org.keycloak.services.resources.admin.info.ServerInfoAdminResource;
import org.keycloak.services.resources.admin.permissions.AdminPermissions;
import org.keycloak.theme.Theme;
Expand Down Expand Up @@ -94,19 +94,31 @@ public static UriBuilder adminBaseUrl(UriBuilder base) {
@GET
@Operation(hidden = true)
public Response masterRealmAdminConsoleRedirect() {
String requestUrl = session.getContext().getUri().getRequestUri().toString();
KeycloakUriInfo adminUriInfo = session.getContext().getUri(UrlType.ADMIN);
if (shouldRedirect(adminUriInfo)) {
RealmModel master = new RealmManager(session).getKeycloakAdminstrationRealm();
return Response.status(302).location(
adminUriInfo.getBaseUriBuilder().path(AdminRoot.class).path(AdminRoot.class, "getAdminConsole").path("/").build(master.getName())
).build();
}
return Response.status(Response.Status.NOT_FOUND).build();
}

boolean shouldRedirect(KeycloakUriInfo adminUriInfo) {
if (!isAdminConsoleEnabled()) {
return false;
}
KeycloakUriInfo frontEndUriInfo = session.getContext().getUri();
String frontEndUrl = frontEndUriInfo.getBaseUri().toString();
String adminUrl = adminUriInfo.getBaseUri().toString();
String localAdminUrl = session.getContext().getUri(UrlType.LOCAL_ADMIN).getBaseUri().toString();

if (!isAdminConsoleEnabled() || (!requestUrl.startsWith(adminUrl) && !requestUrl.startsWith(localAdminUrl))) {
return Response.status(Response.Status.NOT_FOUND).build();
if (adminUrl.equals(frontEndUrl)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes sense to me - the issue I reported would enter here, my frontend and admin are the same.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I built a new keycloak-999.0.0-SNAPSHOT.zip and tested my edge case.

$ ./bin/kc.sh start-dev \
--hostname=https://banana.russdev

In another window I curled the /admin/ endpoint and saw the results I was expecting

$ curl -v http://banana.russdev:8080/admin/
< HTTP/1.1 302 Found
< Location: https://banana.russdev/admin/master/console/

LGTM!

return true; // admin is the same as front-end, we're not leaking information
}
String requestUrl = frontEndUriInfo.getRequestUri().toString();

RealmModel master = new RealmManager(session).getKeycloakAdminstrationRealm();
return Response.status(302).location(
adminUriInfo.getBaseUriBuilder().path(AdminRoot.class).path(AdminRoot.class, "getAdminConsole").path("/").build(master.getName())
).build();
// if we're using the admin url or are local, it's also safe to redirect
return requestUrl.startsWith(adminUrl) || WelcomeResource.isLocal(session);
}

/**
Expand Down Expand Up @@ -282,10 +294,6 @@ public Object getServerInfo() {
return new ServerInfoAdminResource(session);
}

private HttpResponse getHttpResponse() {
return session.getContext().getHttpResponse();
}

private HttpRequest getHttpRequest() {
return session.getContext().getHttpRequest();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2025 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.tests.admin;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.keycloak.testframework.annotations.InjectHttpClient;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.server.KeycloakServerConfig;
import org.keycloak.testframework.server.KeycloakServerConfigBuilder;

/**
* @author Vaclav Muzikar <vmuzikar@redhat.com>
*/
@KeycloakIntegrationTest(config = AdminRootEdgeTest.AdminUrlConfig.class)
public class AdminRootEdgeTest {
// full url with https, with default hostname-admin
private static final String HOSTNAME = "https://127.0.0.1.nip.io:8080";

@InjectHttpClient(followRedirects = false)
private HttpClient client;

@ParameterizedTest
@ValueSource(strings = {"http://127.0.0.1:8080", "http://127.0.0.1.nip.io:8080"})
public void testRedirect(String hostname) throws Exception {
HttpResponse response = client.execute(new HttpGet(hostname + "/admin"));

assertEquals(302, response.getStatusLine().getStatusCode());
assertThat(response.getFirstHeader("Location").getValue(), startsWith(HOSTNAME + "/admin/master/console"));
}

public static class AdminUrlConfig implements KeycloakServerConfig {
@Override
public KeycloakServerConfigBuilder configure(KeycloakServerConfigBuilder config) {
return config.options(Map.of(
"hostname", HOSTNAME
));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ public void testRedirect(String hostname) throws Exception {

@Test
public void testNoRedirectWithFrontendUrl() throws Exception {
HttpResponse response = client.execute(new HttpGet(HOSTNAME + "/admin"));
HttpGet request = new HttpGet(HOSTNAME + "/admin");
// make the request seem like it's coming from a proxy so that it won't seem local
request.addHeader("Forwarded", "for=192.0.2.60");
Comment thread
vmuzikar marked this conversation as resolved.
Resolved
HttpResponse response = client.execute(request);

assertEquals(404, response.getStatusLine().getStatusCode());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public void testAdminLocal() throws Exception {
SimpleHttp get = SimpleHttpDefault.doGet(getDynamicBaseUrl("127.0.0.1.nip.io"), client).header("X-Forwarded-For", "127.0.0.1");

String welcomePage = get.asString();
assertThat(welcomePage, containsString("<a href=\"" + getDynamicBaseUrl("localhost") + "/\">"));
assertThat(welcomePage, containsString("localhost"));
}
}
finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@
</div>
</form>
<#else>
<p>To create the temporary administrative user open <a href="${localAdminUrl}">${localAdminUrl}</a>, or use a <code>bootstrap-admin</code> command.</p>
<p>To create the temporary administrative user, access the Administration Console over localhost, or use a <code>bootstrap-admin</code> command.</p>
</#if>
</#if>
</div>
Expand Down
0