8000 Enforce the post-logout redirect URI client policy on logout requests by Praiztl · Pull Request #55704 · 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
Expand Up @@ -75,4 +75,11 @@ public enum ClientPolicyEvent {
* validation should ignore it and perform their checks during the regular authorization event.
*/
AUTHORIZATION_REQUEST_REDIRECT_URI,

/**
* Validate the post-logout redirect URI parameter of an RP-initiated logout request before the
* logout response can redirect to it. Executors unrelated to redirect URI validation should
* ignore it and perform their checks during the regular logout event.
*/
POST_LOGOUT_REDIRECT_URI,
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.LogoutRequestContext;
import org.keycloak.services.clientpolicy.context.PostLogoutRedirectUriContext;
import org.keycloak.services.cors.Cors;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.AuthenticationSessionManager;
Expand Down Expand Up @@ -242,6 +243,20 @@ public Response logout(@QueryParam(OIDCLoginProtocol.ID_TOKEN_HINT) String encod
event.error(Errors.INVALID_REDIRECT_URI);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
}

// The URI is a registered post-logout redirect URI; also enforce any client policy on it,
// so logout requests are subject to the same restrictions as CRUD and authorization redirects.
try {
session.clientPolicy().triggerOnEvent(new PostLogoutRedirectUriContext(client, validatedRedirectUri));
} catch (ClientPolicyException cpe) {
event.event(EventType.LOGOUT);
event.detail(Details.REDIRECT_URI, postLogoutRedirectUri);
event.detail(Details.REASON, Details.CLIENT_POLICY_ERROR);
event.detail(Details.CLIENT_POLICY_ERROR, cpe.getError());
event.detail(Details.CLIENT_POLICY_ERROR_DETAIL, cpe.getErrorDetail());
event.error(cpe.getError());
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
}
}

UserSessionModel userSession = null;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2026 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.services.clientpolicy.context;

import org.keycloak.models.ClientModel;
import org.keycloak.services.clientpolicy.ClientPolicyContext;
import org.keycloak.services.clientpolicy.ClientPolicyEvent;

