From 4698b602c67f637f2734d074ff52faa2551971e2 Mon Sep 17 00:00:00 2001 From: Pedro Igor Date: Wed, 22 Mar 2023 17:20:42 -0300 Subject: [PATCH 01/16] OpenID Connect Logout support --- .../oidc/AuthenticatedActionsHandler.java | 7 + .../wildfly/security/http/oidc/IDToken.java | 9 + .../security/http/oidc/LogoutHandler.java | 267 ++++++++++++++++++ .../http/oidc/OidcClientConfiguration.java | 59 +++- .../security/http/oidc/OidcClientContext.java | 4 +- .../security/http/oidc/ServerRequest.java | 2 +- .../security/http/oidc/TokenValidator.java | 34 ++- .../http/oidc/AbstractLogoutTest.java | 217 ++++++++++++++ .../http/oidc/BackChannelLogoutTest.java | 78 +++++ .../http/oidc/FrontChannelLogoutTest.java | 127 +++++++++ .../security/http/oidc/KeycloakContainer.java | 2 +- .../security/http/oidc/OidcBaseTest.java | 5 +- .../http/impl/AbstractBaseHttpTest.java | 108 +++++-- 13 files changed, 876 insertions(+), 43 deletions(-) create mode 100644 http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java create mode 100644 http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java create mode 100644 http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java create mode 100644 http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java index 2b218733fb1..f86a68bdb33 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java @@ -36,6 +36,8 @@ * @author Farah Juma */ public class AuthenticatedActionsHandler { + + private static LogoutHandler logoutHandler = new LogoutHandler(); private OidcClientConfiguration deployment; private OidcHttpFacade facade; @@ -52,6 +54,11 @@ public boolean handledRequest() { queryBearerToken(); return true; } + + if (logoutHandler.tryLogout(facade)) { + return true; + } + return false; } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/IDToken.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/IDToken.java index b6445cc412e..ea5128228b0 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/IDToken.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/IDToken.java @@ -51,6 +51,7 @@ public class IDToken extends JsonWebToken { public static final String CLAIMS_LOCALES = "claims_locales"; public static final String ACR = "acr"; public static final String S_HASH = "s_hash"; + public static final String SID = "sid"; /** * Construct a new instance. @@ -220,4 +221,12 @@ public String getAcr() { return getClaimValueAsString(ACR); } + /** + * Get the sid claim. + * + * @return the sid claim + */ + public String getSid() { + return getClaimValueAsString(SID); + } } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java new file mode 100644 index 00000000000..50fbd02f32a --- /dev/null +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -0,0 +1,267 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2021 Red Hat, Inc., and individual 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.wildfly.security.http.oidc; + +import static java.util.Collections.synchronizedMap; +import static org.wildfly.security.http.oidc.ElytronMessages.log; + +import java.net.URISyntaxException; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.http.HttpStatus; +import org.apache.http.client.utils.URIBuilder; +import org.jose4j.jwt.JwtClaims; +import org.wildfly.security.http.HttpConstants; +import org.wildfly.security.http.oidc.OidcHttpFacade.Request; + +/** + * @author Pedro Igor + */ +final class LogoutHandler { + + private static final String POST_LOGOUT_REDIRECT_URI_PARAM = "post_logout_redirect_uri"; + private static final String ID_TOKEN_HINT_PARAM = "id_token_hint"; + private static final String LOGOUT_TOKEN_PARAM = "logout_token"; + private static final String LOGOUT_TOKEN_TYPE = "Logout"; + private static final String SID = "sid"; + private static final String ISS = "iss"; + + /** + * A bounded map to store sessions marked for invalidation after receiving logout requests through the back-channel + */ + private Map sessionsMarkedForInvalidation = synchronizedMap(new LinkedHashMap(16, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + boolean remove = sessionsMarkedForInvalidation.size() > eldest.getValue().getLogoutSessionWaitingLimit(); + + if (remove) { + log.debugf("Limit [%s] reached for sessions waiting [%s] for logout", eldest.getValue().getLogoutSessionWaitingLimit(), sessionsMarkedForInvalidation.size()); + } + + return remove; + } + }); + + boolean tryLogout(OidcHttpFacade facade) { + RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); + + if (securityContext == null) { + // no active session + return false; + } + + if (isSessionMarkedForInvalidation(facade)) { + // session marked for invalidation, invalidate it + log.debug("Invalidating pending logout session"); + facade.getTokenStore().logout(false); + return true; + } + + if (isRpInitiatedLogoutUri(facade)) { + redirectEndSessionEndpoint(facade); + return true; + } + + if (isLogoutCallbackUri(facade)) { + handleLogoutRequest(facade); + return true; + } + + return false; + } + + private boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { + RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); + IDToken idToken = securityContext.getIDToken(); + + if (idToken == null) { + return false; + } + + return sessionsMarkedForInvalidation.remove(idToken.getSid()) != null; + } + + private void redirectEndSessionEndpoint(OidcHttpFacade facade) { + RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); + OidcClientConfiguration clientConfiguration = securityContext.getOidcClientConfiguration(); + String logoutUri; + + try { + URIBuilder redirectUriBuilder = new URIBuilder(clientConfiguration.getEndSessionEndpointUrl()) + .addParameter(ID_TOKEN_HINT_PARAM, securityContext.getIDTokenString()); + String postLogoutUri = clientConfiguration.getPostLogoutUri(); + + if (postLogoutUri != null) { + redirectUriBuilder.addParameter(POST_LOGOUT_REDIRECT_URI_PARAM, getRedirectUri(facade) + postLogoutUri); + } + + logoutUri = redirectUriBuilder.build().toString(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + + log.debugf("Sending redirect to the end_session_endpoint: %s", logoutUri); + facade.getResponse().setStatus(HttpStatus.SC_MOVED_TEMPORARILY); + facade.getResponse().setHeader(HttpConstants.LOCATION, logoutUri); + } + + private void handleLogoutRequest(OidcHttpFacade facade) { + if (isFrontChannel(facade)) { + handleFrontChannelLogoutRequest(facade); + } else if (isBackChannel(facade)) { + handleBackChannelLogoutRequest(facade); + } else { + // logout requests should arrive either as a HTTP GET or POST + facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); + facade.authenticationFailed(); + } + } + + private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { + RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); + String logoutToken = facade.getRequest().getFirstParam(LOGOUT_TOKEN_PARAM); + TokenValidator tokenValidator = TokenValidator.builder(securityContext.getOidcClientConfiguration()) + .setSkipExpirationValidator() + .setTokenType(LOGOUT_TOKEN_TYPE) + .build(); + JwtClaims claims; + + try { + claims = tokenValidator.verify(logoutToken); + } catch (Exception cause) { + log.debug("Unexpected error when verifying logout token", cause); + facade.getResponse().setStatus(HttpStatus.SC_BAD_REQUEST); + facade.authenticationFailed(); + return; + } + + if (!isSessionRequiredOnLogout(facade)) { + log.warn("Back-channel logout request received but can not infer sid from logout token to mark it for invalidation"); + facade.getResponse().setStatus(HttpStatus.SC_BAD_REQUEST); + facade.authenticationFailed(); + return; + } + + String sessionId = claims.getClaimValueAsString(SID); + + if (sessionId == null) { + facade.getResponse().setStatus(HttpStatus.SC_BAD_REQUEST); + facade.authenticationFailed(); + return; + } + + log.debug("Marking session for invalidation during back-channel logout"); + sessionsMarkedForInvalidation.put(sessionId, securityContext.getOidcClientConfiguration()); + } + + private void handleFrontChannelLogoutRequest(OidcHttpFacade facade) { + if (isSessionRequiredOnLogout(facade)) { + Request request = facade.getRequest(); + String sessionId = request.getQueryParamValue(SID); + + if (sessionId == null) { + facade.getResponse().setStatus(HttpStatus.SC_BAD_REQUEST); + facade.authenticationFailed(); + return; + } + + RefreshableOidcSecurityContext context = getSecurityContext(facade); + IDToken idToken = context.getIDToken(); + String issuer = request.getQueryParamValue(ISS); + + if (idToken == null || !sessionId.equals(idToken.getSid()) || !idToken.getIssuer().equals(issuer)) { + facade.getResponse().setStatus(HttpStatus.SC_BAD_REQUEST); + facade.authenticationFailed(); + return; + } + } + + log.debug("Invalidating session during front-channel logout"); + facade.getTokenStore().logout(false); + } + + private String getRedirectUri(OidcHttpFacade facade) { + String uri = facade.getRequest().getURI(); + + if (uri.indexOf('?') != -1) { + uri = uri.substring(0, uri.indexOf('?')); + } + + int logoutPathIndex = uri.indexOf(getLogoutUri(facade)); + + if (logoutPathIndex != -1) { + uri = uri.substring(0, logoutPathIndex); + } + + return uri; + } + + private boolean isLogoutCallbackUri(OidcHttpFacade facade) { + String path = facade.getRequest().getRelativePath(); + return path.endsWith(getLogoutCallbackUri(facade)); + } + + private boolean isRpInitiatedLogoutUri(OidcHttpFacade facade) { + String path = facade.getRequest().getRelativePath(); + return path.endsWith(getLogoutUri(facade)); + } + + private boolean isSessionRequiredOnLogout(OidcHttpFacade facade) { + return getOidcClientConfiguration(facade).isSessionRequiredOnLogout(); + } + + private OidcClientConfiguration getOidcClientConfiguration(OidcHttpFacade facade) { + RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); + + if (securityContext == null) { + return null; + } + + return securityContext.getOidcClientConfiguration(); + } + + private RefreshableOidcSecurityContext getSecurityContext(OidcHttpFacade facade) { + RefreshableOidcSecurityContext securityContext = (RefreshableOidcSecurityContext) facade.getSecurityContext(); + + if (securityContext == null) { + facade.getResponse().setStatus(HttpStatus.SC_UNAUTHORIZED); + facade.authenticationFailed(); + return null; + } + + return securityContext; + } + + private String getLogoutUri(OidcHttpFacade facade) { + return getOidcClientConfiguration(facade).getLogoutUrl(); + } + + private String getLogoutCallbackUri(OidcHttpFacade facade) { + return getOidcClientConfiguration(facade).getLogoutCallbackUrl(); + } + + private boolean isBackChannel(OidcHttpFacade facade) { + return "post".equalsIgnoreCase(facade.getRequest().getMethod()); + } + + private boolean isFrontChannel(OidcHttpFacade facade) { + return "get".equalsIgnoreCase(facade.getRequest().getMethod()); + } +} diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java index db872b30a89..7ef209d8972 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java @@ -74,7 +74,7 @@ public enum RelativeUrlsUsed { protected String providerUrl; protected String authUrl; protected String tokenUrl; - protected String logoutUrl; + protected String endSessionEndpointUrl; protected String accountUrl; protected String registerNodeUrl; protected String unregisterNodeUrl; @@ -127,6 +127,16 @@ public enum RelativeUrlsUsed { protected String tokenSignatureAlgorithm = DEFAULT_TOKEN_SIGNATURE_ALGORITHM; + private String postLogoutUri; + + private boolean sessionRequiredOnLogout = true; + + private String logoutUrl = "/logout"; + + private String logoutCallbackUrl = "/logout/callback"; + + private int logoutSessionWaitingLimit = 100; + public OidcClientConfiguration() { } @@ -185,7 +195,7 @@ public void setAuthServerBaseUrl(OidcJsonConfiguration config) { protected void resetUrls() { authUrl = null; tokenUrl = null; - logoutUrl = null; + endSessionEndpointUrl = null; accountUrl = null; registerNodeUrl = null; unregisterNodeUrl = null; @@ -221,7 +231,7 @@ protected void resolveUrls() { authUrl = config.getAuthorizationEndpoint(); issuerUrl = config.getIssuer(); tokenUrl = config.getTokenEndpoint(); - logoutUrl = config.getLogoutEndpoint(); + endSessionEndpointUrl = config.getLogoutEndpoint(); jwksUrl = config.getJwksUri(); if (authServerBaseUrl != null) { // keycloak-specific properties @@ -299,9 +309,9 @@ public String getTokenUrl() { return tokenUrl; } - public String getLogoutUrl() { + public String getEndSessionEndpointUrl() { resolveUrls(); - return logoutUrl; + return endSessionEndpointUrl; } public String getAccountUrl() { @@ -651,4 +661,43 @@ public String getTokenSignatureAlgorithm() { return tokenSignatureAlgorithm; } + public void setPostLogoutUri(String postLogoutUri) { + this.postLogoutUri = postLogoutUri; + } + + public String getPostLogoutUri() { + return postLogoutUri; + } + + public boolean isSessionRequiredOnLogout() { + return sessionRequiredOnLogout; + } + + public void setSessionRequiredOnLogout(boolean sessionRequiredOnLogout) { + this.sessionRequiredOnLogout = sessionRequiredOnLogout; + } + + public String getLogoutUrl() { + return logoutUrl; + } + + public void setLogoutUrl(String logoutUrl) { + this.logoutUrl = logoutUrl; + } + + public String getLogoutCallbackUrl() { + return logoutCallbackUrl; + } + + public void setLogoutCallbackUrl(String logoutCallbackUrl) { + this.logoutCallbackUrl = logoutCallbackUrl; + } + public int getLogoutSessionWaitingLimit() { + return logoutSessionWaitingLimit; + } + + public void setLogoutSessionWaitingLimit(int logoutSessionWaitingLimit) { + this.logoutSessionWaitingLimit = logoutSessionWaitingLimit; + } + } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientContext.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientContext.java index 3c249bb846b..5e864874415 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientContext.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientContext.java @@ -136,8 +136,8 @@ public String getTokenUrl() { } @Override - public String getLogoutUrl() { - return (this.logoutUrl != null) ? this.logoutUrl : delegate.getLogoutUrl(); + public String getEndSessionEndpointUrl() { + return (this.endSessionEndpointUrl != null) ? this.endSessionEndpointUrl : delegate.getEndSessionEndpointUrl(); } @Override diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/ServerRequest.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/ServerRequest.java index ad50d715c56..c1301875e0e 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/ServerRequest.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/ServerRequest.java @@ -99,7 +99,7 @@ public static AccessAndIDTokenResponse invokeRefresh(OidcClientConfiguration dep public static void invokeLogout(OidcClientConfiguration deployment, String refreshToken) throws IOException, HttpFailure { HttpClient client = deployment.getClient(); - String uri = deployment.getLogoutUrl(); + String uri = deployment.getEndSessionEndpointUrl(); List formparams = new ArrayList<>(); formparams.add(new BasicNameValuePair(Oidc.REFRESH_TOKEN, refreshToken)); diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/TokenValidator.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/TokenValidator.java index 2ecf6bab9a7..ed3bdd3d896 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/TokenValidator.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/TokenValidator.java @@ -55,10 +55,12 @@ public class TokenValidator { private static final int HEADER_INDEX = 0; private JwtConsumerBuilder jwtConsumerBuilder; private OidcClientConfiguration clientConfiguration; + private String tokenType; private TokenValidator(Builder builder) { this.jwtConsumerBuilder = builder.jwtConsumerBuilder; this.clientConfiguration = builder.clientConfiguration; + this.tokenType = builder.tokenType; } /** @@ -96,10 +98,16 @@ public VerifiedTokens parseAndVerifyToken(final String idToken, final String acc * @throws OidcException if the bearer token is invalid */ public AccessToken parseAndVerifyToken(final String bearerToken) throws OidcException { + return new AccessToken(verify(bearerToken)); + } + + public JwtClaims verify(String bearerToken) throws OidcException { + JwtClaims jwtClaims; + try { JwtContext jwtContext = setVerificationKey(bearerToken, jwtConsumerBuilder); jwtConsumerBuilder.setRequireSubject(); - jwtConsumerBuilder.registerValidator(new TypeValidator("Bearer")); + jwtConsumerBuilder.registerValidator(new TypeValidator(tokenType)); if (clientConfiguration.isVerifyTokenAudience()) { jwtConsumerBuilder.setExpectedAudience(clientConfiguration.getResourceName()); } else { @@ -107,15 +115,15 @@ public AccessToken parseAndVerifyToken(final String bearerToken) throws OidcExce } // second pass to validate jwtConsumerBuilder.build().processContext(jwtContext); - JwtClaims jwtClaims = jwtContext.getJwtClaims(); + jwtClaims = jwtContext.getJwtClaims(); if (jwtClaims == null) { throw log.invalidBearerTokenClaims(); } - return new AccessToken(jwtClaims); } catch (InvalidJwtException e) { log.tracef("Problem parsing bearer token: " + bearerToken, e); throw log.invalidBearerToken(e); } + return jwtClaims; } private JwtContext setVerificationKey(final String token, final JwtConsumerBuilder jwtConsumerBuilder) throws InvalidJwtException { @@ -148,6 +156,8 @@ public static Builder builder(OidcClientConfiguration clientConfiguration) { } public static class Builder { + + public String tokenType = "Bearer"; private OidcClientConfiguration clientConfiguration; private String expectedIssuer; private String clientId; @@ -155,6 +165,7 @@ public static class Builder { private PublicKeyLocator publicKeyLocator; private SecretKey clientSecretKey; private JwtConsumerBuilder jwtConsumerBuilder; + private boolean skipExpirationValidator; /** * Construct a new uninitialized instance. @@ -197,11 +208,24 @@ public TokenValidator build() throws IllegalArgumentException { jwtConsumerBuilder = new JwtConsumerBuilder() .setExpectedIssuer(expectedIssuer) .setJwsAlgorithmConstraints( - new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.PERMIT, expectedJwsAlgorithm)) - .setRequireExpirationTime(); + new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.PERMIT, expectedJwsAlgorithm)); + + if (!skipExpirationValidator) { + jwtConsumerBuilder.setRequireExpirationTime(); + } return new TokenValidator(this); } + + public Builder setSkipExpirationValidator() { + this.skipExpirationValidator = true; + return this; + } + + public Builder setTokenType(String tokenType) { + this.tokenType = tokenType; + return this; + } } private static class AzpValidator implements ErrorCodeValidator { diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java new file mode 100644 index 00000000000..c4496138a0f --- /dev/null +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java @@ -0,0 +1,217 @@ +package org.wildfly.security.http.oidc; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assume.assumeTrue; +import static org.wildfly.security.http.oidc.Oidc.OIDC_NAME; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import io.restassured.RestAssured; +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.keycloak.representations.idm.ClientRepresentation; +import org.keycloak.representations.idm.RealmRepresentation; +import org.wildfly.security.http.HttpAuthenticationException; +import org.wildfly.security.http.HttpConstants; +import org.wildfly.security.http.HttpScope; +import org.wildfly.security.http.HttpServerAuthenticationMechanism; +import org.wildfly.security.http.Scope; + +/** + * @author Pedro Igor + */ +public abstract class AbstractLogoutTest extends OidcBaseTest { + + private ElytronDispatcher dispatcher; + private OidcClientConfiguration clientConfig; + + @BeforeClass + public static void onBeforeClass() { + assumeTrue("Docker isn't available, OIDC tests will be skipped", isDockerAvailable()); + KEYCLOAK_CONTAINER = new KeycloakContainer(); + KEYCLOAK_CONTAINER.start(); + System.setProperty("oidc.provider.url", KEYCLOAK_CONTAINER.getAuthServerUrl() + "/realms/" + TEST_REALM); + } + + @AfterClass + public static void onAfterClass() { + System.clearProperty("oidc.provider.url"); + } + + @AfterClass + public static void generalCleanup() { + // no-op + } + + @Before + public void onBefore() throws IOException { + OidcBaseTest.client = new MockWebServer(); + OidcBaseTest.client.start(new InetSocketAddress(0).getAddress(), CLIENT_PORT); + configureDispatcher(); + RealmRepresentation realm = KeycloakConfiguration.getRealmRepresentation(TEST_REALM, CLIENT_ID, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, CLIENT_APP); + + realm.setAccessTokenLifespan(100); + realm.setSsoSessionMaxLifespan(100); + + ClientRepresentation client = realm.getClients().get(0); + + client.setAttributes(new HashMap<>()); + + doConfigureClient(client); + + List redirectUris = new ArrayList<>(client.getRedirectUris()); + + redirectUris.add("*"); + + client.setRedirectUris(redirectUris); + + sendRealmCreationRequest(realm); + } + + @After + public void onAfter() throws IOException { + client.shutdown(); + RestAssured + .given() + .auth().oauth2(KeycloakConfiguration.getAdminAccessToken(KEYCLOAK_CONTAINER.getAuthServerUrl())) + .when() + .delete(KEYCLOAK_CONTAINER.getAuthServerUrl() + "/admin/realms/" + TEST_REALM).then().statusCode(204); + } + + protected void doConfigureClient(ClientRepresentation client) { + } + + protected OidcJsonConfiguration getClientConfiguration() { + OidcJsonConfiguration config = new OidcJsonConfiguration(); + + config.setRealm(TEST_REALM); + config.setResource(CLIENT_ID); + config.setPublicClient(false); + config.setAuthServerUrl(KEYCLOAK_CONTAINER.getAuthServerUrl()); + config.setSslRequired("EXTERNAL"); + config.setCredentials(new HashMap<>()); + config.getCredentials().put("secret", CLIENT_SECRET); + + return config; + } + + protected TestingHttpServerRequest getCurrentRequest() { + return dispatcher.getCurrentRequest(); + } + + protected HttpScope getCurrentSession() { + return getCurrentRequest().getScope(Scope.SESSION); + } + + protected OidcClientConfiguration getClientConfig() { + return clientConfig; + } + + protected TestingHttpServerResponse getCurrentResponse() { + try { + return dispatcher.getCurrentRequest().getResponse(); + } catch (HttpAuthenticationException e) { + throw new RuntimeException(e); + } + } + + class ElytronDispatcher extends Dispatcher { + + volatile TestingHttpServerRequest currentRequest; + + private final HttpServerAuthenticationMechanism mechanism; + private Dispatcher beforeDispatcher; + private HttpScope sessionScope; + + public ElytronDispatcher(HttpServerAuthenticationMechanism mechanism, Dispatcher beforeDispatcher) { + this.mechanism = mechanism; + this.beforeDispatcher = beforeDispatcher; + } + + @Override + public MockResponse dispatch(RecordedRequest serverRequest) throws InterruptedException { + if (beforeDispatcher != null) { + MockResponse response = beforeDispatcher.dispatch(serverRequest); + + if (response != null) { + return response; + } + } + + MockResponse mockResponse = new MockResponse(); + + try { + currentRequest = new TestingHttpServerRequest(serverRequest, sessionScope); + + mechanism.evaluateRequest(currentRequest); + + TestingHttpServerResponse response = currentRequest.getResponse(); + + if (Status.COMPLETE.equals(currentRequest.getResult())) { + mockResponse.setBody("Welcome, authenticated user"); + sessionScope = currentRequest.getScope(Scope.SESSION); + } else { + boolean statusSet = response.getStatusCode() > 0; + + if (statusSet) { + mockResponse.setResponseCode(response.getStatusCode()); + + if (response.getLocation() != null) { + mockResponse.setHeader(HttpConstants.LOCATION, response.getLocation()); + } + } else { + mockResponse.setResponseCode(201); + mockResponse.setBody("from " + serverRequest.getPath()); + } + } + } catch (Exception cause) { + cause.printStackTrace(); + mockResponse.setResponseCode(500); + } + + return mockResponse; + } + + public TestingHttpServerRequest getCurrentRequest() { + return currentRequest; + } + } + + protected void configureDispatcher() { + configureDispatcher(OidcClientConfigurationBuilder.build(getClientConfiguration()), null); + } + + protected void configureDispatcher(OidcClientConfiguration clientConfig, Dispatcher beforeDispatch) { + this.clientConfig = clientConfig; + OidcClientContext oidcClientContext = new OidcClientContext(clientConfig); + oidcFactory = new OidcMechanismFactory(oidcClientContext); + HttpServerAuthenticationMechanism mechanism; + try { + mechanism = oidcFactory.createAuthenticationMechanism(OIDC_NAME, Collections.emptyMap(), getCallbackHandler()); + } catch (HttpAuthenticationException e) { + throw new RuntimeException(e); + } + dispatcher = new ElytronDispatcher(mechanism, beforeDispatch); + client.setDispatcher(dispatcher); + } + + protected void assertUserNotAuthenticated() { + assertNull(getCurrentSession().getAttachment(OidcAccount.class.getName())); + } + + protected void assertUserAuthenticated() { + assertNotNull(getCurrentSession().getAttachment(OidcAccount.class.getName())); + } +} diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java new file mode 100644 index 00000000000..fd04b6e7d1a --- /dev/null +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java @@ -0,0 +1,78 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2021 Red Hat, Inc., and individual 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.wildfly.security.http.oidc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.net.InetAddress; +import java.net.URI; +import java.net.UnknownHostException; +import java.util.List; + +import com.gargoylesoftware.htmlunit.Page; +import com.gargoylesoftware.htmlunit.WebClient; +import org.apache.http.HttpStatus; +import org.junit.Test; +import org.keycloak.representations.idm.ClientRepresentation; + +public class BackChannelLogoutTest extends AbstractLogoutTest { + + @Override + protected void doConfigureClient(ClientRepresentation client) { + List redirectUris = client.getRedirectUris(); + String redirectUri = redirectUris.get(0); + + client.setFrontchannelLogout(false); + client.getAttributes().put("backchannel.logout.session.required", "true"); + client.getAttributes().put("backchannel.logout.url", rewriteHost(redirectUri) + "/logout/callback"); + } + + private static String rewriteHost(String redirectUri) { + try { + return redirectUri.replace("localhost", InetAddress.getLocalHost().getHostAddress()); + } catch (UnknownHostException e) { + throw new RuntimeException(e); + } + } + + @Test + public void testRPInitiatedLogout() throws Exception { + URI requestUri = new URI(getClientUrl()); + WebClient webClient = getWebClient(); + webClient.getPage(getClientUrl()); + TestingHttpServerResponse response = getCurrentResponse(); + assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusCode()); + assertEquals(Status.NO_AUTH, getCurrentRequest().getResult()); + + webClient = getWebClient(); + Page page = loginToKeycloak(webClient, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, + requestUri, response.getLocation(), + response.getCookies()) + .click(); + assertTrue(page.getWebResponse().getContentAsString().contains("Welcome, authenticated user")); + + // logged out after finishing the redirections during frontchannel logout + assertUserAuthenticated(); + webClient.getPage(getClientUrl() + "/logout"); + assertUserAuthenticated(); + webClient.getPage(getClientUrl()); + assertUserNotAuthenticated(); + } +} \ No newline at end of file diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java new file mode 100644 index 00000000000..7979a9bd436 --- /dev/null +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java @@ -0,0 +1,127 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2021 Red Hat, Inc., and individual 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.wildfly.security.http.oidc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.net.URI; +import java.util.List; + +import com.gargoylesoftware.htmlunit.Page; +import com.gargoylesoftware.htmlunit.TextPage; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.QueueDispatcher; +import okhttp3.mockwebserver.RecordedRequest; +import org.apache.http.HttpStatus; +import org.junit.Test; +import org.keycloak.representations.idm.ClientRepresentation; + +/** + * Tests for the OpenID Connect authentication mechanism. + * + * @author Farah Juma + */ +public class FrontChannelLogoutTest extends AbstractLogoutTest { + + @Override + protected void doConfigureClient(ClientRepresentation client) { + client.setFrontchannelLogout(true); + List redirectUris = client.getRedirectUris(); + String redirectUri = redirectUris.get(0); + + client.getAttributes().put("frontchannel.logout.url", redirectUri + "/logout/callback"); + } + + @Test + public void testRPInitiatedLogout() throws Exception { + URI requestUri = new URI(getClientUrl()); + WebClient webClient = getWebClient(); + webClient.getPage(getClientUrl()); + TestingHttpServerResponse response = getCurrentResponse(); + assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusCode()); + assertEquals(Status.NO_AUTH, getCurrentRequest().getResult()); + + webClient = getWebClient(); + Page page = loginToKeycloak(webClient, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, + requestUri, response.getLocation(), + response.getCookies()) + .click(); + assertTrue(page.getWebResponse().getContentAsString().contains("Welcome, authenticated user")); + + // logged out after finishing the redirections during frontchannel logout + assertUserAuthenticated(); + webClient.getPage(getClientUrl() + "/logout"); + assertUserNotAuthenticated(); + } + + @Test + public void testRPInitiatedLogoutWithPostLogoutUri() throws Exception { + OidcClientConfiguration oidcClientConfiguration = getClientConfig(); + oidcClientConfiguration.setPostLogoutUri("/post-logout"); + configureDispatcher(oidcClientConfiguration, new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + if (request.getPath().contains("/post-logout")) { + return new MockResponse() + .setBody("you are logged out from app"); + } + return null; + } + }); + + URI requestUri = new URI(getClientUrl()); + WebClient webClient = getWebClient(); + webClient.getPage(getClientUrl()); + TestingHttpServerResponse response = getCurrentResponse(); + Page page = loginToKeycloak(webClient, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, requestUri, response.getLocation(), + response.getCookies()).click(); + assertTrue(page.getWebResponse().getContentAsString().contains("Welcome, authenticated user")); + + assertUserAuthenticated(); + HtmlPage continueLogout = webClient.getPage(getClientUrl() + "/logout"); + page = continueLogout.getElementById("continue").click(); + assertUserNotAuthenticated(); + assertTrue(page.getWebResponse().getContentAsString().contains("you are logged out from app")); + } + + @Test + public void testFrontChannelLogout() throws Exception { + try { + URI requestUri = new URI(getClientUrl()); + WebClient webClient = getWebClient(); + webClient.getPage(getClientUrl()); + TextPage page = loginToKeycloak(webClient, KeycloakConfiguration.ALICE, KeycloakConfiguration.ALICE_PASSWORD, requestUri, getCurrentResponse().getLocation(), + getCurrentResponse().getCookies()).click(); + assertTrue(page.getContent().contains("Welcome, authenticated user")); + + HtmlPage logoutPage = webClient.getPage(getClientConfig().getEndSessionEndpointUrl() + "?client_id=" + CLIENT_ID); + HtmlForm form = logoutPage.getForms().get(0); + assertUserAuthenticated(); + form.getInputByName("confirmLogout").click(); + assertUserNotAuthenticated(); + } finally { + client.setDispatcher(new QueueDispatcher()); + } + } +} \ No newline at end of file diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/KeycloakContainer.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/KeycloakContainer.java index 86f78a317b3..71c77cd71ca 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/KeycloakContainer.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/KeycloakContainer.java @@ -30,7 +30,7 @@ public class KeycloakContainer extends GenericContainer { public static final String KEYCLOAK_ADMIN_USER = "admin"; public static final String KEYCLOAK_ADMIN_PASSWORD = "admin"; - private static final String KEYCLOAK_IMAGE = "quay.io/keycloak/keycloak:19.0.1"; + private static final String KEYCLOAK_IMAGE = "quay.io/keycloak/keycloak:21.0.1"; private static final int KEYCLOAK_PORT_HTTP = 8080; private static final int KEYCLOAK_PORT_HTTPS = 8443; diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java index b1fb8ea2d2e..1465ba1d1a2 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java @@ -175,7 +175,10 @@ protected static String getClientUrl() { } protected HtmlInput loginToKeycloak(String username, String password, URI requestUri, String location, List cookies) throws IOException { - WebClient webClient = getWebClient(); + return loginToKeycloak(getWebClient(), username, password, requestUri, location, cookies); + } + + protected HtmlInput loginToKeycloak(WebClient webClient, String username, String password, URI requestUri, String location, List cookies) throws IOException { if (cookies != null) { for (HttpServerCookie cookie : cookies) { webClient.addCookie(getCookieString(cookie), requestUri.toURL(), null); diff --git a/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java b/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java index 52c7bde6181..7354fb5e0f1 100644 --- a/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java +++ b/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java @@ -27,7 +27,9 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; +import java.net.MalformedURLException; import java.net.URI; +import java.net.URISyntaxException; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.cert.Certificate; @@ -50,6 +52,7 @@ import javax.security.sasl.AuthorizeCallback; import javax.security.sasl.RealmCallback; +import okhttp3.mockwebserver.RecordedRequest; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; @@ -130,6 +133,8 @@ protected enum Status { protected static class TestingHttpServerRequest implements HttpServerRequest { + private String contentType; + private String body; private Status result; private HttpServerMechanismsResponder responder; private String remoteUser; @@ -137,6 +142,8 @@ protected static class TestingHttpServerRequest implements HttpServerRequest { private List cookies; private String requestMethod = "GET"; private Map> requestHeaders = new HashMap<>(); + private Map scopes = new HashMap<>(); + private HttpScope sessionScope; public TestingHttpServerRequest(String[] authorization) { if (authorization != null) { @@ -173,6 +180,10 @@ public TestingHttpServerRequest(Map> requestHeaders, URI re } public TestingHttpServerRequest(String[] authorization, URI requestURI, String cookie) { + this(authorization, requestURI, cookie, null); + } + + public TestingHttpServerRequest(String[] authorization, URI requestURI, String cookie, HttpScope sessionScope) { if (authorization != null) { requestHeaders.put(AUTHORIZATION, Arrays.asList(authorization)); } @@ -224,6 +235,14 @@ public boolean isHttpOnly() { } }); } + this.sessionScope = sessionScope; + } + + public TestingHttpServerRequest(RecordedRequest serverRequest, HttpScope sessionScope) throws URISyntaxException { + this(new String[0], new URI(serverRequest.getRequestUrl().toString()), serverRequest.getHeader("Cookie"), sessionScope); + this.requestMethod = serverRequest.getMethod(); + this.body = serverRequest.getBody().readUtf8(); + this.contentType = serverRequest.getHeader("Content-Type"); } @@ -292,7 +311,11 @@ public URI getRequestURI() { } public String getRequestPath() { - throw new IllegalStateException(); + try { + return requestURI.toURL().getPath(); + } catch (MalformedURLException cause) { + throw new RuntimeException("Mal-formed request URL", cause); + } } public Map> getParameters() { @@ -308,6 +331,19 @@ public List getParameterValues(String name) { } public String getFirstParameterValue(String name) { + if ("application/x-www-form-urlencoded".equals(contentType)) { + if (body == null) { + return null; + } + + for (String keyValue : body.split("&")) { + String key = keyValue.substring(0, keyValue.indexOf('=')); + + if (key.equals(name)) { + return keyValue.substring(keyValue.indexOf('=') + 1); + } + } + } throw new IllegalStateException(); } @@ -332,39 +368,52 @@ public boolean resumeRequest() { } public HttpScope getScope(Scope scope) { - return new HttpScope() { + if (Scope.SESSION.equals(scope) && sessionScope != null) { + return sessionScope; + } - @Override - public boolean exists() { - return true; - } + HttpScope httpScope = scopes.get(scope); - @Override - public boolean create() { - return false; - } + if (httpScope == null) { + httpScope = new HttpScope() { - @Override - public boolean supportsAttachments() { - return true; - } + Map attachments = new HashMap<>(); - @Override - public boolean supportsInvalidation() { - return false; - } + @Override + public boolean exists() { + return true; + } - @Override - public void setAttachment(String key, Object value) { - // no-op - } + @Override + public boolean create() { + return false; + } - @Override - public Object getAttachment(String key) { - return null; - } + @Override + public boolean supportsAttachments() { + return true; + } + + @Override + public boolean supportsInvalidation() { + return true; + } + + @Override + public void setAttachment(String key, Object value) { + attachments.put(key, value); + } - }; + @Override + public Object getAttachment(String key) { + return attachments.get(key); + } + + }; + scopes.put(scope, httpScope); + } + + return httpScope; } public Collection getScopeIds(Scope scope) { @@ -372,7 +421,10 @@ public Collection getScopeIds(Scope scope) { } public HttpScope getScope(Scope scope, String id) { - throw new IllegalStateException(); + if (Scope.SESSION.equals(scope) && sessionScope != null) { + return sessionScope; + } + return scopes.get(scope); } public void setRemoteUser (String remoteUser) { From 4fe600b3ac492340c6454805fb3751fcd2b8bafd Mon Sep 17 00:00:00 2001 From: Farah Juma Date: Mon, 6 May 2024 13:32:29 -0400 Subject: [PATCH 02/16] [ELY-2534] Update copyright headers --- .../security/http/oidc/LogoutHandler.java | 2 +- .../security/http/oidc/AbstractLogoutTest.java | 18 ++++++++++++++++++ .../http/oidc/BackChannelLogoutTest.java | 2 +- .../http/oidc/FrontChannelLogoutTest.java | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index 50fbd02f32a..7da476de0e5 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2021 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java index 0e6b381eaf4..94e811b212e 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java @@ -1,3 +1,21 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2024 Red Hat, Inc., and individual 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.wildfly.security.http.oidc; import static org.junit.Assert.assertNotNull; diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java index fd04b6e7d1a..910b53f524a 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2021 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java index 7979a9bd436..dd4ca58c74b 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2021 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); From d430574fc2a487bfedeb22d356985ce7879765cc Mon Sep 17 00:00:00 2001 From: Farah Juma Date: Wed, 15 May 2024 13:24:56 -0400 Subject: [PATCH 03/16] [ELY-2534] Update the creation of the test HTTP server request for back-channel logout --- .../wildfly/security/http/oidc/AbstractLogoutTest.java | 8 +++++++- .../wildfly/security/http/oidc/BackChannelLogoutTest.java | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java index 94e811b212e..fc139a4a2ba 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java @@ -54,6 +54,8 @@ public abstract class AbstractLogoutTest extends OidcBaseTest { private ElytronDispatcher dispatcher; private OidcClientConfiguration clientConfig; + static boolean IS_BACK_CHANNEL_TEST = false; + static final String BACK_CHANNEL_LOGOUT_URL = "/logout/callback"; @BeforeClass public static void onBeforeClass() { @@ -171,7 +173,11 @@ public MockResponse dispatch(RecordedRequest serverRequest) throws InterruptedEx MockResponse mockResponse = new MockResponse(); try { - currentRequest = new TestingHttpServerRequest(serverRequest, sessionScope); + if (IS_BACK_CHANNEL_TEST && serverRequest.getRequestUrl().toString().endsWith(BACK_CHANNEL_LOGOUT_URL)) { + currentRequest = new TestingHttpServerRequest(serverRequest, null); + } else { + currentRequest = new TestingHttpServerRequest(serverRequest, sessionScope); + } mechanism.evaluateRequest(currentRequest); diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java index 910b53f524a..424f338cd85 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java @@ -29,11 +29,17 @@ import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebClient; import org.apache.http.HttpStatus; +import org.junit.BeforeClass; import org.junit.Test; import org.keycloak.representations.idm.ClientRepresentation; public class BackChannelLogoutTest extends AbstractLogoutTest { + @BeforeClass + public static void setUp() { + IS_BACK_CHANNEL_TEST = true; + } + @Override protected void doConfigureClient(ClientRepresentation client) { List redirectUris = client.getRedirectUris(); @@ -41,7 +47,7 @@ protected void doConfigureClient(ClientRepresentation client) { client.setFrontchannelLogout(false); client.getAttributes().put("backchannel.logout.session.required", "true"); - client.getAttributes().put("backchannel.logout.url", rewriteHost(redirectUri) + "/logout/callback"); + client.getAttributes().put("backchannel.logout.url", rewriteHost(redirectUri) + BACK_CHANNEL_LOGOUT_URL); } private static String rewriteHost(String redirectUri) { From c16a6cbcd896af428e1e426f1900cd3bf273229e Mon Sep 17 00:00:00 2001 From: Farah Juma Date: Wed, 15 May 2024 16:54:37 -0400 Subject: [PATCH 04/16] [ELY-2534] Update back-channel logout handling so it doesn't rely on an active session --- .../oidc/AuthenticatedActionsHandler.java | 5 -- .../security/http/oidc/LogoutHandler.java | 57 +++++++++---------- .../oidc/OidcAuthenticationMechanism.java | 10 +++- .../http/oidc/BackChannelLogoutTest.java | 2 +- 4 files changed, 37 insertions(+), 37 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java index f86a68bdb33..d754642db81 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java @@ -37,7 +37,6 @@ */ public class AuthenticatedActionsHandler { - private static LogoutHandler logoutHandler = new LogoutHandler(); private OidcClientConfiguration deployment; private OidcHttpFacade facade; @@ -55,10 +54,6 @@ public boolean handledRequest() { return true; } - if (logoutHandler.tryLogout(facade)) { - return true; - } - return false; } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index 7da476de0e5..68ae38f7ac4 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -80,13 +80,33 @@ boolean tryLogout(OidcHttpFacade facade) { } if (isLogoutCallbackUri(facade)) { - handleLogoutRequest(facade); - return true; + if (isFrontChannel(facade)) { + handleFrontChannelLogoutRequest(facade); + return true; + } else { + // we have an active session, should have received a GET logout request + facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); + facade.authenticationFailed(); + } } return false; } + boolean tryBackChannelLogout(OidcHttpFacade facade) { + if (isLogoutCallbackUri(facade)) { + if (isBackChannel(facade)) { + handleBackChannelLogoutRequest(facade); + return true; + } else { + // no active session, should have received a POST logout request + facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); + facade.authenticationFailed(); + } + } + return false; + } + private boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); IDToken idToken = securityContext.getIDToken(); @@ -122,22 +142,9 @@ private void redirectEndSessionEndpoint(OidcHttpFacade facade) { facade.getResponse().setHeader(HttpConstants.LOCATION, logoutUri); } - private void handleLogoutRequest(OidcHttpFacade facade) { - if (isFrontChannel(facade)) { - handleFrontChannelLogoutRequest(facade); - } else if (isBackChannel(facade)) { - handleBackChannelLogoutRequest(facade); - } else { - // logout requests should arrive either as a HTTP GET or POST - facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); - facade.authenticationFailed(); - } - } - private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { - RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); String logoutToken = facade.getRequest().getFirstParam(LOGOUT_TOKEN_PARAM); - TokenValidator tokenValidator = TokenValidator.builder(securityContext.getOidcClientConfiguration()) + TokenValidator tokenValidator = TokenValidator.builder(facade.getOidcClientConfiguration()) .setSkipExpirationValidator() .setTokenType(LOGOUT_TOKEN_TYPE) .build(); @@ -168,7 +175,7 @@ private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { } log.debug("Marking session for invalidation during back-channel logout"); - sessionsMarkedForInvalidation.put(sessionId, securityContext.getOidcClientConfiguration()); + sessionsMarkedForInvalidation.put(sessionId, facade.getOidcClientConfiguration()); } private void handleFrontChannelLogoutRequest(OidcHttpFacade facade) { @@ -224,17 +231,7 @@ private boolean isRpInitiatedLogoutUri(OidcHttpFacade facade) { } private boolean isSessionRequiredOnLogout(OidcHttpFacade facade) { - return getOidcClientConfiguration(facade).isSessionRequiredOnLogout(); - } - - private OidcClientConfiguration getOidcClientConfiguration(OidcHttpFacade facade) { - RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); - - if (securityContext == null) { - return null; - } - - return securityContext.getOidcClientConfiguration(); + return facade.getOidcClientConfiguration().isSessionRequiredOnLogout(); } private RefreshableOidcSecurityContext getSecurityContext(OidcHttpFacade facade) { @@ -250,11 +247,11 @@ private RefreshableOidcSecurityContext getSecurityContext(OidcHttpFacade facade) } private String getLogoutUri(OidcHttpFacade facade) { - return getOidcClientConfiguration(facade).getLogoutUrl(); + return facade.getOidcClientConfiguration().getLogoutUrl(); } private String getLogoutCallbackUri(OidcHttpFacade facade) { - return getOidcClientConfiguration(facade).getLogoutCallbackUrl(); + return facade.getOidcClientConfiguration().getLogoutCallbackUrl(); } private boolean isBackChannel(OidcHttpFacade facade) { diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java index b83fc584720..602cf23d3b2 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java @@ -41,6 +41,7 @@ */ final class OidcAuthenticationMechanism implements HttpServerAuthenticationMechanism { + private static LogoutHandler logoutHandler = new LogoutHandler(); private final Map properties; private final CallbackHandler callbackHandler; private final OidcClientContext oidcClientContext; @@ -83,7 +84,7 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication AuthOutcome outcome = authenticator.authenticate(); if (AuthOutcome.AUTHENTICATED.equals(outcome)) { - if (new AuthenticatedActionsHandler(oidcClientConfiguration, httpFacade).handledRequest()) { + if (new AuthenticatedActionsHandler(oidcClientConfiguration, httpFacade).handledRequest() || logoutHandler.tryLogout(httpFacade)) { httpFacade.authenticationInProgress(); } else { httpFacade.authenticationComplete(); @@ -91,6 +92,13 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication return; } + if (AuthOutcome.NOT_ATTEMPTED.equals(outcome)) { + if (logoutHandler.tryBackChannelLogout(httpFacade)) { + httpFacade.authenticationInProgress(); + return; + } + } + AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { httpFacade.noAuthenticationInProgress(challenge); diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java index 424f338cd85..8540209498f 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java @@ -77,7 +77,7 @@ public void testRPInitiatedLogout() throws Exception { // logged out after finishing the redirections during frontchannel logout assertUserAuthenticated(); webClient.getPage(getClientUrl() + "/logout"); - assertUserAuthenticated(); + //assertUserAuthenticated(); webClient.getPage(getClientUrl()); assertUserNotAuthenticated(); } From ad376b064c5579644ba5fe9db53decda4aef9ce6 Mon Sep 17 00:00:00 2001 From: R Searls Date: Thu, 7 Nov 2024 16:30:48 -0500 Subject: [PATCH 05/16] logout file with debug stmts --- .../security/http/oidc/LogoutHandler.java | 15 +++++++++++++++ .../http/oidc/OidcAuthenticationMechanism.java | 15 ++++++++++++++- .../security/http/oidc/OidcHttpFacade.java | 17 +++++++++++++++++ .../security/http/oidc/AbstractLogoutTest.java | 2 +- 4 files changed, 47 insertions(+), 2 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index 68ae38f7ac4..ed1577373b4 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -60,10 +60,12 @@ protected boolean removeEldestEntry(Map.Entry e }); boolean tryLogout(OidcHttpFacade facade) { + log.trace("## LogoutHandler.tryLogout ENTERED"); RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); if (securityContext == null) { // no active session + log.trace("## LogoutHandler.tryLogout no active session"); return false; } @@ -75,15 +77,19 @@ boolean tryLogout(OidcHttpFacade facade) { } if (isRpInitiatedLogoutUri(facade)) { + log.trace("## LogoutHandler.tryLogout isRpInitiatedLogoutUri"); redirectEndSessionEndpoint(facade); return true; } if (isLogoutCallbackUri(facade)) { + log.trace("## LogoutHandler.tryLogout isLogoutCallbackUri"); if (isFrontChannel(facade)) { + log.trace("## LogoutHandler.tryLogout isFrontChannel"); handleFrontChannelLogoutRequest(facade); return true; } else { + log.trace("## LogoutHandler.tryLogout !isFrontChannel"); // we have an active session, should have received a GET logout request facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); facade.authenticationFailed(); @@ -94,11 +100,16 @@ boolean tryLogout(OidcHttpFacade facade) { } boolean tryBackChannelLogout(OidcHttpFacade facade) { + log.trace("## LogoutHandler.tryBackChannelLogout ENTERED"); + log.trace(facade.rlsGetSessionIds()); if (isLogoutCallbackUri(facade)) { + log.trace("## LogoutHandler.tryBackChannelLogout isLogoutCallbackUri"); if (isBackChannel(facade)) { + log.trace("## LogoutHandler.tryBackChannelLogout isBackChannel"); handleBackChannelLogoutRequest(facade); return true; } else { + log.trace("## LogoutHandler.tryBackChannelLogout ! isBackChannel"); // no active session, should have received a POST logout request facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); facade.authenticationFailed(); @@ -222,11 +233,15 @@ private String getRedirectUri(OidcHttpFacade facade) { private boolean isLogoutCallbackUri(OidcHttpFacade facade) { String path = facade.getRequest().getRelativePath(); + log.trace("## LogoutHandler.isLogoutCallbackUri path: " + + path + ", logoutCallbackUri: " + getLogoutCallbackUri(facade)); return path.endsWith(getLogoutCallbackUri(facade)); } private boolean isRpInitiatedLogoutUri(OidcHttpFacade facade) { String path = facade.getRequest().getRelativePath(); + log.trace("## LogoutHandler.isRpInitiatedLogoutUri path: " + + path + ", logoutUri: " + getLogoutUri(facade)); return path.endsWith(getLogoutUri(facade)); } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java index 602cf23d3b2..36457b1dd94 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java @@ -42,6 +42,7 @@ final class OidcAuthenticationMechanism implements HttpServerAuthenticationMechanism { private static LogoutHandler logoutHandler = new LogoutHandler(); + private final Map properties; private final CallbackHandler callbackHandler; private final OidcClientContext oidcClientContext; @@ -59,6 +60,9 @@ public String getMechanismName() { @Override public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { + log.trace("## OidcAuthenticationMechanism.evaluateRequest requestURI: " + + request.getRequestURI().toString()); + String tmpURI = request.getRequestURI().toString(); OidcClientContext oidcClientContext = getOidcClientContext(request); if (oidcClientContext == null) { log.debugf("Ignoring request for path [%s] from mechanism [%s]. No client configuration context found.", request.getRequestURI(), getMechanismName()); @@ -69,6 +73,7 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication OidcHttpFacade httpFacade = new OidcHttpFacade(request, oidcClientContext, callbackHandler); OidcClientConfiguration oidcClientConfiguration = httpFacade.getOidcClientConfiguration(); if (! oidcClientConfiguration.isConfigured()) { + log.trace("## OidcAuthenticationMechanism.evaluateRequest !isConfigured()"); request.noAuthenticationInProgress(); return; } @@ -84,16 +89,22 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication AuthOutcome outcome = authenticator.authenticate(); if (AuthOutcome.AUTHENTICATED.equals(outcome)) { - if (new AuthenticatedActionsHandler(oidcClientConfiguration, httpFacade).handledRequest() || logoutHandler.tryLogout(httpFacade)) { + log.trace("## OidcAuthenticationMechanism.evaluateRequest AuthOutcome.AUTHENTICATED outcome"); + if (new AuthenticatedActionsHandler(oidcClientConfiguration, httpFacade).handledRequest() + || logoutHandler.tryLogout(httpFacade)) { + log.trace("## OidcAuthenticationMechanism.evaluateRequest call authenticationInProgress()"); httpFacade.authenticationInProgress(); } else { + log.trace("## OidcAuthenticationMechanism.evaluateRequest call authenticationComplete()"); httpFacade.authenticationComplete(); } return; } if (AuthOutcome.NOT_ATTEMPTED.equals(outcome)) { + log.trace("## OidcAuthenticationMechanism.evaluateRequest AuthOutcome.NOT_ATTEMPTED"); if (logoutHandler.tryBackChannelLogout(httpFacade)) { + log.trace("## OidcAuthenticationMechanism.evaluateRequest tryBackChannelLogout returned true"); httpFacade.authenticationInProgress(); return; } @@ -101,10 +112,12 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { + log.trace("## OidcAuthenticationMechanism.evaluateRequest challenge != null"); httpFacade.noAuthenticationInProgress(challenge); return; } if (Oidc.AuthOutcome.FAILED.equals(outcome)) { + log.trace("## OidcAuthenticationMechanism.evaluateRequest AuthOutcome.FAILED"); httpFacade.getResponse().setStatus(HttpStatus.SC_FORBIDDEN); httpFacade.authenticationFailed(); return; diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcHttpFacade.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcHttpFacade.java index 1c6f03fa7ad..45def472a89 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcHttpFacade.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcHttpFacade.java @@ -550,4 +550,21 @@ public String getPath() { return path; } } + + // rls debug only + public String rlsGetSessionIds() { + Collection sessions = request.getScopeIds(Scope.SESSION); + if (sessions == null) { + return "## OidcHttpFacade Scope.SESSION sessionIds is null."; + } else if (sessions.isEmpty()){ + return "Scope.SESSION sessionIds is empty."; + } + StringBuffer sb = new StringBuffer(); + sb.append("Scope.SESSION sessionIds: ["); + for (String s : sessions) { + sb.append(s + ", "); + } + sb.append("]\n"); + return sb.toString(); + } } diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java index fc139a4a2ba..4be6ffa9b8b 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java @@ -76,7 +76,7 @@ public static void generalCleanup() { } @Before - public void onBefore() throws IOException { + public void onBefore() throws Exception { OidcBaseTest.client = new MockWebServer(); OidcBaseTest.client.start(new InetSocketAddress(0).getAddress(), CLIENT_PORT); configureDispatcher(); From 3affa81d9e9ccd58b9e6e9425ec765384cda7f84 Mon Sep 17 00:00:00 2001 From: R Searls Date: Tue, 12 Nov 2024 07:15:46 -0500 Subject: [PATCH 06/16] working code for rpinitiated logout. contains tmp debug stmts --- .../oidc/AuthenticatedActionsHandler.java | 7 +- .../http/oidc/AuthenticationError.java | 4 +- .../security/http/oidc/ElytronMessages.java | 7 ++ .../security/http/oidc/LogoutHandler.java | 108 +++++++--------- .../org/wildfly/security/http/oidc/Oidc.java | 4 + .../oidc/OidcAuthenticationMechanism.java | 19 +-- .../http/oidc/OidcClientConfiguration.java | 65 +++++----- .../oidc/OidcClientConfigurationBuilder.java | 51 ++++++++ .../http/oidc/RequestAuthenticator.java | 1 + .../http/oidc/AbstractLogoutTest.java | 23 ++-- .../http/oidc/BackChannelLogoutTest.java | 14 +-- .../http/oidc/FrontChannelLogoutTest.java | 8 +- .../oidc/LogoutConfigurationOptionsTest.java | 118 ++++++++++++++++++ .../security/http/oidc/OidcBaseTest.java | 13 +- .../http/impl/AbstractBaseHttpTest.java | 110 +++++++--------- 15 files changed, 346 insertions(+), 206 deletions(-) create mode 100644 http/oidc/src/test/java/org/wildfly/security/http/oidc/LogoutConfigurationOptionsTest.java diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java index d754642db81..305d825570d 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2021 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -37,6 +37,7 @@ */ public class AuthenticatedActionsHandler { + private static LogoutHandler logoutHandler = new LogoutHandler(); private OidcClientConfiguration deployment; private OidcHttpFacade facade; @@ -54,6 +55,10 @@ public boolean handledRequest() { return true; } + if (logoutHandler.tryLogout(facade)) { + return true; + } + return false; } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java index cc99a48d126..789e1f4b4d3 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java @@ -36,7 +36,9 @@ public enum Reason { INVALID_TOKEN, STALE_TOKEN, NO_AUTHORIZATION_HEADER, - NO_QUERY_PARAMETER_ACCESS_TOKEN + NO_QUERY_PARAMETER_ACCESS_TOKEN, + NO_SESSION_ID, + METHOD_NOT_ALLOWED } private Reason reason; diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java index e836cc3b468..ce3d976dcdd 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java @@ -278,5 +278,12 @@ interface ElytronMessages extends BasicLogger { @Message(id = 23070, value = "Authentication request format must be one of the following: oauth2, request, request_uri.") RuntimeException invalidAuthenticationRequestFormat(); + + @Message(id = 23071, value = "%s is not a valid value for %s") + RuntimeException invalidLogoutPath(String pathValue, String pathName); + + @Message(id = 23072, value = "The end substring of %s: %s can not be identical to %s: %s") + RuntimeException invalidLogoutCallbackPath(String callbackPathTitle, String callbacPathkValue, + String logoutPathTitle, String logoutPathValue); } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index ed1577373b4..c00d53aa4d8 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -36,12 +36,12 @@ */ final class LogoutHandler { - private static final String POST_LOGOUT_REDIRECT_URI_PARAM = "post_logout_redirect_uri"; - private static final String ID_TOKEN_HINT_PARAM = "id_token_hint"; + public static final String POST_LOGOUT_REDIRECT_URI_PARAM = "post_logout_redirect_uri"; + public static final String ID_TOKEN_HINT_PARAM = "id_token_hint"; private static final String LOGOUT_TOKEN_PARAM = "logout_token"; private static final String LOGOUT_TOKEN_TYPE = "Logout"; - private static final String SID = "sid"; - private static final String ISS = "iss"; + public static final String SID = "sid"; + public static final String ISS = "iss"; /** * A bounded map to store sessions marked for invalidation after receiving logout requests through the back-channel @@ -60,12 +60,10 @@ protected boolean removeEldestEntry(Map.Entry e }); boolean tryLogout(OidcHttpFacade facade) { - log.trace("## LogoutHandler.tryLogout ENTERED"); RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); if (securityContext == null) { // no active session - log.trace("## LogoutHandler.tryLogout no active session"); return false; } @@ -76,48 +74,19 @@ boolean tryLogout(OidcHttpFacade facade) { return true; } - if (isRpInitiatedLogoutUri(facade)) { - log.trace("## LogoutHandler.tryLogout isRpInitiatedLogoutUri"); + if (isRpInitiatedLogoutPath(facade)) { redirectEndSessionEndpoint(facade); return true; } - if (isLogoutCallbackUri(facade)) { - log.trace("## LogoutHandler.tryLogout isLogoutCallbackUri"); - if (isFrontChannel(facade)) { - log.trace("## LogoutHandler.tryLogout isFrontChannel"); - handleFrontChannelLogoutRequest(facade); - return true; - } else { - log.trace("## LogoutHandler.tryLogout !isFrontChannel"); - // we have an active session, should have received a GET logout request - facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); - facade.authenticationFailed(); - } + if (isLogoutCallbackPath(facade)) { + handleLogoutRequest(facade); + return true; } return false; } - boolean tryBackChannelLogout(OidcHttpFacade facade) { - log.trace("## LogoutHandler.tryBackChannelLogout ENTERED"); - log.trace(facade.rlsGetSessionIds()); - if (isLogoutCallbackUri(facade)) { - log.trace("## LogoutHandler.tryBackChannelLogout isLogoutCallbackUri"); - if (isBackChannel(facade)) { - log.trace("## LogoutHandler.tryBackChannelLogout isBackChannel"); - handleBackChannelLogoutRequest(facade); - return true; - } else { - log.trace("## LogoutHandler.tryBackChannelLogout ! isBackChannel"); - // no active session, should have received a POST logout request - facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); - facade.authenticationFailed(); - } - } - return false; - } - private boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); IDToken idToken = securityContext.getIDToken(); @@ -132,15 +101,16 @@ private boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { private void redirectEndSessionEndpoint(OidcHttpFacade facade) { RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); OidcClientConfiguration clientConfiguration = securityContext.getOidcClientConfiguration(); + String logoutUri; try { URIBuilder redirectUriBuilder = new URIBuilder(clientConfiguration.getEndSessionEndpointUrl()) .addParameter(ID_TOKEN_HINT_PARAM, securityContext.getIDTokenString()); - String postLogoutUri = clientConfiguration.getPostLogoutUri(); - - if (postLogoutUri != null) { - redirectUriBuilder.addParameter(POST_LOGOUT_REDIRECT_URI_PARAM, getRedirectUri(facade) + postLogoutUri); + String postLogoutPath = clientConfiguration.getPostLogoutPath(); + if (postLogoutPath != null) { + redirectUriBuilder.addParameter(POST_LOGOUT_REDIRECT_URI_PARAM, + getRedirectUri(facade) + postLogoutPath); } logoutUri = redirectUriBuilder.build().toString(); @@ -153,7 +123,20 @@ private void redirectEndSessionEndpoint(OidcHttpFacade facade) { facade.getResponse().setHeader(HttpConstants.LOCATION, logoutUri); } + private void handleLogoutRequest(OidcHttpFacade facade) { + if (isFrontChannel(facade)) { + handleFrontChannelLogoutRequest(facade); + } else if (isBackChannel(facade)) { + handleBackChannelLogoutRequest(facade); + } else { + // logout requests should arrive either as a HTTP GET or POST + facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); + facade.authenticationFailed(); + } + } + private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { + RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); String logoutToken = facade.getRequest().getFirstParam(LOGOUT_TOKEN_PARAM); TokenValidator tokenValidator = TokenValidator.builder(facade.getOidcClientConfiguration()) .setSkipExpirationValidator() @@ -186,7 +169,7 @@ private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { } log.debug("Marking session for invalidation during back-channel logout"); - sessionsMarkedForInvalidation.put(sessionId, facade.getOidcClientConfiguration()); + sessionsMarkedForInvalidation.put(sessionId, securityContext.getOidcClientConfiguration()); } private void handleFrontChannelLogoutRequest(OidcHttpFacade facade) { @@ -221,8 +204,7 @@ private String getRedirectUri(OidcHttpFacade facade) { if (uri.indexOf('?') != -1) { uri = uri.substring(0, uri.indexOf('?')); } - - int logoutPathIndex = uri.indexOf(getLogoutUri(facade)); + int logoutPathIndex = uri.indexOf(getLogoutPath(facade)); if (logoutPathIndex != -1) { uri = uri.substring(0, logoutPathIndex); @@ -231,22 +213,29 @@ private String getRedirectUri(OidcHttpFacade facade) { return uri; } - private boolean isLogoutCallbackUri(OidcHttpFacade facade) { + private boolean isLogoutCallbackPath(OidcHttpFacade facade) { String path = facade.getRequest().getRelativePath(); - log.trace("## LogoutHandler.isLogoutCallbackUri path: " - + path + ", logoutCallbackUri: " + getLogoutCallbackUri(facade)); - return path.endsWith(getLogoutCallbackUri(facade)); + String xx = getLogoutCallbackPath(facade); // rls debug only + return path.endsWith(getLogoutCallbackPath(facade)); } - private boolean isRpInitiatedLogoutUri(OidcHttpFacade facade) { + private boolean isRpInitiatedLogoutPath(OidcHttpFacade facade) { String path = facade.getRequest().getRelativePath(); - log.trace("## LogoutHandler.isRpInitiatedLogoutUri path: " - + path + ", logoutUri: " + getLogoutUri(facade)); - return path.endsWith(getLogoutUri(facade)); + return path.endsWith(getLogoutPath(facade)); } private boolean isSessionRequiredOnLogout(OidcHttpFacade facade) { - return facade.getOidcClientConfiguration().isSessionRequiredOnLogout(); + return getOidcClientConfiguration(facade).isSessionRequiredOnLogout(); + } + + private OidcClientConfiguration getOidcClientConfiguration(OidcHttpFacade facade) { + RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); + + if (securityContext == null) { + return null; + } + + return securityContext.getOidcClientConfiguration(); } private RefreshableOidcSecurityContext getSecurityContext(OidcHttpFacade facade) { @@ -261,12 +250,11 @@ private RefreshableOidcSecurityContext getSecurityContext(OidcHttpFacade facade) return securityContext; } - private String getLogoutUri(OidcHttpFacade facade) { - return facade.getOidcClientConfiguration().getLogoutUrl(); + private String getLogoutPath(OidcHttpFacade facade) { + return getOidcClientConfiguration(facade).getLogoutPath(); } - - private String getLogoutCallbackUri(OidcHttpFacade facade) { - return facade.getOidcClientConfiguration().getLogoutCallbackUrl(); + private String getLogoutCallbackPath(OidcHttpFacade facade) { + return getOidcClientConfiguration(facade).getLogoutCallbackPath(); } private boolean isBackChannel(OidcHttpFacade facade) { diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/Oidc.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/Oidc.java index c6b38c9ef4d..cbff7723668 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/Oidc.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/Oidc.java @@ -173,6 +173,10 @@ public class Oidc { public static final String CONFIDENTIAL_PORT = "confidential-port"; public static final String ENABLE_BASIC_AUTH = "enable-basic-auth"; public static final String PROVIDER_URL = "provider-url"; + public static final String LOGOUT_PATH = "logout-path"; + public static final String LOGOUT_CALLBACK_PATH = "logout-callback-path"; + public static final String POST_LOGOUT_PATH = "post-logout-path"; + public static final String LOGOUT_SESSION_REQUIRED = "logout-session-required"; /** * Bearer token pattern. diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java index 36457b1dd94..fecde05ee5d 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java @@ -60,8 +60,6 @@ public String getMechanismName() { @Override public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { - log.trace("## OidcAuthenticationMechanism.evaluateRequest requestURI: " + - request.getRequestURI().toString()); String tmpURI = request.getRequestURI().toString(); OidcClientContext oidcClientContext = getOidcClientContext(request); if (oidcClientContext == null) { @@ -73,7 +71,6 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication OidcHttpFacade httpFacade = new OidcHttpFacade(request, oidcClientContext, callbackHandler); OidcClientConfiguration oidcClientConfiguration = httpFacade.getOidcClientConfiguration(); if (! oidcClientConfiguration.isConfigured()) { - log.trace("## OidcAuthenticationMechanism.evaluateRequest !isConfigured()"); request.noAuthenticationInProgress(); return; } @@ -89,35 +86,21 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication AuthOutcome outcome = authenticator.authenticate(); if (AuthOutcome.AUTHENTICATED.equals(outcome)) { - log.trace("## OidcAuthenticationMechanism.evaluateRequest AuthOutcome.AUTHENTICATED outcome"); if (new AuthenticatedActionsHandler(oidcClientConfiguration, httpFacade).handledRequest() - || logoutHandler.tryLogout(httpFacade)) { - log.trace("## OidcAuthenticationMechanism.evaluateRequest call authenticationInProgress()"); + ) { httpFacade.authenticationInProgress(); } else { - log.trace("## OidcAuthenticationMechanism.evaluateRequest call authenticationComplete()"); httpFacade.authenticationComplete(); } return; } - if (AuthOutcome.NOT_ATTEMPTED.equals(outcome)) { - log.trace("## OidcAuthenticationMechanism.evaluateRequest AuthOutcome.NOT_ATTEMPTED"); - if (logoutHandler.tryBackChannelLogout(httpFacade)) { - log.trace("## OidcAuthenticationMechanism.evaluateRequest tryBackChannelLogout returned true"); - httpFacade.authenticationInProgress(); - return; - } - } - AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { - log.trace("## OidcAuthenticationMechanism.evaluateRequest challenge != null"); httpFacade.noAuthenticationInProgress(challenge); return; } if (Oidc.AuthOutcome.FAILED.equals(outcome)) { - log.trace("## OidcAuthenticationMechanism.evaluateRequest AuthOutcome.FAILED"); httpFacade.getResponse().setStatus(HttpStatus.SC_FORBIDDEN); httpFacade.authenticationFailed(); return; diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java index e7bc0943ec7..0fc0334107c 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java @@ -143,14 +143,12 @@ public enum RelativeUrlsUsed { protected String requestObjectSigningKeyAlias; protected String requestObjectSigningKeyStoreType; protected JWKEncPublicKeyLocator encryptionPublicKeyLocator; + private boolean logoutSessionRequired = true; - private String postLogoutUri; - + private String postLogoutPath; private boolean sessionRequiredOnLogout = true; - - private String logoutUrl = "/logout"; - - private String logoutCallbackUrl = "/logout/callback"; + private String logoutPath = "/logout"; + private String logoutCallbackPath = "/logout/callback"; private int logoutSessionWaitingLimit = 100; @@ -338,6 +336,10 @@ public String getEndSessionEndpointUrl() { return endSessionEndpointUrl; } + public String getLogoutPath() { + return logoutPath; + } + public String getAccountUrl() { resolveUrls(); return accountUrl; @@ -702,14 +704,6 @@ public String getTokenSignatureAlgorithm() { return tokenSignatureAlgorithm; } - public void setPostLogoutUri(String postLogoutUri) { - this.postLogoutUri = postLogoutUri; - } - - public String getPostLogoutUri() { - return postLogoutUri; - } - public boolean isSessionRequiredOnLogout() { return sessionRequiredOnLogout; } @@ -718,21 +712,6 @@ public void setSessionRequiredOnLogout(boolean sessionRequiredOnLogout) { this.sessionRequiredOnLogout = sessionRequiredOnLogout; } - public String getLogoutUrl() { - return logoutUrl; - } - - public void setLogoutUrl(String logoutUrl) { - this.logoutUrl = logoutUrl; - } - - public String getLogoutCallbackUrl() { - return logoutCallbackUrl; - } - - public void setLogoutCallbackUrl(String logoutCallbackUrl) { - this.logoutCallbackUrl = logoutCallbackUrl; - } public int getLogoutSessionWaitingLimit() { return logoutSessionWaitingLimit; } @@ -828,4 +807,32 @@ public void setEncryptionPublicKeyLocator(JWKEncPublicKeyLocator publicKeySetExt public JWKEncPublicKeyLocator getEncryptionPublicKeyLocator() { return this.encryptionPublicKeyLocator; } + + public void setPostLogoutPath(String postLogoutPath) { + this.postLogoutPath = postLogoutPath; + } + + public String getPostLogoutPath() { + return postLogoutPath; + } + + public boolean isLogoutSessionRequired() { + return logoutSessionRequired; + } + + public void setLogoutSessionRequired(boolean logoutSessionRequired) { + this.logoutSessionRequired = logoutSessionRequired; + } + + public void setLogoutPath(String logoutPath) { + this.logoutPath = logoutPath; + } + + public String getLogoutCallbackPath() { + return logoutCallbackPath; + } + + public void setLogoutCallbackPath(String logoutCallbackPath) { + this.logoutCallbackPath = logoutCallbackPath; + } } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java index 43bebace9f6..fc80ef01358 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java @@ -25,6 +25,10 @@ import static org.wildfly.security.http.oidc.Oidc.AuthenticationRequestFormat.REQUEST_URI; import static org.wildfly.security.http.oidc.Oidc.SSLRequired; import static org.wildfly.security.http.oidc.Oidc.TokenStore; +import static org.wildfly.security.http.oidc.Oidc.LOGOUT_PATH; +import static org.wildfly.security.http.oidc.Oidc.LOGOUT_CALLBACK_PATH; +import static org.wildfly.security.http.oidc.Oidc.POST_LOGOUT_PATH; +import static org.wildfly.security.http.oidc.Oidc.LOGOUT_SESSION_REQUIRED; import java.io.IOException; import java.io.InputStream; @@ -195,6 +199,46 @@ protected OidcClientConfiguration internalBuild(final OidcJsonConfiguration oidc oidcClientConfiguration.setTokenSignatureAlgorithm(oidcJsonConfiguration.getTokenSignatureAlgorithm()); + String tmpLogoutPath = System.getProperty(LOGOUT_PATH); + if (tmpLogoutPath != null) { + if (isValidPath(tmpLogoutPath)) { + oidcClientConfiguration.setLogoutPath(tmpLogoutPath); + } else { + throw log.invalidLogoutPath(tmpLogoutPath, LOGOUT_PATH); + } + } + + + String tmpLogoutCallbackPath = System.getProperty(LOGOUT_CALLBACK_PATH); + if (tmpLogoutCallbackPath != null) { + if (isValidPath(tmpLogoutCallbackPath) + && !tmpLogoutCallbackPath.endsWith(oidcClientConfiguration.getLogoutPath())) { + oidcClientConfiguration.setLogoutCallbackPath(tmpLogoutCallbackPath); + } else { + if (!isValidPath(tmpLogoutCallbackPath)) { + throw log.invalidLogoutPath(tmpLogoutPath, LOGOUT_CALLBACK_PATH); + } else { + throw log.invalidLogoutCallbackPath(LOGOUT_CALLBACK_PATH, tmpLogoutCallbackPath, + LOGOUT_PATH, oidcClientConfiguration.getLogoutPath()); + } + } + } + + String tmpPostLogoutPath = System.getProperty(POST_LOGOUT_PATH); + if (tmpPostLogoutPath != null) { + if (isValidPath(tmpPostLogoutPath)) { + oidcClientConfiguration.setPostLogoutPath(tmpPostLogoutPath); + } else { + throw log.invalidLogoutPath(tmpLogoutPath, POST_LOGOUT_PATH); + } + } + + String tmpLogoutSessionRequired = System.getProperty(LOGOUT_SESSION_REQUIRED); + if (tmpLogoutSessionRequired != null) { + oidcClientConfiguration.setLogoutSessionRequired( + Boolean.valueOf(tmpLogoutSessionRequired)); + } + return oidcClientConfiguration; } @@ -236,4 +280,11 @@ public static OidcClientConfiguration build(OidcJsonConfiguration oidcJsonConfig return new OidcClientConfigurationBuilder().internalBuild(oidcJsonConfiguration); } + private boolean isValidPath(String path) { + String tmpPath = path.trim(); + if (tmpPath.length() > 1 && tmpPath.startsWith("/")) { + return true; + } + return false; + } } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/RequestAuthenticator.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/RequestAuthenticator.java index 87b18e0abef..f635b7e79a8 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/RequestAuthenticator.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/RequestAuthenticator.java @@ -55,6 +55,7 @@ public RequestAuthenticator(OidcHttpFacade facade, OidcClientConfiguration deplo public AuthOutcome authenticate() { AuthOutcome authenticate = doAuthenticate(); if (AuthOutcome.AUTHENTICATED.equals(authenticate) && !facade.isAuthorized()) { + log.trace("## RequestAutenticator.authenticate AUTHENTICATED but NOT Autorized"); return AuthOutcome.FAILED; } return authenticate; diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java index 4be6ffa9b8b..35adc45ad16 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java @@ -7,15 +7,14 @@ * 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 + * 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. + * 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.wildfly.security.http.oidc; import static org.junit.Assert.assertNotNull; @@ -54,8 +53,6 @@ public abstract class AbstractLogoutTest extends OidcBaseTest { private ElytronDispatcher dispatcher; private OidcClientConfiguration clientConfig; - static boolean IS_BACK_CHANNEL_TEST = false; - static final String BACK_CHANNEL_LOGOUT_URL = "/logout/callback"; @BeforeClass public static void onBeforeClass() { @@ -80,7 +77,7 @@ public void onBefore() throws Exception { OidcBaseTest.client = new MockWebServer(); OidcBaseTest.client.start(new InetSocketAddress(0).getAddress(), CLIENT_PORT); configureDispatcher(); - RealmRepresentation realm = KeycloakConfiguration.getRealmRepresentation(TEST_REALM, CLIENT_ID, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, CLIENT_APP, CONFIGURE_CLIENT_SCOPES); + RealmRepresentation realm = KeycloakConfiguration.getRealmRepresentation(TEST_REALM, CLIENT_ID, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, CLIENT_APP, false); realm.setAccessTokenLifespan(100); realm.setSsoSessionMaxLifespan(100); @@ -173,11 +170,7 @@ public MockResponse dispatch(RecordedRequest serverRequest) throws InterruptedEx MockResponse mockResponse = new MockResponse(); try { - if (IS_BACK_CHANNEL_TEST && serverRequest.getRequestUrl().toString().endsWith(BACK_CHANNEL_LOGOUT_URL)) { - currentRequest = new TestingHttpServerRequest(serverRequest, null); - } else { - currentRequest = new TestingHttpServerRequest(serverRequest, sessionScope); - } + currentRequest = new TestingHttpServerRequest(serverRequest, sessionScope); mechanism.evaluateRequest(currentRequest); diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java index 8540209498f..e4fed155139 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java @@ -29,25 +29,21 @@ import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebClient; import org.apache.http.HttpStatus; -import org.junit.BeforeClass; import org.junit.Test; import org.keycloak.representations.idm.ClientRepresentation; public class BackChannelLogoutTest extends AbstractLogoutTest { - @BeforeClass - public static void setUp() { - IS_BACK_CHANNEL_TEST = true; - } - @Override protected void doConfigureClient(ClientRepresentation client) { List redirectUris = client.getRedirectUris(); String redirectUri = redirectUris.get(0); + OidcClientConfiguration config = new OidcClientConfiguration(); client.setFrontchannelLogout(false); client.getAttributes().put("backchannel.logout.session.required", "true"); - client.getAttributes().put("backchannel.logout.url", rewriteHost(redirectUri) + BACK_CHANNEL_LOGOUT_URL); + client.getAttributes().put("backchannel.logout.url", rewriteHost(redirectUri) + + config.getLogoutCallbackPath()); } private static String rewriteHost(String redirectUri) { @@ -76,8 +72,8 @@ public void testRPInitiatedLogout() throws Exception { // logged out after finishing the redirections during frontchannel logout assertUserAuthenticated(); - webClient.getPage(getClientUrl() + "/logout"); - //assertUserAuthenticated(); + webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); + assertUserAuthenticated(); webClient.getPage(getClientUrl()); assertUserNotAuthenticated(); } diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java index dd4ca58c74b..5137d404130 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java @@ -50,7 +50,9 @@ protected void doConfigureClient(ClientRepresentation client) { List redirectUris = client.getRedirectUris(); String redirectUri = redirectUris.get(0); - client.getAttributes().put("frontchannel.logout.url", redirectUri + "/logout/callback"); + OidcClientConfiguration ocConfig = new OidcClientConfiguration(); + client.getAttributes().put("frontchannel.logout.url", redirectUri + + ocConfig.getLogoutCallbackPath()); } @Test @@ -71,14 +73,14 @@ public void testRPInitiatedLogout() throws Exception { // logged out after finishing the redirections during frontchannel logout assertUserAuthenticated(); - webClient.getPage(getClientUrl() + "/logout"); + webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); assertUserNotAuthenticated(); } @Test public void testRPInitiatedLogoutWithPostLogoutUri() throws Exception { OidcClientConfiguration oidcClientConfiguration = getClientConfig(); - oidcClientConfiguration.setPostLogoutUri("/post-logout"); + oidcClientConfiguration.setPostLogoutPath("/post-logout"); configureDispatcher(oidcClientConfiguration, new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/LogoutConfigurationOptionsTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/LogoutConfigurationOptionsTest.java new file mode 100644 index 00000000000..c6fb24cf754 --- /dev/null +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/LogoutConfigurationOptionsTest.java @@ -0,0 +1,118 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2024 Red Hat, Inc., and individual 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.wildfly.security.http.oidc; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/* + Verify that invalid logout config options values are flagged. + */ +public class LogoutConfigurationOptionsTest { + private OidcJsonConfiguration oidcJsonConfiguration; + + @Before + public void before() { + oidcJsonConfiguration = new OidcJsonConfiguration(); + // minimum required options + oidcJsonConfiguration.setRealm("realm"); + oidcJsonConfiguration.setResource("resource"); + oidcJsonConfiguration.setClientId("clientId"); + oidcJsonConfiguration.setAuthServerUrl("AuthServerUrl"); + } + + @After + public void after() { + System.clearProperty(Oidc.LOGOUT_PATH); + System.clearProperty(Oidc.LOGOUT_CALLBACK_PATH); + System.clearProperty(Oidc.POST_LOGOUT_PATH); + } + + @Test + public void testLogoutPath() { + + try { + System.setProperty(Oidc.LOGOUT_PATH, " "); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("Empty " +Oidc.LOGOUT_PATH+ " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.LOGOUT_PATH)); + } + + try { + System.setProperty(Oidc.LOGOUT_PATH, "/"); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("/ in " +Oidc.LOGOUT_PATH+ " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.LOGOUT_PATH)); + } + } + + @Test + public void testCallbackLogoutPath() { + + try { + System.setProperty(Oidc.LOGOUT_CALLBACK_PATH, " "); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("Empty " + Oidc.LOGOUT_CALLBACK_PATH + " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.LOGOUT_CALLBACK_PATH)); + } + + try { + System.setProperty(Oidc.LOGOUT_CALLBACK_PATH, "/"); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("/ in " + Oidc.LOGOUT_CALLBACK_PATH + " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.LOGOUT_CALLBACK_PATH)); + } + + try { + System.setProperty(Oidc.LOGOUT_PATH, "/mylogout"); + System.setProperty(Oidc.LOGOUT_CALLBACK_PATH, "/more/mylogout"); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("Identical paths is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().contains("ELY23072")); + } + } + + @Test + public void testPostLogoutPath() { + + try { + System.setProperty(Oidc.POST_LOGOUT_PATH, " "); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("Empty " +Oidc.POST_LOGOUT_PATH+ " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.POST_LOGOUT_PATH)); + } + + try { + System.setProperty(Oidc.POST_LOGOUT_PATH, "/"); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("/ in " + Oidc.POST_LOGOUT_PATH + " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.POST_LOGOUT_PATH)); + } + } +} diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java index b8a14b0d982..4f1028f829e 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2022 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -212,7 +212,7 @@ public MockResponse dispatch(RecordedRequest recordedRequest) throws Interrupted } protected static Dispatcher createAppResponse(HttpServerAuthenticationMechanism mechanism, int expectedStatusCode, String expectedLocation, String clientPageText, - Map attachments) { + Map sessionScopeAttachments) { return new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException { @@ -225,8 +225,8 @@ public MockResponse dispatch(RecordedRequest recordedRequest) throws Interrupted TestingHttpServerResponse response = request.getResponse(); assertEquals(expectedStatusCode, response.getStatusCode()); assertEquals(expectedLocation, response.getLocation()); - for (String key : request.getAttachments().keySet()) { - attachments.put(key, request.getAttachments().get(key)); + for (String key : request.getSessionScopeAttachments().keySet()) { + sessionScopeAttachments.put(key, request.getSessionScopeAttachments().get(key)); } return new MockResponse().setBody(clientPageText); } catch (Exception e) { @@ -240,7 +240,7 @@ public MockResponse dispatch(RecordedRequest recordedRequest) throws Interrupted } protected static Dispatcher createAppResponse(HttpServerAuthenticationMechanism mechanism, String clientPageText, - Map attachments, String tenant, boolean sameTenant) { + Map sessionScopeAttachments, String tenant, boolean sameTenant) { return new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException { @@ -248,7 +248,7 @@ public MockResponse dispatch(RecordedRequest recordedRequest) throws Interrupted if (path.contains("/" + CLIENT_APP + "/" + tenant)) { try { TestingHttpServerRequest request = new TestingHttpServerRequest(new String[0], - new URI(recordedRequest.getRequestUrl().toString()), attachments); + new URI(recordedRequest.getRequestUrl().toString()), sessionScopeAttachments); mechanism.evaluateRequest(request); TestingHttpServerResponse response = request.getResponse(); if (sameTenant) { @@ -279,6 +279,7 @@ static WebClient getWebClient() { WebClient webClient = new WebClient(); webClient.setCssErrorHandler(new SilentCssErrorHandler()); webClient.setJavaScriptErrorListener(new SilentJavaScriptErrorListener()); + webClient.getOptions().setMaxInMemory(50000 * 1024); return webClient; } diff --git a/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java b/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java index 9fe171c9214..962c13fef08 100644 --- a/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java +++ b/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2017 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -27,9 +27,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; -import java.net.MalformedURLException; import java.net.URI; -import java.net.URISyntaxException; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.cert.Certificate; @@ -157,10 +155,9 @@ protected static class TestingHttpServerRequest implements HttpServerRequest { private List cookies; private String requestMethod = "GET"; private Map> requestHeaders = new HashMap<>(); - private Map attachments = new HashMap<>(); - private Map scopes = new HashMap<>(); - private HttpScope sessionScope; private X500Principal testPrincipal = null; + private Map sessionScopeAttachments = new HashMap<>(); + private HttpScope sessionScope; public TestingHttpServerRequest(String[] authorization) { if (authorization != null) { @@ -188,14 +185,14 @@ public TestingHttpServerRequest(String[] authorization, URI requestURI) { this.cookies = new ArrayList<>(); } - public TestingHttpServerRequest(String[] authorization, URI requestURI, Map attachments) { + public TestingHttpServerRequest(String[] authorization, URI requestURI, Map sessionScopeAttachments) { if (authorization != null) { requestHeaders.put(AUTHORIZATION, Arrays.asList(authorization)); } this.remoteUser = null; this.requestURI = requestURI; this.cookies = new ArrayList<>(); - this.attachments = attachments; + this.sessionScopeAttachments = sessionScopeAttachments; } public TestingHttpServerRequest(String[] authorization, URI requestURI, List cookies) { @@ -216,10 +213,6 @@ public TestingHttpServerRequest(Map> requestHeaders, URI re } public TestingHttpServerRequest(String[] authorization, URI requestURI, String cookie) { - this(authorization, requestURI, cookie, null); - } - - public TestingHttpServerRequest(String[] authorization, URI requestURI, String cookie, HttpScope sessionScope) { if (authorization != null) { requestHeaders.put(AUTHORIZATION, Arrays.asList(authorization)); } @@ -231,14 +224,14 @@ public TestingHttpServerRequest(String[] authorization, URI requestURI, String c final String cookieValue = cookie.substring(cookie.indexOf('=') + 1); cookies.add(HttpServerCookie.getInstance(cookieName, cookieValue, null, -1, "/", false, 0, true)); } - this.sessionScope = sessionScope; } - public TestingHttpServerRequest(RecordedRequest serverRequest, HttpScope sessionScope) throws URISyntaxException { - this(new String[0], new URI(serverRequest.getRequestUrl().toString()), serverRequest.getHeader("Cookie"), sessionScope); - this.requestMethod = serverRequest.getMethod(); - this.body = serverRequest.getBody().readUtf8(); - this.contentType = serverRequest.getHeader("Content-Type"); + public TestingHttpServerRequest(RecordedRequest request, HttpScope sessionScope) { + this(new String[0], request.getRequestUrl().uri(), request.getHeader("Cookie")); + this.requestMethod = request.getMethod(); + this.body = request.getBody().readUtf8(); + this.contentType = request.getHeader("Content-Type"); + this.sessionScope = sessionScope; } public Status getResult() { @@ -312,11 +305,7 @@ public URI getRequestURI() { } public String getRequestPath() { - try { - return requestURI.toURL().getPath(); - } catch (MalformedURLException cause) { - throw new RuntimeException("Mal-formed request URL", cause); - } + return requestURI.getPath(); } public Map> getParameters() { @@ -371,52 +360,48 @@ public boolean resumeRequest() { public HttpScope getScope(Scope scope) { if (scope.equals(Scope.SSL_SESSION)) { return null; - } - - if (Scope.SESSION.equals(scope) && sessionScope != null) { + } else if (sessionScope != null) { return sessionScope; } - HttpScope httpScope = scopes.get(scope); + return new HttpScope() { - if (httpScope == null) { - return new HttpScope() { - - @Override - public boolean exists() { - return true; - } + @Override + public boolean exists() { + return true; + } - @Override - public boolean create() { - return false; - } + @Override + public boolean create() { + return false; + } - @Override - public boolean supportsAttachments() { - return true; - } + @Override + public boolean supportsAttachments() { + return true; + } - @Override - public boolean supportsInvalidation() { - return true; - } + @Override + public boolean supportsInvalidation() { + return false; + } - @Override - public void setAttachment(String key, Object value) { - attachments.put(key, value); + @Override + public void setAttachment(String key, Object value) { + if (scope.equals(Scope.SESSION)) { + sessionScopeAttachments.put(key, value); } + } - @Override - public Object getAttachment(String key) { - return attachments.get(key); + @Override + public Object getAttachment(String key) { + if (scope.equals(Scope.SESSION)) { + return sessionScopeAttachments.get(key); + } else { + return null; } - - }; - } - scopes.put(scope, httpScope); - - return httpScope; + } + }; } public Collection getScopeIds(Scope scope) { @@ -424,10 +409,7 @@ public Collection getScopeIds(Scope scope) { } public HttpScope getScope(Scope scope, String id) { - if (Scope.SESSION.equals(scope) && sessionScope != null) { - return sessionScope; - } - return scopes.get(scope); + throw new IllegalStateException(); } public void setRemoteUser(String remoteUser) { @@ -439,8 +421,8 @@ public String getRemoteUser() { return remoteUser; } - public Map getAttachments() { - return attachments; + public Map getSessionScopeAttachments() { + return sessionScopeAttachments; } } From 509a811e2a976bd6d9aaa1f2c4af12e2406b821f Mon Sep 17 00:00:00 2001 From: Farah Juma Date: Fri, 29 Nov 2024 17:12:02 -0500 Subject: [PATCH 07/16] [ELY-2534] Restore the changes made so that back-channel logout handling doesn't rely on an active session and ensure the session will get invalidated appropriately upon subsequent requests --- .../oidc/AuthenticatedActionsHandler.java | 5 -- .../security/http/oidc/LogoutHandler.java | 51 ++++++++----------- .../oidc/OidcAuthenticationMechanism.java | 9 +++- 3 files changed, 29 insertions(+), 36 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java index 305d825570d..8197c38a92c 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java @@ -37,7 +37,6 @@ */ public class AuthenticatedActionsHandler { - private static LogoutHandler logoutHandler = new LogoutHandler(); private OidcClientConfiguration deployment; private OidcHttpFacade facade; @@ -55,10 +54,6 @@ public boolean handledRequest() { return true; } - if (logoutHandler.tryLogout(facade)) { - return true; - } - return false; } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index c00d53aa4d8..92faf977576 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -61,7 +61,6 @@ protected boolean removeEldestEntry(Map.Entry e boolean tryLogout(OidcHttpFacade facade) { RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); - if (securityContext == null) { // no active session return false; @@ -80,8 +79,14 @@ boolean tryLogout(OidcHttpFacade facade) { } if (isLogoutCallbackPath(facade)) { - handleLogoutRequest(facade); - return true; + if (isFrontChannel(facade)) { + handleFrontChannelLogoutRequest(facade); + return true; + } else { + // we have an active session, should have received a GET logout request + facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); + facade.authenticationFailed(); + } } return false; @@ -89,12 +94,12 @@ boolean tryLogout(OidcHttpFacade facade) { private boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); + IDToken idToken = securityContext.getIDToken(); if (idToken == null) { return false; } - return sessionsMarkedForInvalidation.remove(idToken.getSid()) != null; } @@ -123,20 +128,17 @@ private void redirectEndSessionEndpoint(OidcHttpFacade facade) { facade.getResponse().setHeader(HttpConstants.LOCATION, logoutUri); } - private void handleLogoutRequest(OidcHttpFacade facade) { - if (isFrontChannel(facade)) { - handleFrontChannelLogoutRequest(facade); - } else if (isBackChannel(facade)) { - handleBackChannelLogoutRequest(facade); - } else { - // logout requests should arrive either as a HTTP GET or POST - facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); - facade.authenticationFailed(); + boolean tryBackChannelLogout(OidcHttpFacade facade) { + if (isLogoutCallbackPath(facade)) { + if (isBackChannel(facade)) { + handleBackChannelLogoutRequest(facade); + return true; + } } + return false; } private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { - RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); String logoutToken = facade.getRequest().getFirstParam(LOGOUT_TOKEN_PARAM); TokenValidator tokenValidator = TokenValidator.builder(facade.getOidcClientConfiguration()) .setSkipExpirationValidator() @@ -169,7 +171,7 @@ private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { } log.debug("Marking session for invalidation during back-channel logout"); - sessionsMarkedForInvalidation.put(sessionId, securityContext.getOidcClientConfiguration()); + sessionsMarkedForInvalidation.put(sessionId, facade.getOidcClientConfiguration()); } private void handleFrontChannelLogoutRequest(OidcHttpFacade facade) { @@ -213,9 +215,8 @@ private String getRedirectUri(OidcHttpFacade facade) { return uri; } - private boolean isLogoutCallbackPath(OidcHttpFacade facade) { + boolean isLogoutCallbackPath(OidcHttpFacade facade) { String path = facade.getRequest().getRelativePath(); - String xx = getLogoutCallbackPath(facade); // rls debug only return path.endsWith(getLogoutCallbackPath(facade)); } @@ -225,17 +226,7 @@ private boolean isRpInitiatedLogoutPath(OidcHttpFacade facade) { } private boolean isSessionRequiredOnLogout(OidcHttpFacade facade) { - return getOidcClientConfiguration(facade).isSessionRequiredOnLogout(); - } - - private OidcClientConfiguration getOidcClientConfiguration(OidcHttpFacade facade) { - RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); - - if (securityContext == null) { - return null; - } - - return securityContext.getOidcClientConfiguration(); + return facade.getOidcClientConfiguration().isSessionRequiredOnLogout(); } private RefreshableOidcSecurityContext getSecurityContext(OidcHttpFacade facade) { @@ -251,10 +242,10 @@ private RefreshableOidcSecurityContext getSecurityContext(OidcHttpFacade facade) } private String getLogoutPath(OidcHttpFacade facade) { - return getOidcClientConfiguration(facade).getLogoutPath(); + return facade.getOidcClientConfiguration().getLogoutPath(); } private String getLogoutCallbackPath(OidcHttpFacade facade) { - return getOidcClientConfiguration(facade).getLogoutCallbackPath(); + return facade.getOidcClientConfiguration().getLogoutCallbackPath(); } private boolean isBackChannel(OidcHttpFacade facade) { diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java index fecde05ee5d..29c4ecb743b 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java @@ -87,7 +87,7 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication AuthOutcome outcome = authenticator.authenticate(); if (AuthOutcome.AUTHENTICATED.equals(outcome)) { if (new AuthenticatedActionsHandler(oidcClientConfiguration, httpFacade).handledRequest() - ) { + || logoutHandler.tryLogout(httpFacade)) { httpFacade.authenticationInProgress(); } else { httpFacade.authenticationComplete(); @@ -95,6 +95,13 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication return; } + if (AuthOutcome.NOT_ATTEMPTED.equals(outcome)) { + if (logoutHandler.tryBackChannelLogout(httpFacade)) { + httpFacade.authenticationInProgress(); + return; + } + } + AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { httpFacade.noAuthenticationInProgress(challenge); From 77d49117816c6645645ada110313b22e594b5342 Mon Sep 17 00:00:00 2001 From: Farah Juma Date: Tue, 3 Dec 2024 12:25:57 -0500 Subject: [PATCH 08/16] [ELY-2534] Fix back-channel logout by moving the isSessionMarkedForInvalidation check to before the authenticator#authenticate call and update the check to not remove the session from the map to ensure that the user gets logged out from any other apps too --- .../security/http/oidc/LogoutHandler.java | 21 +++++++++---------- .../oidc/OidcAuthenticationMechanism.java | 5 +++++ 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index 92faf977576..361991eab5a 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -29,6 +29,8 @@ import org.apache.http.client.utils.URIBuilder; import org.jose4j.jwt.JwtClaims; import org.wildfly.security.http.HttpConstants; +import org.wildfly.security.http.HttpScope; +import org.wildfly.security.http.Scope; import org.wildfly.security.http.oidc.OidcHttpFacade.Request; /** @@ -66,13 +68,6 @@ boolean tryLogout(OidcHttpFacade facade) { return false; } - if (isSessionMarkedForInvalidation(facade)) { - // session marked for invalidation, invalidate it - log.debug("Invalidating pending logout session"); - facade.getTokenStore().logout(false); - return true; - } - if (isRpInitiatedLogoutPath(facade)) { redirectEndSessionEndpoint(facade); return true; @@ -92,15 +87,19 @@ boolean tryLogout(OidcHttpFacade facade) { return false; } - private boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { - RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); - + boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { + HttpScope session = facade.getScope(Scope.SESSION); + if (session == null || ! session.exists()) return false; + RefreshableOidcSecurityContext securityContext = (RefreshableOidcSecurityContext) session.getAttachment(OidcSecurityContext.class.getName()); + if (securityContext == null) { + return false; + } IDToken idToken = securityContext.getIDToken(); if (idToken == null) { return false; } - return sessionsMarkedForInvalidation.remove(idToken.getSid()) != null; + return sessionsMarkedForInvalidation.containsKey(idToken.getSid()); } private void redirectEndSessionEndpoint(OidcHttpFacade facade) { diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java index 29c4ecb743b..1a4963ea6e1 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java @@ -76,6 +76,11 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication } RequestAuthenticator authenticator = createRequestAuthenticator(httpFacade, oidcClientConfiguration); + if (logoutHandler.isSessionMarkedForInvalidation(httpFacade)) { + // session marked for invalidation, invalidate it + log.debug("Invalidating pending logout session"); + httpFacade.getTokenStore().logout(false); + } httpFacade.getTokenStore().checkCurrentToken(); if ((oidcClientConfiguration.getAuthServerBaseUrl() != null && keycloakPreActions(httpFacade, oidcClientConfiguration)) || preflightCors(httpFacade, oidcClientConfiguration)) { From 3aebc41a8142a29f4327587ec53300ad6e0ba0f6 Mon Sep 17 00:00:00 2001 From: Farah Juma Date: Tue, 3 Dec 2024 17:12:36 -0500 Subject: [PATCH 09/16] [ELY-2534] Use the client ID and sid from the ID token in the key for the sessionsMarkedForInvalidation map --- .../org/wildfly/security/http/oidc/LogoutHandler.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index 361991eab5a..ac33649bb93 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -42,6 +42,7 @@ final class LogoutHandler { public static final String ID_TOKEN_HINT_PARAM = "id_token_hint"; private static final String LOGOUT_TOKEN_PARAM = "logout_token"; private static final String LOGOUT_TOKEN_TYPE = "Logout"; + private static final String CLIENT_ID_SID_SEPARATOR = "-"; public static final String SID = "sid"; public static final String ISS = "iss"; @@ -99,7 +100,7 @@ boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { if (idToken == null) { return false; } - return sessionsMarkedForInvalidation.containsKey(idToken.getSid()); + return sessionsMarkedForInvalidation.remove(getSessionKey(facade, idToken.getSid())) != null; } private void redirectEndSessionEndpoint(OidcHttpFacade facade) { @@ -170,7 +171,11 @@ private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { } log.debug("Marking session for invalidation during back-channel logout"); - sessionsMarkedForInvalidation.put(sessionId, facade.getOidcClientConfiguration()); + sessionsMarkedForInvalidation.put(getSessionKey(facade, sessionId), facade.getOidcClientConfiguration()); + } + + private String getSessionKey(OidcHttpFacade facade, String sessionId) { + return facade.getOidcClientConfiguration().getClientId() + CLIENT_ID_SID_SEPARATOR + sessionId; } private void handleFrontChannelLogoutRequest(OidcHttpFacade facade) { From ebdeafed2aea641a57cc8a6d0b38338ef1c61466 Mon Sep 17 00:00:00 2001 From: R Searls Date: Thu, 7 Nov 2024 16:30:48 -0500 Subject: [PATCH 10/16] [ELY-2534] OIDC logout support --- .../oidc/AuthenticatedActionsHandler.java | 2 +- .../http/oidc/AuthenticationError.java | 4 +- .../security/http/oidc/ElytronMessages.java | 7 ++ .../security/http/oidc/LogoutHandler.java | 102 ++++++++------- .../org/wildfly/security/http/oidc/Oidc.java | 4 + .../oidc/OidcAuthenticationMechanism.java | 10 +- .../http/oidc/OidcClientConfiguration.java | 65 +++++----- .../oidc/OidcClientConfigurationBuilder.java | 54 ++++++++ .../http/oidc/OidcRequestAuthenticator.java | 1 - .../http/oidc/OidcSessionTokenStore.java | 17 ++- .../http/oidc/AbstractLogoutTest.java | 30 ++--- .../http/oidc/BackChannelLogoutTest.java | 17 +-- .../http/oidc/FrontChannelLogoutTest.java | 11 +- .../oidc/LogoutConfigurationOptionsTest.java | 118 ++++++++++++++++++ .../security/http/oidc/OidcBaseTest.java | 13 +- .../http/impl/AbstractBaseHttpTest.java | 113 ++++++++--------- 16 files changed, 378 insertions(+), 190 deletions(-) create mode 100644 http/oidc/src/test/java/org/wildfly/security/http/oidc/LogoutConfigurationOptionsTest.java diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java index d754642db81..8197c38a92c 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticatedActionsHandler.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2021 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java index cc99a48d126..789e1f4b4d3 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java @@ -36,7 +36,9 @@ public enum Reason { INVALID_TOKEN, STALE_TOKEN, NO_AUTHORIZATION_HEADER, - NO_QUERY_PARAMETER_ACCESS_TOKEN + NO_QUERY_PARAMETER_ACCESS_TOKEN, + NO_SESSION_ID, + METHOD_NOT_ALLOWED } private Reason reason; diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java index e836cc3b468..ce3d976dcdd 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java @@ -278,5 +278,12 @@ interface ElytronMessages extends BasicLogger { @Message(id = 23070, value = "Authentication request format must be one of the following: oauth2, request, request_uri.") RuntimeException invalidAuthenticationRequestFormat(); + + @Message(id = 23071, value = "%s is not a valid value for %s") + RuntimeException invalidLogoutPath(String pathValue, String pathName); + + @Message(id = 23072, value = "The end substring of %s: %s can not be identical to %s: %s") + RuntimeException invalidLogoutCallbackPath(String callbackPathTitle, String callbacPathkValue, + String logoutPathTitle, String logoutPathValue); } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index 68ae38f7ac4..cda713dc61d 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -29,6 +29,8 @@ import org.apache.http.client.utils.URIBuilder; import org.jose4j.jwt.JwtClaims; import org.wildfly.security.http.HttpConstants; +import org.wildfly.security.http.HttpScope; +import org.wildfly.security.http.Scope; import org.wildfly.security.http.oidc.OidcHttpFacade.Request; /** @@ -36,12 +38,13 @@ */ final class LogoutHandler { - private static final String POST_LOGOUT_REDIRECT_URI_PARAM = "post_logout_redirect_uri"; - private static final String ID_TOKEN_HINT_PARAM = "id_token_hint"; + public static final String POST_LOGOUT_REDIRECT_URI_PARAM = "post_logout_redirect_uri"; + public static final String ID_TOKEN_HINT_PARAM = "id_token_hint"; private static final String LOGOUT_TOKEN_PARAM = "logout_token"; private static final String LOGOUT_TOKEN_TYPE = "Logout"; - private static final String SID = "sid"; - private static final String ISS = "iss"; + private static final String CLIENT_ID_SID_SEPARATOR = "-"; + public static final String SID = "sid"; + public static final String ISS = "iss"; /** * A bounded map to store sessions marked for invalidation after receiving logout requests through the back-channel @@ -60,27 +63,24 @@ protected boolean removeEldestEntry(Map.Entry e }); boolean tryLogout(OidcHttpFacade facade) { + log.trace("tryLogout entered"); RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); - if (securityContext == null) { // no active session + log.trace("tryLogout securityContext == null"); return false; } - if (isSessionMarkedForInvalidation(facade)) { - // session marked for invalidation, invalidate it - log.debug("Invalidating pending logout session"); - facade.getTokenStore().logout(false); - return true; - } - - if (isRpInitiatedLogoutUri(facade)) { + if (isRpInitiatedLogoutPath(facade)) { + log.trace("isRpInitiatedLogoutPath"); redirectEndSessionEndpoint(facade); return true; } - if (isLogoutCallbackUri(facade)) { + if (isLogoutCallbackPath(facade)) { + log.trace("isLogoutCallbackPath"); if (isFrontChannel(facade)) { + log.trace("isFrontChannel"); handleFrontChannelLogoutRequest(facade); return true; } else { @@ -89,50 +89,41 @@ boolean tryLogout(OidcHttpFacade facade) { facade.authenticationFailed(); } } - return false; } - boolean tryBackChannelLogout(OidcHttpFacade facade) { - if (isLogoutCallbackUri(facade)) { - if (isBackChannel(facade)) { - handleBackChannelLogoutRequest(facade); - return true; - } else { - // no active session, should have received a POST logout request - facade.getResponse().setStatus(HttpStatus.SC_METHOD_NOT_ALLOWED); - facade.authenticationFailed(); - } + boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { + HttpScope session = facade.getScope(Scope.SESSION); + if (session == null || ! session.exists()) return false; + RefreshableOidcSecurityContext securityContext = (RefreshableOidcSecurityContext) session.getAttachment(OidcSecurityContext.class.getName()); + if (securityContext == null) { + return false; } - return false; - } - - private boolean isSessionMarkedForInvalidation(OidcHttpFacade facade) { - RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); IDToken idToken = securityContext.getIDToken(); if (idToken == null) { return false; } - - return sessionsMarkedForInvalidation.remove(idToken.getSid()) != null; + return sessionsMarkedForInvalidation.remove(getSessionKey(facade, idToken.getSid())) != null; } private void redirectEndSessionEndpoint(OidcHttpFacade facade) { RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); OidcClientConfiguration clientConfiguration = securityContext.getOidcClientConfiguration(); + String logoutUri; try { URIBuilder redirectUriBuilder = new URIBuilder(clientConfiguration.getEndSessionEndpointUrl()) .addParameter(ID_TOKEN_HINT_PARAM, securityContext.getIDTokenString()); - String postLogoutUri = clientConfiguration.getPostLogoutUri(); - - if (postLogoutUri != null) { - redirectUriBuilder.addParameter(POST_LOGOUT_REDIRECT_URI_PARAM, getRedirectUri(facade) + postLogoutUri); + String postLogoutPath = clientConfiguration.getPostLogoutPath(); + if (postLogoutPath != null) { + redirectUriBuilder.addParameter(POST_LOGOUT_REDIRECT_URI_PARAM, + getRedirectUri(facade) + postLogoutPath); } logoutUri = redirectUriBuilder.build().toString(); + log.trace("redirectEndSessionEndpoint path: " + redirectUriBuilder.toString()); } catch (URISyntaxException e) { throw new RuntimeException(e); } @@ -142,6 +133,19 @@ private void redirectEndSessionEndpoint(OidcHttpFacade facade) { facade.getResponse().setHeader(HttpConstants.LOCATION, logoutUri); } + boolean tryBackChannelLogout(OidcHttpFacade facade) { + log.trace("tryBackChannelLogout entered"); + if (isLogoutCallbackPath(facade)) { + log.trace("isLogoutCallbackPath"); + if (isBackChannel(facade)) { + log.trace("isBackChannel"); + handleBackChannelLogoutRequest(facade); + return true; + } + } + return false; + } + private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { String logoutToken = facade.getRequest().getFirstParam(LOGOUT_TOKEN_PARAM); TokenValidator tokenValidator = TokenValidator.builder(facade.getOidcClientConfiguration()) @@ -175,7 +179,11 @@ private void handleBackChannelLogoutRequest(OidcHttpFacade facade) { } log.debug("Marking session for invalidation during back-channel logout"); - sessionsMarkedForInvalidation.put(sessionId, facade.getOidcClientConfiguration()); + sessionsMarkedForInvalidation.put(getSessionKey(facade, sessionId), facade.getOidcClientConfiguration()); + } + + private String getSessionKey(OidcHttpFacade facade, String sessionId) { + return facade.getOidcClientConfiguration().getClientId() + CLIENT_ID_SID_SEPARATOR + sessionId; } private void handleFrontChannelLogoutRequest(OidcHttpFacade facade) { @@ -210,8 +218,7 @@ private String getRedirectUri(OidcHttpFacade facade) { if (uri.indexOf('?') != -1) { uri = uri.substring(0, uri.indexOf('?')); } - - int logoutPathIndex = uri.indexOf(getLogoutUri(facade)); + int logoutPathIndex = uri.indexOf(getLogoutPath(facade)); if (logoutPathIndex != -1) { uri = uri.substring(0, logoutPathIndex); @@ -220,14 +227,14 @@ private String getRedirectUri(OidcHttpFacade facade) { return uri; } - private boolean isLogoutCallbackUri(OidcHttpFacade facade) { + private boolean isLogoutCallbackPath(OidcHttpFacade facade) { String path = facade.getRequest().getRelativePath(); - return path.endsWith(getLogoutCallbackUri(facade)); + return path.endsWith(getLogoutCallbackPath(facade)); } - private boolean isRpInitiatedLogoutUri(OidcHttpFacade facade) { + private boolean isRpInitiatedLogoutPath(OidcHttpFacade facade) { String path = facade.getRequest().getRelativePath(); - return path.endsWith(getLogoutUri(facade)); + return path.endsWith(getLogoutPath(facade)); } private boolean isSessionRequiredOnLogout(OidcHttpFacade facade) { @@ -246,12 +253,11 @@ private RefreshableOidcSecurityContext getSecurityContext(OidcHttpFacade facade) return securityContext; } - private String getLogoutUri(OidcHttpFacade facade) { - return facade.getOidcClientConfiguration().getLogoutUrl(); + private String getLogoutPath(OidcHttpFacade facade) { + return facade.getOidcClientConfiguration().getLogoutPath(); } - - private String getLogoutCallbackUri(OidcHttpFacade facade) { - return facade.getOidcClientConfiguration().getLogoutCallbackUrl(); + private String getLogoutCallbackPath(OidcHttpFacade facade) { + return facade.getOidcClientConfiguration().getLogoutCallbackPath(); } private boolean isBackChannel(OidcHttpFacade facade) { diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/Oidc.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/Oidc.java index c6b38c9ef4d..cbff7723668 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/Oidc.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/Oidc.java @@ -173,6 +173,10 @@ public class Oidc { public static final String CONFIDENTIAL_PORT = "confidential-port"; public static final String ENABLE_BASIC_AUTH = "enable-basic-auth"; public static final String PROVIDER_URL = "provider-url"; + public static final String LOGOUT_PATH = "logout-path"; + public static final String LOGOUT_CALLBACK_PATH = "logout-callback-path"; + public static final String POST_LOGOUT_PATH = "post-logout-path"; + public static final String LOGOUT_SESSION_REQUIRED = "logout-session-required"; /** * Bearer token pattern. diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java index 602cf23d3b2..a33d6b261d9 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java @@ -42,6 +42,7 @@ final class OidcAuthenticationMechanism implements HttpServerAuthenticationMechanism { private static LogoutHandler logoutHandler = new LogoutHandler(); + private final Map properties; private final CallbackHandler callbackHandler; private final OidcClientContext oidcClientContext; @@ -59,6 +60,7 @@ public String getMechanismName() { @Override public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { + log.debug("evaluateRequest uri: " + request.getRequestURI().toString()); OidcClientContext oidcClientContext = getOidcClientContext(request); if (oidcClientContext == null) { log.debugf("Ignoring request for path [%s] from mechanism [%s]. No client configuration context found.", request.getRequestURI(), getMechanismName()); @@ -74,6 +76,11 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication } RequestAuthenticator authenticator = createRequestAuthenticator(httpFacade, oidcClientConfiguration); + if (logoutHandler.isSessionMarkedForInvalidation(httpFacade)) { + // session marked for invalidation, invalidate it + log.debug("Invalidating pending logout session"); + httpFacade.getTokenStore().logout(false); + } httpFacade.getTokenStore().checkCurrentToken(); if ((oidcClientConfiguration.getAuthServerBaseUrl() != null && keycloakPreActions(httpFacade, oidcClientConfiguration)) || preflightCors(httpFacade, oidcClientConfiguration)) { @@ -84,7 +91,8 @@ public void evaluateRequest(HttpServerRequest request) throws HttpAuthentication AuthOutcome outcome = authenticator.authenticate(); if (AuthOutcome.AUTHENTICATED.equals(outcome)) { - if (new AuthenticatedActionsHandler(oidcClientConfiguration, httpFacade).handledRequest() || logoutHandler.tryLogout(httpFacade)) { + if (new AuthenticatedActionsHandler(oidcClientConfiguration, httpFacade).handledRequest() + || logoutHandler.tryLogout(httpFacade)) { httpFacade.authenticationInProgress(); } else { httpFacade.authenticationComplete(); diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java index e7bc0943ec7..0fc0334107c 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfiguration.java @@ -143,14 +143,12 @@ public enum RelativeUrlsUsed { protected String requestObjectSigningKeyAlias; protected String requestObjectSigningKeyStoreType; protected JWKEncPublicKeyLocator encryptionPublicKeyLocator; + private boolean logoutSessionRequired = true; - private String postLogoutUri; - + private String postLogoutPath; private boolean sessionRequiredOnLogout = true; - - private String logoutUrl = "/logout"; - - private String logoutCallbackUrl = "/logout/callback"; + private String logoutPath = "/logout"; + private String logoutCallbackPath = "/logout/callback"; private int logoutSessionWaitingLimit = 100; @@ -338,6 +336,10 @@ public String getEndSessionEndpointUrl() { return endSessionEndpointUrl; } + public String getLogoutPath() { + return logoutPath; + } + public String getAccountUrl() { resolveUrls(); return accountUrl; @@ -702,14 +704,6 @@ public String getTokenSignatureAlgorithm() { return tokenSignatureAlgorithm; } - public void setPostLogoutUri(String postLogoutUri) { - this.postLogoutUri = postLogoutUri; - } - - public String getPostLogoutUri() { - return postLogoutUri; - } - public boolean isSessionRequiredOnLogout() { return sessionRequiredOnLogout; } @@ -718,21 +712,6 @@ public void setSessionRequiredOnLogout(boolean sessionRequiredOnLogout) { this.sessionRequiredOnLogout = sessionRequiredOnLogout; } - public String getLogoutUrl() { - return logoutUrl; - } - - public void setLogoutUrl(String logoutUrl) { - this.logoutUrl = logoutUrl; - } - - public String getLogoutCallbackUrl() { - return logoutCallbackUrl; - } - - public void setLogoutCallbackUrl(String logoutCallbackUrl) { - this.logoutCallbackUrl = logoutCallbackUrl; - } public int getLogoutSessionWaitingLimit() { return logoutSessionWaitingLimit; } @@ -828,4 +807,32 @@ public void setEncryptionPublicKeyLocator(JWKEncPublicKeyLocator publicKeySetExt public JWKEncPublicKeyLocator getEncryptionPublicKeyLocator() { return this.encryptionPublicKeyLocator; } + + public void setPostLogoutPath(String postLogoutPath) { + this.postLogoutPath = postLogoutPath; + } + + public String getPostLogoutPath() { + return postLogoutPath; + } + + public boolean isLogoutSessionRequired() { + return logoutSessionRequired; + } + + public void setLogoutSessionRequired(boolean logoutSessionRequired) { + this.logoutSessionRequired = logoutSessionRequired; + } + + public void setLogoutPath(String logoutPath) { + this.logoutPath = logoutPath; + } + + public String getLogoutCallbackPath() { + return logoutCallbackPath; + } + + public void setLogoutCallbackPath(String logoutCallbackPath) { + this.logoutCallbackPath = logoutCallbackPath; + } } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java index 43bebace9f6..52d59e13819 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java @@ -25,6 +25,10 @@ import static org.wildfly.security.http.oidc.Oidc.AuthenticationRequestFormat.REQUEST_URI; import static org.wildfly.security.http.oidc.Oidc.SSLRequired; import static org.wildfly.security.http.oidc.Oidc.TokenStore; +import static org.wildfly.security.http.oidc.Oidc.LOGOUT_PATH; +import static org.wildfly.security.http.oidc.Oidc.LOGOUT_CALLBACK_PATH; +import static org.wildfly.security.http.oidc.Oidc.POST_LOGOUT_PATH; +import static org.wildfly.security.http.oidc.Oidc.LOGOUT_SESSION_REQUIRED; import java.io.IOException; import java.io.InputStream; @@ -195,6 +199,49 @@ protected OidcClientConfiguration internalBuild(final OidcJsonConfiguration oidc oidcClientConfiguration.setTokenSignatureAlgorithm(oidcJsonConfiguration.getTokenSignatureAlgorithm()); + String tmpLogoutPath = System.getProperty(LOGOUT_PATH); + log.debug("sysProp LOGOUT_PATH: " + (tmpLogoutPath == null ? "NULL" : tmpLogoutPath)); + if (tmpLogoutPath != null) { + if (isValidPath(tmpLogoutPath)) { + oidcClientConfiguration.setLogoutPath(tmpLogoutPath); + } else { + throw log.invalidLogoutPath(tmpLogoutPath, LOGOUT_PATH); + } + } + + + String tmpLogoutCallbackPath = System.getProperty(LOGOUT_CALLBACK_PATH); + log.debug("sysProp LOGOUT_CALLBACK_PATH: " + (tmpLogoutCallbackPath == null ? "NULL" : tmpLogoutCallbackPath)); + if (tmpLogoutCallbackPath != null) { + if (isValidPath(tmpLogoutCallbackPath) + && !tmpLogoutCallbackPath.endsWith(oidcClientConfiguration.getLogoutPath())) { + oidcClientConfiguration.setLogoutCallbackPath(tmpLogoutCallbackPath); + } else { + if (!isValidPath(tmpLogoutCallbackPath)) { + throw log.invalidLogoutPath(tmpLogoutPath, LOGOUT_CALLBACK_PATH); + } else { + throw log.invalidLogoutCallbackPath(LOGOUT_CALLBACK_PATH, tmpLogoutCallbackPath, + LOGOUT_PATH, oidcClientConfiguration.getLogoutPath()); + } + } + } + + String tmpPostLogoutPath = System.getProperty(POST_LOGOUT_PATH); + log.debug("sysProp POST_LOGOUT_PATH: " + (tmpPostLogoutPath == null ? "NULL" : tmpPostLogoutPath)); + if (tmpPostLogoutPath != null) { + if (isValidPath(tmpPostLogoutPath)) { + oidcClientConfiguration.setPostLogoutPath(tmpPostLogoutPath); + } else { + throw log.invalidLogoutPath(tmpLogoutPath, POST_LOGOUT_PATH); + } + } + + String tmpLogoutSessionRequired = System.getProperty(LOGOUT_SESSION_REQUIRED); + if (tmpLogoutSessionRequired != null) { + oidcClientConfiguration.setLogoutSessionRequired( + Boolean.valueOf(tmpLogoutSessionRequired)); + } + return oidcClientConfiguration; } @@ -236,4 +283,11 @@ public static OidcClientConfiguration build(OidcJsonConfiguration oidcJsonConfig return new OidcClientConfigurationBuilder().internalBuild(oidcJsonConfiguration); } + private boolean isValidPath(String path) { + String tmpPath = path.trim(); + if (tmpPath.length() > 1 && tmpPath.startsWith("/")) { + return true; + } + return false; + } } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcRequestAuthenticator.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcRequestAuthenticator.java index 5ef5c26122e..0588c165682 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcRequestAuthenticator.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcRequestAuthenticator.java @@ -184,7 +184,6 @@ protected String getCode() { protected String getRedirectUri(String state) { String url = getRequestUrl(); log.debugf("callback uri: %s", url); - try { if (! facade.getRequest().isSecure() && deployment.getSSLRequired().isRequired(facade.getRequest().getRemoteAddr())) { int port = getSSLRedirectPort(); diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcSessionTokenStore.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcSessionTokenStore.java index cb6206177cd..6762afc0f47 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcSessionTokenStore.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcSessionTokenStore.java @@ -45,21 +45,29 @@ public OidcSessionTokenStore(OidcHttpFacade httpFacade) { @Override public void checkCurrentToken() { HttpScope session = httpFacade.getScope(Scope.SESSION); - if (session == null || ! session.exists()) return; + if (session == null || ! session.exists()) { + return; + } RefreshableOidcSecurityContext securityContext = (RefreshableOidcSecurityContext) session.getAttachment(OidcSecurityContext.class.getName()); - if (securityContext == null) return; + if (securityContext == null) { + return; + } // just in case session got serialized if (securityContext.getOidcClientConfiguration() == null) { securityContext.setCurrentRequestInfo(httpFacade.getOidcClientConfiguration(), this); } - if (securityContext.isActive() && ! securityContext.getOidcClientConfiguration().isAlwaysRefreshToken()) return; + if (securityContext.isActive() && ! securityContext.getOidcClientConfiguration().isAlwaysRefreshToken()) { + return; + } // FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will // not be updated boolean success = securityContext.refreshToken(false); - if (success && securityContext.isActive()) return; + if (success && securityContext.isActive()) { + return; + } // Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session session.setAttachment(OidcSecurityContext.class.getName(), null); @@ -132,7 +140,6 @@ public void saveAccountInfo(OidcAccount account) { } }); } - session.setAttachment(OidcAccount.class.getName(), account); session.setAttachment(OidcSecurityContext.class.getName(), account.getOidcSecurityContext()); diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java index fc139a4a2ba..85a270cfd82 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java @@ -7,15 +7,14 @@ * 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 + * 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. + * 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.wildfly.security.http.oidc; import static org.junit.Assert.assertNotNull; @@ -54,8 +53,6 @@ public abstract class AbstractLogoutTest extends OidcBaseTest { private ElytronDispatcher dispatcher; private OidcClientConfiguration clientConfig; - static boolean IS_BACK_CHANNEL_TEST = false; - static final String BACK_CHANNEL_LOGOUT_URL = "/logout/callback"; @BeforeClass public static void onBeforeClass() { @@ -76,11 +73,13 @@ public static void generalCleanup() { } @Before - public void onBefore() throws IOException { + public void onBefore() throws Exception { OidcBaseTest.client = new MockWebServer(); OidcBaseTest.client.start(new InetSocketAddress(0).getAddress(), CLIENT_PORT); configureDispatcher(); - RealmRepresentation realm = KeycloakConfiguration.getRealmRepresentation(TEST_REALM, CLIENT_ID, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, CLIENT_APP, CONFIGURE_CLIENT_SCOPES); + RealmRepresentation realm = KeycloakConfiguration.getRealmRepresentation( + TEST_REALM, CLIENT_ID, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, + CLIENT_APP, false); realm.setAccessTokenLifespan(100); realm.setSsoSessionMaxLifespan(100); @@ -164,7 +163,6 @@ public ElytronDispatcher(HttpServerAuthenticationMechanism mechanism, Dispatcher public MockResponse dispatch(RecordedRequest serverRequest) throws InterruptedException { if (beforeDispatcher != null) { MockResponse response = beforeDispatcher.dispatch(serverRequest); - if (response != null) { return response; } @@ -173,11 +171,7 @@ public MockResponse dispatch(RecordedRequest serverRequest) throws InterruptedEx MockResponse mockResponse = new MockResponse(); try { - if (IS_BACK_CHANNEL_TEST && serverRequest.getRequestUrl().toString().endsWith(BACK_CHANNEL_LOGOUT_URL)) { - currentRequest = new TestingHttpServerRequest(serverRequest, null); - } else { - currentRequest = new TestingHttpServerRequest(serverRequest, sessionScope); - } + currentRequest = new TestingHttpServerRequest(serverRequest, sessionScope); mechanism.evaluateRequest(currentRequest); @@ -232,7 +226,7 @@ protected void configureDispatcher(OidcClientConfiguration clientConfig, Dispatc } protected void assertUserNotAuthenticated() { - assertNull(getCurrentSession().getAttachment(OidcAccount.class.getName())); + assertNull(getCurrentSession()); } protected void assertUserAuthenticated() { diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java index 8540209498f..f9e22010481 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java @@ -29,25 +29,21 @@ import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebClient; import org.apache.http.HttpStatus; -import org.junit.BeforeClass; import org.junit.Test; import org.keycloak.representations.idm.ClientRepresentation; public class BackChannelLogoutTest extends AbstractLogoutTest { - @BeforeClass - public static void setUp() { - IS_BACK_CHANNEL_TEST = true; - } - @Override protected void doConfigureClient(ClientRepresentation client) { List redirectUris = client.getRedirectUris(); String redirectUri = redirectUris.get(0); + OidcClientConfiguration config = new OidcClientConfiguration(); client.setFrontchannelLogout(false); client.getAttributes().put("backchannel.logout.session.required", "true"); - client.getAttributes().put("backchannel.logout.url", rewriteHost(redirectUri) + BACK_CHANNEL_LOGOUT_URL); + client.getAttributes().put("backchannel.logout.url", rewriteHost(redirectUri) + + config.getLogoutCallbackPath()); } private static String rewriteHost(String redirectUri) { @@ -59,9 +55,10 @@ private static String rewriteHost(String redirectUri) { } @Test - public void testRPInitiatedLogout() throws Exception { + public void testBackChannelLogout() throws Exception { URI requestUri = new URI(getClientUrl()); WebClient webClient = getWebClient(); + webClient.getPage(getClientUrl()); TestingHttpServerResponse response = getCurrentResponse(); assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusCode()); @@ -76,9 +73,7 @@ public void testRPInitiatedLogout() throws Exception { // logged out after finishing the redirections during frontchannel logout assertUserAuthenticated(); - webClient.getPage(getClientUrl() + "/logout"); - //assertUserAuthenticated(); - webClient.getPage(getClientUrl()); + webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); assertUserNotAuthenticated(); } } \ No newline at end of file diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java index dd4ca58c74b..8a6f72ef432 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java @@ -49,8 +49,9 @@ protected void doConfigureClient(ClientRepresentation client) { client.setFrontchannelLogout(true); List redirectUris = client.getRedirectUris(); String redirectUri = redirectUris.get(0); - - client.getAttributes().put("frontchannel.logout.url", redirectUri + "/logout/callback"); + OidcClientConfiguration config = new OidcClientConfiguration(); + client.getAttributes().put("frontchannel.logout.url", redirectUri + + config.getLogoutCallbackPath()); } @Test @@ -71,14 +72,14 @@ public void testRPInitiatedLogout() throws Exception { // logged out after finishing the redirections during frontchannel logout assertUserAuthenticated(); - webClient.getPage(getClientUrl() + "/logout"); + webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); assertUserNotAuthenticated(); } @Test public void testRPInitiatedLogoutWithPostLogoutUri() throws Exception { OidcClientConfiguration oidcClientConfiguration = getClientConfig(); - oidcClientConfiguration.setPostLogoutUri("/post-logout"); + oidcClientConfiguration.setPostLogoutPath("/post-logout"); configureDispatcher(oidcClientConfiguration, new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { @@ -99,7 +100,7 @@ public MockResponse dispatch(RecordedRequest request) { assertTrue(page.getWebResponse().getContentAsString().contains("Welcome, authenticated user")); assertUserAuthenticated(); - HtmlPage continueLogout = webClient.getPage(getClientUrl() + "/logout"); + HtmlPage continueLogout = webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); page = continueLogout.getElementById("continue").click(); assertUserNotAuthenticated(); assertTrue(page.getWebResponse().getContentAsString().contains("you are logged out from app")); diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/LogoutConfigurationOptionsTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/LogoutConfigurationOptionsTest.java new file mode 100644 index 00000000000..c6fb24cf754 --- /dev/null +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/LogoutConfigurationOptionsTest.java @@ -0,0 +1,118 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2024 Red Hat, Inc., and individual 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.wildfly.security.http.oidc; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/* + Verify that invalid logout config options values are flagged. + */ +public class LogoutConfigurationOptionsTest { + private OidcJsonConfiguration oidcJsonConfiguration; + + @Before + public void before() { + oidcJsonConfiguration = new OidcJsonConfiguration(); + // minimum required options + oidcJsonConfiguration.setRealm("realm"); + oidcJsonConfiguration.setResource("resource"); + oidcJsonConfiguration.setClientId("clientId"); + oidcJsonConfiguration.setAuthServerUrl("AuthServerUrl"); + } + + @After + public void after() { + System.clearProperty(Oidc.LOGOUT_PATH); + System.clearProperty(Oidc.LOGOUT_CALLBACK_PATH); + System.clearProperty(Oidc.POST_LOGOUT_PATH); + } + + @Test + public void testLogoutPath() { + + try { + System.setProperty(Oidc.LOGOUT_PATH, " "); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("Empty " +Oidc.LOGOUT_PATH+ " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.LOGOUT_PATH)); + } + + try { + System.setProperty(Oidc.LOGOUT_PATH, "/"); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("/ in " +Oidc.LOGOUT_PATH+ " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.LOGOUT_PATH)); + } + } + + @Test + public void testCallbackLogoutPath() { + + try { + System.setProperty(Oidc.LOGOUT_CALLBACK_PATH, " "); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("Empty " + Oidc.LOGOUT_CALLBACK_PATH + " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.LOGOUT_CALLBACK_PATH)); + } + + try { + System.setProperty(Oidc.LOGOUT_CALLBACK_PATH, "/"); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("/ in " + Oidc.LOGOUT_CALLBACK_PATH + " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.LOGOUT_CALLBACK_PATH)); + } + + try { + System.setProperty(Oidc.LOGOUT_PATH, "/mylogout"); + System.setProperty(Oidc.LOGOUT_CALLBACK_PATH, "/more/mylogout"); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("Identical paths is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().contains("ELY23072")); + } + } + + @Test + public void testPostLogoutPath() { + + try { + System.setProperty(Oidc.POST_LOGOUT_PATH, " "); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("Empty " +Oidc.POST_LOGOUT_PATH+ " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.POST_LOGOUT_PATH)); + } + + try { + System.setProperty(Oidc.POST_LOGOUT_PATH, "/"); + OidcClientConfigurationBuilder.build(oidcJsonConfiguration); + fail("/ in " + Oidc.POST_LOGOUT_PATH + " is invalid"); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith(Oidc.POST_LOGOUT_PATH)); + } + } +} diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java index b8a14b0d982..4f1028f829e 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/OidcBaseTest.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2022 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -212,7 +212,7 @@ public MockResponse dispatch(RecordedRequest recordedRequest) throws Interrupted } protected static Dispatcher createAppResponse(HttpServerAuthenticationMechanism mechanism, int expectedStatusCode, String expectedLocation, String clientPageText, - Map attachments) { + Map sessionScopeAttachments) { return new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException { @@ -225,8 +225,8 @@ public MockResponse dispatch(RecordedRequest recordedRequest) throws Interrupted TestingHttpServerResponse response = request.getResponse(); assertEquals(expectedStatusCode, response.getStatusCode()); assertEquals(expectedLocation, response.getLocation()); - for (String key : request.getAttachments().keySet()) { - attachments.put(key, request.getAttachments().get(key)); + for (String key : request.getSessionScopeAttachments().keySet()) { + sessionScopeAttachments.put(key, request.getSessionScopeAttachments().get(key)); } return new MockResponse().setBody(clientPageText); } catch (Exception e) { @@ -240,7 +240,7 @@ public MockResponse dispatch(RecordedRequest recordedRequest) throws Interrupted } protected static Dispatcher createAppResponse(HttpServerAuthenticationMechanism mechanism, String clientPageText, - Map attachments, String tenant, boolean sameTenant) { + Map sessionScopeAttachments, String tenant, boolean sameTenant) { return new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException { @@ -248,7 +248,7 @@ public MockResponse dispatch(RecordedRequest recordedRequest) throws Interrupted if (path.contains("/" + CLIENT_APP + "/" + tenant)) { try { TestingHttpServerRequest request = new TestingHttpServerRequest(new String[0], - new URI(recordedRequest.getRequestUrl().toString()), attachments); + new URI(recordedRequest.getRequestUrl().toString()), sessionScopeAttachments); mechanism.evaluateRequest(request); TestingHttpServerResponse response = request.getResponse(); if (sameTenant) { @@ -279,6 +279,7 @@ static WebClient getWebClient() { WebClient webClient = new WebClient(); webClient.setCssErrorHandler(new SilentCssErrorHandler()); webClient.setJavaScriptErrorListener(new SilentJavaScriptErrorListener()); + webClient.getOptions().setMaxInMemory(50000 * 1024); return webClient; } diff --git a/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java b/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java index 9fe171c9214..0938a6297ea 100644 --- a/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java +++ b/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java @@ -1,6 +1,6 @@ /* * JBoss, Home of Professional Open Source. - * Copyright 2017 Red Hat, Inc., and individual contributors + * Copyright 2024 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -27,9 +27,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; -import java.net.MalformedURLException; import java.net.URI; -import java.net.URISyntaxException; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.cert.Certificate; @@ -157,10 +155,9 @@ protected static class TestingHttpServerRequest implements HttpServerRequest { private List cookies; private String requestMethod = "GET"; private Map> requestHeaders = new HashMap<>(); - private Map attachments = new HashMap<>(); - private Map scopes = new HashMap<>(); - private HttpScope sessionScope; private X500Principal testPrincipal = null; + private Map sessionScopeAttachments = new HashMap<>(); + private HttpScope sessionScope; public TestingHttpServerRequest(String[] authorization) { if (authorization != null) { @@ -188,14 +185,14 @@ public TestingHttpServerRequest(String[] authorization, URI requestURI) { this.cookies = new ArrayList<>(); } - public TestingHttpServerRequest(String[] authorization, URI requestURI, Map attachments) { + public TestingHttpServerRequest(String[] authorization, URI requestURI, Map sessionScopeAttachments) { if (authorization != null) { requestHeaders.put(AUTHORIZATION, Arrays.asList(authorization)); } this.remoteUser = null; this.requestURI = requestURI; this.cookies = new ArrayList<>(); - this.attachments = attachments; + this.sessionScopeAttachments = sessionScopeAttachments; } public TestingHttpServerRequest(String[] authorization, URI requestURI, List cookies) { @@ -216,10 +213,6 @@ public TestingHttpServerRequest(Map> requestHeaders, URI re } public TestingHttpServerRequest(String[] authorization, URI requestURI, String cookie) { - this(authorization, requestURI, cookie, null); - } - - public TestingHttpServerRequest(String[] authorization, URI requestURI, String cookie, HttpScope sessionScope) { if (authorization != null) { requestHeaders.put(AUTHORIZATION, Arrays.asList(authorization)); } @@ -231,14 +224,14 @@ public TestingHttpServerRequest(String[] authorization, URI requestURI, String c final String cookieValue = cookie.substring(cookie.indexOf('=') + 1); cookies.add(HttpServerCookie.getInstance(cookieName, cookieValue, null, -1, "/", false, 0, true)); } - this.sessionScope = sessionScope; } - public TestingHttpServerRequest(RecordedRequest serverRequest, HttpScope sessionScope) throws URISyntaxException { - this(new String[0], new URI(serverRequest.getRequestUrl().toString()), serverRequest.getHeader("Cookie"), sessionScope); - this.requestMethod = serverRequest.getMethod(); - this.body = serverRequest.getBody().readUtf8(); - this.contentType = serverRequest.getHeader("Content-Type"); + public TestingHttpServerRequest(RecordedRequest request, HttpScope sessionScope) { + this(new String[0], request.getRequestUrl().uri(), request.getHeader("Cookie")); + this.requestMethod = request.getMethod(); + this.body = request.getBody().readUtf8(); + this.contentType = request.getHeader("Content-Type"); + this.sessionScope = sessionScope; } public Status getResult() { @@ -312,11 +305,7 @@ public URI getRequestURI() { } public String getRequestPath() { - try { - return requestURI.toURL().getPath(); - } catch (MalformedURLException cause) { - throw new RuntimeException("Mal-formed request URL", cause); - } + return requestURI.getPath(); } public Map> getParameters() { @@ -369,54 +358,53 @@ public boolean resumeRequest() { } public HttpScope getScope(Scope scope) { - if (scope.equals(Scope.SSL_SESSION)) { + if (requestURI != null && "/clientApp/logout/callback".equals(requestURI.getPath())){ return null; } - - if (Scope.SESSION.equals(scope) && sessionScope != null) { + if (scope.equals(Scope.SSL_SESSION)) { + return null; + } else if (sessionScope != null) { return sessionScope; } - HttpScope httpScope = scopes.get(scope); - - if (httpScope == null) { - return new HttpScope() { + return new HttpScope() { - @Override - public boolean exists() { - return true; - } + @Override + public boolean exists() { + return true; + } - @Override - public boolean create() { - return false; - } + @Override + public boolean create() { + return false; + } - @Override - public boolean supportsAttachments() { - return true; - } + @Override + public boolean supportsAttachments() { + return true; + } - @Override - public boolean supportsInvalidation() { - return true; - } + @Override + public boolean supportsInvalidation() { + return false; + } - @Override - public void setAttachment(String key, Object value) { - attachments.put(key, value); + @Override + public void setAttachment(String key, Object value) { + if (scope.equals(Scope.SESSION)) { + sessionScopeAttachments.put(key, value); } + } - @Override - public Object getAttachment(String key) { - return attachments.get(key); + @Override + public Object getAttachment(String key) { + if (scope.equals(Scope.SESSION)) { + return sessionScopeAttachments.get(key); + } else { + return null; } - - }; - } - scopes.put(scope, httpScope); - - return httpScope; + } + }; } public Collection getScopeIds(Scope scope) { @@ -424,10 +412,7 @@ public Collection getScopeIds(Scope scope) { } public HttpScope getScope(Scope scope, String id) { - if (Scope.SESSION.equals(scope) && sessionScope != null) { - return sessionScope; - } - return scopes.get(scope); + throw new IllegalStateException(); } public void setRemoteUser(String remoteUser) { @@ -439,8 +424,8 @@ public String getRemoteUser() { return remoteUser; } - public Map getAttachments() { - return attachments; + public Map getSessionScopeAttachments() { + return sessionScopeAttachments; } } From 9a61d67d64622049c8f5fca98fe1606720a4ff0e Mon Sep 17 00:00:00 2001 From: R Searls Date: Thu, 7 Nov 2024 16:30:48 -0500 Subject: [PATCH 11/16] [ELY-2534] OIDC logout support --- .../security/http/oidc/LogoutHandler.java | 12 ++++++++++-- .../http/oidc/OidcAuthenticationMechanism.java | 2 +- .../oidc/OidcClientConfigurationBuilder.java | 3 +++ .../http/oidc/OidcRequestAuthenticator.java | 1 - .../http/oidc/OidcSessionTokenStore.java | 17 ++++++++++++----- .../security/http/oidc/AbstractLogoutTest.java | 7 ++++--- .../http/oidc/BackChannelLogoutTest.java | 7 +++---- .../http/oidc/FrontChannelLogoutTest.java | 9 ++++----- .../http/impl/AbstractBaseHttpTest.java | 3 +++ 9 files changed, 40 insertions(+), 21 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index ac33649bb93..cda713dc61d 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -63,19 +63,24 @@ protected boolean removeEldestEntry(Map.Entry e }); boolean tryLogout(OidcHttpFacade facade) { + log.trace("tryLogout entered"); RefreshableOidcSecurityContext securityContext = getSecurityContext(facade); if (securityContext == null) { // no active session + log.trace("tryLogout securityContext == null"); return false; } if (isRpInitiatedLogoutPath(facade)) { + log.trace("isRpInitiatedLogoutPath"); redirectEndSessionEndpoint(facade); return true; } if (isLogoutCallbackPath(facade)) { + log.trace("isLogoutCallbackPath"); if (isFrontChannel(facade)) { + log.trace("isFrontChannel"); handleFrontChannelLogoutRequest(facade); return true; } else { @@ -84,7 +89,6 @@ boolean tryLogout(OidcHttpFacade facade) { facade.authenticationFailed(); } } - return false; } @@ -119,6 +123,7 @@ private void redirectEndSessionEndpoint(OidcHttpFacade facade) { } logoutUri = redirectUriBuilder.build().toString(); + log.trace("redirectEndSessionEndpoint path: " + redirectUriBuilder.toString()); } catch (URISyntaxException e) { throw new RuntimeException(e); } @@ -129,8 +134,11 @@ private void redirectEndSessionEndpoint(OidcHttpFacade facade) { } boolean tryBackChannelLogout(OidcHttpFacade facade) { + log.trace("tryBackChannelLogout entered"); if (isLogoutCallbackPath(facade)) { + log.trace("isLogoutCallbackPath"); if (isBackChannel(facade)) { + log.trace("isBackChannel"); handleBackChannelLogoutRequest(facade); return true; } @@ -219,7 +227,7 @@ private String getRedirectUri(OidcHttpFacade facade) { return uri; } - boolean isLogoutCallbackPath(OidcHttpFacade facade) { + private boolean isLogoutCallbackPath(OidcHttpFacade facade) { String path = facade.getRequest().getRelativePath(); return path.endsWith(getLogoutCallbackPath(facade)); } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java index 1a4963ea6e1..a33d6b261d9 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcAuthenticationMechanism.java @@ -60,7 +60,7 @@ public String getMechanismName() { @Override public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { - String tmpURI = request.getRequestURI().toString(); + log.debug("evaluateRequest uri: " + request.getRequestURI().toString()); OidcClientContext oidcClientContext = getOidcClientContext(request); if (oidcClientContext == null) { log.debugf("Ignoring request for path [%s] from mechanism [%s]. No client configuration context found.", request.getRequestURI(), getMechanismName()); diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java index fc80ef01358..52d59e13819 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java @@ -200,6 +200,7 @@ protected OidcClientConfiguration internalBuild(final OidcJsonConfiguration oidc oidcClientConfiguration.setTokenSignatureAlgorithm(oidcJsonConfiguration.getTokenSignatureAlgorithm()); String tmpLogoutPath = System.getProperty(LOGOUT_PATH); + log.debug("sysProp LOGOUT_PATH: " + (tmpLogoutPath == null ? "NULL" : tmpLogoutPath)); if (tmpLogoutPath != null) { if (isValidPath(tmpLogoutPath)) { oidcClientConfiguration.setLogoutPath(tmpLogoutPath); @@ -210,6 +211,7 @@ protected OidcClientConfiguration internalBuild(final OidcJsonConfiguration oidc String tmpLogoutCallbackPath = System.getProperty(LOGOUT_CALLBACK_PATH); + log.debug("sysProp LOGOUT_CALLBACK_PATH: " + (tmpLogoutCallbackPath == null ? "NULL" : tmpLogoutCallbackPath)); if (tmpLogoutCallbackPath != null) { if (isValidPath(tmpLogoutCallbackPath) && !tmpLogoutCallbackPath.endsWith(oidcClientConfiguration.getLogoutPath())) { @@ -225,6 +227,7 @@ protected OidcClientConfiguration internalBuild(final OidcJsonConfiguration oidc } String tmpPostLogoutPath = System.getProperty(POST_LOGOUT_PATH); + log.debug("sysProp POST_LOGOUT_PATH: " + (tmpPostLogoutPath == null ? "NULL" : tmpPostLogoutPath)); if (tmpPostLogoutPath != null) { if (isValidPath(tmpPostLogoutPath)) { oidcClientConfiguration.setPostLogoutPath(tmpPostLogoutPath); diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcRequestAuthenticator.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcRequestAuthenticator.java index 5ef5c26122e..0588c165682 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcRequestAuthenticator.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcRequestAuthenticator.java @@ -184,7 +184,6 @@ protected String getCode() { protected String getRedirectUri(String state) { String url = getRequestUrl(); log.debugf("callback uri: %s", url); - try { if (! facade.getRequest().isSecure() && deployment.getSSLRequired().isRequired(facade.getRequest().getRemoteAddr())) { int port = getSSLRedirectPort(); diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcSessionTokenStore.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcSessionTokenStore.java index cb6206177cd..6762afc0f47 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcSessionTokenStore.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcSessionTokenStore.java @@ -45,21 +45,29 @@ public OidcSessionTokenStore(OidcHttpFacade httpFacade) { @Override public void checkCurrentToken() { HttpScope session = httpFacade.getScope(Scope.SESSION); - if (session == null || ! session.exists()) return; + if (session == null || ! session.exists()) { + return; + } RefreshableOidcSecurityContext securityContext = (RefreshableOidcSecurityContext) session.getAttachment(OidcSecurityContext.class.getName()); - if (securityContext == null) return; + if (securityContext == null) { + return; + } // just in case session got serialized if (securityContext.getOidcClientConfiguration() == null) { securityContext.setCurrentRequestInfo(httpFacade.getOidcClientConfiguration(), this); } - if (securityContext.isActive() && ! securityContext.getOidcClientConfiguration().isAlwaysRefreshToken()) return; + if (securityContext.isActive() && ! securityContext.getOidcClientConfiguration().isAlwaysRefreshToken()) { + return; + } // FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will // not be updated boolean success = securityContext.refreshToken(false); - if (success && securityContext.isActive()) return; + if (success && securityContext.isActive()) { + return; + } // Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session session.setAttachment(OidcSecurityContext.class.getName(), null); @@ -132,7 +140,6 @@ public void saveAccountInfo(OidcAccount account) { } }); } - session.setAttachment(OidcAccount.class.getName(), account); session.setAttachment(OidcSecurityContext.class.getName(), account.getOidcSecurityContext()); diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java index 35adc45ad16..85a270cfd82 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/AbstractLogoutTest.java @@ -77,7 +77,9 @@ public void onBefore() throws Exception { OidcBaseTest.client = new MockWebServer(); OidcBaseTest.client.start(new InetSocketAddress(0).getAddress(), CLIENT_PORT); configureDispatcher(); - RealmRepresentation realm = KeycloakConfiguration.getRealmRepresentation(TEST_REALM, CLIENT_ID, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, CLIENT_APP, false); + RealmRepresentation realm = KeycloakConfiguration.getRealmRepresentation( + TEST_REALM, CLIENT_ID, CLIENT_SECRET, CLIENT_HOST_NAME, CLIENT_PORT, + CLIENT_APP, false); realm.setAccessTokenLifespan(100); realm.setSsoSessionMaxLifespan(100); @@ -161,7 +163,6 @@ public ElytronDispatcher(HttpServerAuthenticationMechanism mechanism, Dispatcher public MockResponse dispatch(RecordedRequest serverRequest) throws InterruptedException { if (beforeDispatcher != null) { MockResponse response = beforeDispatcher.dispatch(serverRequest); - if (response != null) { return response; } @@ -225,7 +226,7 @@ protected void configureDispatcher(OidcClientConfiguration clientConfig, Dispatc } protected void assertUserNotAuthenticated() { - assertNull(getCurrentSession().getAttachment(OidcAccount.class.getName())); + assertNull(getCurrentSession()); } protected void assertUserAuthenticated() { diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java index e4fed155139..d39e5af418f 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/BackChannelLogoutTest.java @@ -55,9 +55,10 @@ private static String rewriteHost(String redirectUri) { } @Test - public void testRPInitiatedLogout() throws Exception { + public void testBackChannelLogout() throws Exception { URI requestUri = new URI(getClientUrl()); WebClient webClient = getWebClient(); + webClient.getPage(getClientUrl()); TestingHttpServerResponse response = getCurrentResponse(); assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusCode()); @@ -73,8 +74,6 @@ public void testRPInitiatedLogout() throws Exception { // logged out after finishing the redirections during frontchannel logout assertUserAuthenticated(); webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); - assertUserAuthenticated(); - webClient.getPage(getClientUrl()); assertUserNotAuthenticated(); } -} \ No newline at end of file +} diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java index 5137d404130..ec4eeff3c56 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java @@ -49,10 +49,9 @@ protected void doConfigureClient(ClientRepresentation client) { client.setFrontchannelLogout(true); List redirectUris = client.getRedirectUris(); String redirectUri = redirectUris.get(0); - - OidcClientConfiguration ocConfig = new OidcClientConfiguration(); + OidcClientConfiguration config = new OidcClientConfiguration(); client.getAttributes().put("frontchannel.logout.url", redirectUri - + ocConfig.getLogoutCallbackPath()); + + config.getLogoutCallbackPath()); } @Test @@ -101,7 +100,7 @@ public MockResponse dispatch(RecordedRequest request) { assertTrue(page.getWebResponse().getContentAsString().contains("Welcome, authenticated user")); assertUserAuthenticated(); - HtmlPage continueLogout = webClient.getPage(getClientUrl() + "/logout"); + HtmlPage continueLogout = webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); page = continueLogout.getElementById("continue").click(); assertUserNotAuthenticated(); assertTrue(page.getWebResponse().getContentAsString().contains("you are logged out from app")); @@ -126,4 +125,4 @@ public void testFrontChannelLogout() throws Exception { client.setDispatcher(new QueueDispatcher()); } } -} \ No newline at end of file +} diff --git a/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java b/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java index 962c13fef08..0938a6297ea 100644 --- a/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java +++ b/tests/base/src/test/java/org/wildfly/security/http/impl/AbstractBaseHttpTest.java @@ -358,6 +358,9 @@ public boolean resumeRequest() { } public HttpScope getScope(Scope scope) { + if (requestURI != null && "/clientApp/logout/callback".equals(requestURI.getPath())){ + return null; + } if (scope.equals(Scope.SSL_SESSION)) { return null; } else if (sessionScope != null) { From 48c15dde497c8978f388be31df1d516811b2c92a Mon Sep 17 00:00:00 2001 From: R Searls Date: Thu, 7 Nov 2024 16:30:48 -0500 Subject: [PATCH 12/16] [ELY-2534] OIDC logout support --- tool/LICENSE.txt | 203 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 202 insertions(+), 1 deletion(-) mode change 120000 => 100644 tool/LICENSE.txt diff --git a/tool/LICENSE.txt b/tool/LICENSE.txt deleted file mode 120000 index 57ddfc0a053..00000000000 --- a/tool/LICENSE.txt +++ /dev/null @@ -1 +0,0 @@ -src/main/resources/META-INF/LICENSE.txt \ No newline at end of file diff --git a/tool/LICENSE.txt b/tool/LICENSE.txt new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/tool/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. From 6974f0a2ccce75b44d3f61a2de7d9f593a449fd0 Mon Sep 17 00:00:00 2001 From: R Searls Date: Thu, 9 Jan 2025 15:06:02 -0500 Subject: [PATCH 13/16] support post-logout-path as only an absolute URI --- .../java/org/wildfly/security/http/oidc/LogoutHandler.java | 4 ++-- .../security/http/oidc/OidcClientConfigurationBuilder.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index cda713dc61d..339c2a62bf6 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -118,8 +118,8 @@ private void redirectEndSessionEndpoint(OidcHttpFacade facade) { .addParameter(ID_TOKEN_HINT_PARAM, securityContext.getIDTokenString()); String postLogoutPath = clientConfiguration.getPostLogoutPath(); if (postLogoutPath != null) { - redirectUriBuilder.addParameter(POST_LOGOUT_REDIRECT_URI_PARAM, - getRedirectUri(facade) + postLogoutPath); + log.trace("post_logout_redirect_uri: " + postLogoutPath); + redirectUriBuilder.addParameter(POST_LOGOUT_REDIRECT_URI_PARAM, postLogoutPath); } logoutUri = redirectUriBuilder.build().toString(); diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java index 52d59e13819..51a2477386b 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/OidcClientConfigurationBuilder.java @@ -218,7 +218,7 @@ protected OidcClientConfiguration internalBuild(final OidcJsonConfiguration oidc oidcClientConfiguration.setLogoutCallbackPath(tmpLogoutCallbackPath); } else { if (!isValidPath(tmpLogoutCallbackPath)) { - throw log.invalidLogoutPath(tmpLogoutPath, LOGOUT_CALLBACK_PATH); + throw log.invalidLogoutPath(tmpLogoutCallbackPath, LOGOUT_CALLBACK_PATH); } else { throw log.invalidLogoutCallbackPath(LOGOUT_CALLBACK_PATH, tmpLogoutCallbackPath, LOGOUT_PATH, oidcClientConfiguration.getLogoutPath()); @@ -229,10 +229,10 @@ protected OidcClientConfiguration internalBuild(final OidcJsonConfiguration oidc String tmpPostLogoutPath = System.getProperty(POST_LOGOUT_PATH); log.debug("sysProp POST_LOGOUT_PATH: " + (tmpPostLogoutPath == null ? "NULL" : tmpPostLogoutPath)); if (tmpPostLogoutPath != null) { - if (isValidPath(tmpPostLogoutPath)) { + if (isValidPath(tmpPostLogoutPath) || tmpPostLogoutPath.startsWith("http")) { oidcClientConfiguration.setPostLogoutPath(tmpPostLogoutPath); } else { - throw log.invalidLogoutPath(tmpLogoutPath, POST_LOGOUT_PATH); + throw log.invalidLogoutPath(tmpPostLogoutPath, POST_LOGOUT_PATH); } } From edd3d934a8f989afdc3b37060548a024ba02d102 Mon Sep 17 00:00:00 2001 From: R Searls Date: Fri, 10 Jan 2025 09:05:28 -0500 Subject: [PATCH 14/16] fixed unit test to support post_logout_path as a URI --- .../wildfly/security/http/oidc/FrontChannelLogoutTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java index ec4eeff3c56..838763e2aca 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java @@ -79,7 +79,7 @@ public void testRPInitiatedLogout() throws Exception { @Test public void testRPInitiatedLogoutWithPostLogoutUri() throws Exception { OidcClientConfiguration oidcClientConfiguration = getClientConfig(); - oidcClientConfiguration.setPostLogoutPath("/post-logout"); + oidcClientConfiguration.setPostLogoutPath("http://localhost/8080/post-logout"); configureDispatcher(oidcClientConfiguration, new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { @@ -100,7 +100,7 @@ public MockResponse dispatch(RecordedRequest request) { assertTrue(page.getWebResponse().getContentAsString().contains("Welcome, authenticated user")); assertUserAuthenticated(); - HtmlPage continueLogout = webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); + HtmlPage continueLogout = webClient.getPage(getClientConfig().getLogoutPath()); page = continueLogout.getElementById("continue").click(); assertUserNotAuthenticated(); assertTrue(page.getWebResponse().getContentAsString().contains("you are logged out from app")); From 324e71c9c5d2662cb8d66dd9f3e6d24324ec9cc4 Mon Sep 17 00:00:00 2001 From: R Searls Date: Fri, 10 Jan 2025 15:06:53 -0500 Subject: [PATCH 15/16] working test fix --- .../wildfly/security/http/oidc/FrontChannelLogoutTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java index 838763e2aca..3a20cb1f509 100644 --- a/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java +++ b/http/oidc/src/test/java/org/wildfly/security/http/oidc/FrontChannelLogoutTest.java @@ -79,7 +79,7 @@ public void testRPInitiatedLogout() throws Exception { @Test public void testRPInitiatedLogoutWithPostLogoutUri() throws Exception { OidcClientConfiguration oidcClientConfiguration = getClientConfig(); - oidcClientConfiguration.setPostLogoutPath("http://localhost/8080/post-logout"); + oidcClientConfiguration.setPostLogoutPath(getClientUrl()+"/post-logout"); configureDispatcher(oidcClientConfiguration, new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { @@ -100,7 +100,7 @@ public MockResponse dispatch(RecordedRequest request) { assertTrue(page.getWebResponse().getContentAsString().contains("Welcome, authenticated user")); assertUserAuthenticated(); - HtmlPage continueLogout = webClient.getPage(getClientConfig().getLogoutPath()); + HtmlPage continueLogout = webClient.getPage(getClientUrl() + getClientConfig().getLogoutPath()); page = continueLogout.getElementById("continue").click(); assertUserNotAuthenticated(); assertTrue(page.getWebResponse().getContentAsString().contains("you are logged out from app")); From 8d1e83726c15be64cdda8fd12c7f1b6ce45ffdb2 Mon Sep 17 00:00:00 2001 From: R Searls Date: Fri, 10 Jan 2025 16:54:45 -0500 Subject: [PATCH 16/16] remove obsolete ENUMs. Text change in a few msgs. Several constants made private --- .../wildfly/security/http/oidc/AuthenticationError.java | 4 +--- .../org/wildfly/security/http/oidc/ElytronMessages.java | 8 ++++---- .../org/wildfly/security/http/oidc/LogoutHandler.java | 8 ++++---- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java index 789e1f4b4d3..cc99a48d126 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/AuthenticationError.java @@ -36,9 +36,7 @@ public enum Reason { INVALID_TOKEN, STALE_TOKEN, NO_AUTHORIZATION_HEADER, - NO_QUERY_PARAMETER_ACCESS_TOKEN, - NO_SESSION_ID, - METHOD_NOT_ALLOWED + NO_QUERY_PARAMETER_ACCESS_TOKEN } private Reason reason; diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java index ce3d976dcdd..7b54b318462 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/ElytronMessages.java @@ -279,11 +279,11 @@ interface ElytronMessages extends BasicLogger { @Message(id = 23070, value = "Authentication request format must be one of the following: oauth2, request, request_uri.") RuntimeException invalidAuthenticationRequestFormat(); - @Message(id = 23071, value = "%s is not a valid value for %s") + @Message(id = 23071, value = "Invalid logout output: %s is not a valid value for %s") RuntimeException invalidLogoutPath(String pathValue, String pathName); - @Message(id = 23072, value = "The end substring of %s: %s can not be identical to %s: %s") - RuntimeException invalidLogoutCallbackPath(String callbackPathTitle, String callbacPathkValue, - String logoutPathTitle, String logoutPathValue); + @Message(id = 23072, value = "Invalid %s: %s the value can not be identical to %s: %s") + RuntimeException invalidLogoutCallbackPath(String callbackPathTitle, String callbackPathValue, + String logoutPathTitle, String logoutPathName); } diff --git a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java index 339c2a62bf6..23e719d12b4 100644 --- a/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java +++ b/http/oidc/src/main/java/org/wildfly/security/http/oidc/LogoutHandler.java @@ -38,13 +38,13 @@ */ final class LogoutHandler { - public static final String POST_LOGOUT_REDIRECT_URI_PARAM = "post_logout_redirect_uri"; - public static final String ID_TOKEN_HINT_PARAM = "id_token_hint"; + private static final String POST_LOGOUT_REDIRECT_URI_PARAM = "post_logout_redirect_uri"; + private static final String ID_TOKEN_HINT_PARAM = "id_token_hint"; private static final String LOGOUT_TOKEN_PARAM = "logout_token"; private static final String LOGOUT_TOKEN_TYPE = "Logout"; private static final String CLIENT_ID_SID_SEPARATOR = "-"; - public static final String SID = "sid"; - public static final String ISS = "iss"; + private static final String SID = "sid"; + private static final String ISS = "iss"; /** * A bounded map to store sessions marked for invalidation after receiving logout requests through the back-channel