/**
* The resolved post-logout redirect URI of an RP-initiated logout request, validated against the
* client's registered post-logout redirect URIs but not yet against client policies.
*/
public class PostLogoutRedirectUriContext implements ClientPolicyContext, ClientModelContext {

private final ClientModel client;
private final String postLogoutRedirectUri;

public PostLogoutRedirectUriContext(ClientModel client, String postLogoutRedirectUri) {
this.client = client;
this.postLogoutRedirectUri = postLogoutRedirectUri;
}

@Override
public ClientPolicyEvent getEvent() {
return ClientPolicyEvent.POST_LOGOUT_REDIRECT_URI;
}

@Override
public ClientModel getClient() {
return client;
}

public String getPostLogoutRedirectUri() {
return postLogoutRedirectUri;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ public String getProviderId() {

@Override
public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyException {
// Validate the callback before rejecting the request during the regular authorization event.
if (context.getEvent() == ClientPolicyEvent.AUTHORIZATION_REQUEST_REDIRECT_URI) {
// Validate the callback before rejecting the request during the regular authorization and logout events.
if (context.getEvent() == ClientPolicyEvent.AUTHORIZATION_REQUEST_REDIRECT_URI
|| context.getEvent() == ClientPolicyEvent.POST_LOGOUT_REDIRECT_URI) {
return;
}
throw new ClientPolicyException(OAuthErrorException.INVALID_REQUEST, "Request not allowed");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.clientpolicy.context.AuthorizationRequestParametersContext;
import org.keycloak.services.clientpolicy.context.ClientCRUDContext;
import org.keycloak.services.clientpolicy.context.PostLogoutRedirectUriContext;
import org.keycloak.services.clientpolicy.executor.SecureRedirectUrisEnforcerExecutorFactory.UriType;

import com.fasterxml.jackson.annotation.JsonProperty;
Expand Down Expand Up @@ -193,6 +194,9 @@ public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyExcep
case AUTHORIZATION_REQUEST:
validateAuthorizationRedirectUri((AuthorizationRequestParametersContext) context);
return;
case POST_LOGOUT_REDIRECT_URI:
validatePostLogoutRedirectUri((PostLogoutRedirectUriContext) context);
return;
default:
}
}
Expand All @@ -205,6 +209,38 @@ private void validateAuthorizationRedirectUri(AuthorizationRequestParametersCont
verifyRedirectUri(context.getRedirectUri(), true);
}

private void validatePostLogoutRedirectUri(PostLogoutRedirectUriContext context) throws ClientPolicyException {
if (context.getClient() == null) {
throw invalidRedirectUri("Invalid parameter: clientId");
}
verifyPostLogoutRedirectUri(context.getPostLogoutRedirectUri());
}

// The URI has already been matched against the client's registered post-logout redirect URIs, so it may
// be a registered value (OAuth 2.1 registers a loopback redirect URI without a port) or the runtime
// callback the client used (a loopback client substitutes a dynamic port at request time). The only
// restriction that differs between those two forms is the OAuth 2.1 loopback port rule, which requires a
// port for a request parameter and forbids one for a registered URI, so select the request-parameter
// form of the rule when the URI carries an explicit port and the registered form otherwise. Every other
// restriction (http scheme, wildcards, fragments, permitted domains, open-redirect override) is enforced
// identically to a registered redirect URI.
void verifyPostLogoutRedirectUri(String redirectUri) throws ClientPolicyException {
// open redirect allows any value for redirect uri
if (configuration.isAllowOpenRedirect()) {
return;
}
verifyRedirectUri(redirectUri, hasExplicitPort(redirectUri));
}

private static boolean hasExplicitPort(String redirectUri) {
try {
return new URI(redirectUri).getPort() > -1;
} catch (URISyntaxException e) {
// Let verifyRedirectUri surface the syntax error with the proper error detail.
return false;
}
}

private void verifyRedirectUris(ClientCRUDContext context) throws ClientPolicyException {
ClientRepresentation proposed = context.getProposedClientRepresentation();
if (isAuthFlowWithRedirectEnabled(proposed)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,47 @@ public void successPrivateUseUriScheme_OAuth2_0Compliant() {
).forEach(i->checkSuccess(i, false));
}

@Test
public void postLogoutLoopbackAcceptedWithOrWithoutPort_OAuth2_1() {
enable(ALLOW_IPV4_LOOPBACK_ADDRESS, ALLOW_IPV6_LOOPBACK_ADDRESS, ALLOW_HTTP_SCHEME, OAUTH_2_1_COMPLIANT);
setupConfiguration(configuration);
// A post-logout URI is matched against the registered list before it reaches the executor, so the
// registered loopback form (no port) and the runtime callback form (explicit port) are both valid.
Stream.of(
"http://127.0.0.1/oauth2redirect/example-provider",
"http://127.0.0.1:43321/oauth2redirect/example-provider",
"http://[::1]/oauth2redirect/example-provider",
"http://[::1]:43321/oauth2redirect/example-provider"
).forEach(this::checkPostLogoutSuccess);
}

@Test
public void postLogoutHonorsOpenRedirectOverride() {
enable(ALLOW_OPEN_REDIRECT);
setupConfiguration(configuration);
checkPostLogoutSuccess("http://anywhere.example.com/post-logout");
}

@Test
public void postLogoutRejectsDisallowedHttp() {
// default config: http scheme not allowed
setupConfiguration(configuration);
try {
executor.verifyPostLogoutRedirectUri("http://insecure.example.com/post-logout");
fail();
} catch (ClientPolicyException e) {
assertEquals(SecureRedirectUrisEnforcerExecutor.ERR_NORMALURI, e.getErrorDetail());
}
}

private void checkPostLogoutSuccess(String redirectUri) {
try {
executor.verifyPostLogoutRedirectUri(redirectUri);
} catch (ClientPolicyException e) {
fail(redirectUri + " : " + e.getErrorDetail());
}
}

private void permittedDomains(String... domains) {
ArrayNode arrayNode = JsonSerialization.mapper.createArrayNode();
Arrays.stream(domains).forEach(arrayNode::add);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Copyright 2026 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.client.policies;

import java.util.Collections;

import org.keycloak.protocol.oidc.OIDCConfigAttributes;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.services.clientpolicy.condition.AnyClientConditionFactory;
import org.keycloak.services.clientpolicy.executor.SecureRedirectUrisEnforcerExecutorFactory;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.oauth.OAuthClient;
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.realm.ManagedRealm;

import org.junit.jupiter.api.Test;

import static org.keycloak.tests.utils.ClientPoliciesUtil.createAnyClientConditionConfig;
import static org.keycloak.tests.utils.ClientPoliciesUtil.createSecureRedirectUrisEnforcerExecutorConfig;

import static org.junit.jupiter.api.Assertions.assertFalse;

/**
* Regression test for #52578: the SecureRedirectUrisEnforcer policy must reject a post-logout
* redirect URI on an actual RP-initiated logout request, not only on client CRUD operations.
* The URI is registered on the client before the policy is enabled, so it passes the client's
* registered post-logout list at logout time and would escape enforcement without the dedicated
* POST_LOGOUT_REDIRECT_URI client-policy event.
*/
@KeycloakIntegrationTest
public class SecureRedirectUrisEnforcerPostLogoutTest extends AbstractClientPoliciesTest {

private static final String HTTP_DISALLOWED_POST_LOGOUT = "http://insecure.example.com/post-logout";
private static final String HTTPS_CALLBACK = "https://app.example.com/callback";

@InjectRealm
protected ManagedRealm realm;

@InjectOAuthClient
protected OAuthClient oauth;

@Test
public void testLogoutIsRejectedForPolicyViolatingPostLogoutRedirectUri() throws Exception {
String clientId = generateSuffixedName("post-logout-http");
createClientByAdmin(realm, clientId, OIDCLoginProtocol.LOGIN_PROTOCOL, rep -> {
rep.setStandardFlowEnabled(Boolean.TRUE);
rep.setRedirectUris(Collections.singletonList(HTTPS_CALLBACK));
rep.getAttributes().put(OIDCConfigAttributes.POST_LOGOUT_REDIRECT_URIS, HTTP_DISALLOWED_POST_LOGOUT);
});

setupSecureRedirectPolicy();

oauth.client(clientId);
oauth.logoutForm().withClientId().postLogoutRedirectUri(HTTP_DISALLOWED_POST_LOGOUT).open();

assertFalse(oauth.getDriver().getCurrentUrl().startsWith(HTTP_DISALLOWED_POST_LOGOUT));
}

private void setupSecureRedirectPolicy() throws Exception {
setupPolicy(
realm,
SecureRedirectUrisEnforcerExecutorFactory.PROVIDER_ID,
createSecureRedirectUrisEnforcerExecutorConfig(cfg -> {}),
AnyClientConditionFactory.PROVIDER_ID,
createAnyClientConditionConfig());
}
}
0