diff --git a/ChangeLog.md b/ChangeLog.md index 880da8f4df..a4e79f1f1b 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -17,6 +17,13 @@ specific language governing permissions and limitations under the License. --> +**2026-11-18 Arturo Bernal (abernal AT apache DOT org)** + +* _3.0.1-git-10_ + +* Fix for [JSPWIKI-94](https://issues.apache.org/jira/browse/JSPWIKI-94): the new module jspwiki-oidc logs users in with OpenID Connect, with the pac4j filters, and presents them to the wiki as users authenticated by the container, including their roles and the logout. It is not included in the war unless it is built with the profile oidc, and its filters are disabled in web.xml +* Fix for [JSPWIKI-1375](https://issues.apache.org/jira/browse/JSPWIKI-1375): the OpenID Connect login of the module jspwiki-oidc works with any OpenID Connect provider, with the claims for the name and the roles of the user configurable + **2026-11-14 Multiple authors** * _3.0.1-git-09 diff --git a/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java b/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java index 7128b9933e..a588475922 100644 --- a/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java +++ b/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java @@ -69,7 +69,7 @@ public final class Release { *

* If the build identifier is empty, it is not added. */ - public static final String BUILD = "9"; + public static final String BUILD = "10"; /** * This is the generic version string you should use when printing out the version. It is of diff --git a/jspwiki-oidc/README.md b/jspwiki-oidc/README.md new file mode 100644 index 0000000000..8695f8561c --- /dev/null +++ b/jspwiki-oidc/README.md @@ -0,0 +1,90 @@ + + + +# jspwiki-oidc + +Logs users in with OpenID Connect, using the pac4j filters, and presents them to the wiki as users authenticated by the +container. It works with any OpenID Connect provider: it has been tried with Keycloak, see +[JSPWIKI-94](https://issues.apache.org/jira/browse/JSPWIKI-94) and +[JSPWIKI-1375](https://issues.apache.org/jira/browse/JSPWIKI-1375). The configurations for Google and Microsoft Entra ID (Azure) +below follow what these providers document, and have not been tried with them. + +## Enabling it + +1. Build the war with `mvn package -Poidc`, or add this module and its dependencies to `WEB-INF/lib`. +2. Create `WEB-INF/classes/jspwiki-oidc.properties`: + + ``` + oidc.clientId=the client id + oidc.secret=the client secret + oidc.discoveryUri=https://provider.example.org/.well-known/openid-configuration + oidc.callbackUrl=/oidc/callback + ``` + + The optional settings are: + + - `oidc.scope`, `openid email profile` by default. + - `oidc.usernameClaim`, the claim with the name of the user in the wiki, `preferred_username` by default. When the claim is + missing, the wiki uses the e-mail address, and then the identifier of the user at the provider. + - `oidc.rolesClaim`, the claim with the roles of the user. It is searched in the profile and in the access token when this is a JWT, + and it may be a dotted path through nested claims. Without it, the users have no roles from the provider. + - `oidc.roleMapping`, to turn the values of the roles claim into the names of the roles of the wiki when the provider sends + identifiers instead of names, written `value=Role,value2=Role2`. + +3. Add to `WEB-INF/classes/jspwiki-custom.properties`: + + ``` + jspwiki.authorizer = org.apache.wiki.oidc.OidcAuthorizer + ``` + + The roles the wiki takes from the provider are `Admin` and `Authenticated`. Change them with the property + `jspwiki.oidc.roles`, a comma separated list. +4. In `WEB-INF/web.xml`, remove the comment marks around the OpenID Connect filters. +5. In the provider, register the address `https://your.wiki/oidc/callback` as redirect URI, and the address of the wiki as post logout + redirect URI if the provider has that setting. + +The links to log in and out of the wiki then use the provider: `Login.jsp` sends the user to it, and `Logout.jsp` ends the session of the +wiki and of the provider. The wiki is not asked for passwords, and its own user profiles are not used. + +## Providers + +Keycloak: the roles are in the access token, in the nested claim `realm_access.roles`. + +``` +oidc.discoveryUri=https://keycloak.example.org/realms/jspwiki/.well-known/openid-configuration +oidc.rolesClaim=realm_access.roles +``` + +Microsoft Entra ID (Azure): register the application with the redirect URI, create a client secret and define application roles +(App roles) for the administrators, which Entra sends in the claim `roles`. Use the tenant in the discovery address. + +``` +oidc.discoveryUri=https://login.microsoftonline.com/TENANT-ID/v2.0/.well-known/openid-configuration +oidc.usernameClaim=preferred_username +oidc.rolesClaim=roles +``` + +Google: create an OAuth client of type web application. Google does not send roles, so all its users are authenticated users of the wiki, +and the administrators can be defined with the groups of the wiki. + +``` +oidc.discoveryUri=https://accounts.google.com/.well-known/openid-configuration +oidc.usernameClaim=email +``` diff --git a/jspwiki-oidc/pom.xml b/jspwiki-oidc/pom.xml new file mode 100644 index 0000000000..a49b56d242 --- /dev/null +++ b/jspwiki-oidc/pom.xml @@ -0,0 +1,86 @@ + + + + + + org.apache.jspwiki + jspwiki-builder + 3.0.1-SNAPSHOT + + + 4.0.0 + jspwiki-oidc + Apache JSPWiki OpenID Connect login + + + 6.5.5 + 8.0.3 + + + + + org.pac4j + jakartaee-pac4j + ${jakartaee-pac4j.version} + + + + org.pac4j + pac4j-oidc + ${pac4j.version} + + + + ${project.groupId} + jspwiki-main + ${project.version} + provided + + + + org.slf4j + slf4j-api + + + + jakarta.servlet + jakarta.servlet-api + provided + + + + org.junit.jupiter + junit-jupiter-api + test + + + + org.junit.jupiter + junit-jupiter-engine + test + + + + org.mockito + mockito-core + test + + + diff --git a/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/ClaimRolesAuthorizationGenerator.java b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/ClaimRolesAuthorizationGenerator.java new file mode 100644 index 0000000000..2e682668a8 --- /dev/null +++ b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/ClaimRolesAuthorizationGenerator.java @@ -0,0 +1,108 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.text.ParseException; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.pac4j.core.authorization.generator.AuthorizationGenerator; +import org.pac4j.core.context.CallContext; +import org.pac4j.core.profile.UserProfile; +import org.pac4j.oidc.profile.OidcProfile; + +import com.nimbusds.jwt.JWTParser; + +/** + * Takes the roles of the user from a claim of the profile or of the access token, as {@code roles} in Azure or + * {@code realm_access.roles} in Keycloak. + */ +class ClaimRolesAuthorizationGenerator implements AuthorizationGenerator { + + private final String claim; + private final Map< String, String > mapping; + + ClaimRolesAuthorizationGenerator( final String claim, final Map< String, String > mapping ) { + this.claim = claim; + this.mapping = mapping; + } + + /** {@inheritDoc} */ + @Override + public Optional< UserProfile > generate( final CallContext context, final UserProfile profile ) { + final Map< String, Object > claims = new HashMap<>( profile.getAttributes() ); + if( profile instanceof OidcProfile && ( ( OidcProfile )profile ).getAccessToken() != null ) { + try { + claims.putAll( JWTParser.parse( ( ( OidcProfile )profile ).getAccessToken().getValue() ).getJWTClaimsSet().getClaims() ); + } catch( final ParseException e ) { + // the access token is opaque, so the roles can only be in the profile + } + } + profile.addRoles( rolesFrom( claims ) ); + return Optional.of( profile ); + } + + /** + * Reads the roles from a set of claims. + * + * @param claims the claims of the profile and of the access token + * @return the names of the roles of the wiki + */ + Set< String > rolesFrom( final Map< String, Object > claims ) { + final Set< String > roles = new LinkedHashSet<>(); + final Object value = lookup( claims, claim ); + if( value instanceof Collection ) { + for( final Object item : ( Collection< ? > )value ) { + add( roles, item ); + } + } else { + add( roles, value ); + } + return roles; + } + + private void add( final Set< String > roles, final Object value ) { + if( value != null && !value.toString().isBlank() ) { + final String text = value.toString().trim(); + roles.add( mapping.getOrDefault( text, text ) ); + } + } + + /** + * Looks a claim up by its name or, if there is none with that name, by a path of names separated by dots through nested claims. + */ + static Object lookup( final Map< String, Object > claims, final String path ) { + if( claims.containsKey( path ) ) { + return claims.get( path ); + } + Object current = claims; + for( final String part : path.split( "\\." ) ) { + if( !( current instanceof Map ) ) { + return null; + } + current = ( ( Map< ?, ? > )current ).get( part ); + } + return current; + } + +} diff --git a/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcAuthorizer.java b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcAuthorizer.java new file mode 100644 index 0000000000..985fe9dca2 --- /dev/null +++ b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcAuthorizer.java @@ -0,0 +1,52 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.util.Arrays; +import java.util.Properties; + +import org.apache.wiki.api.core.Engine; +import org.apache.wiki.auth.authorize.Role; +import org.apache.wiki.auth.authorize.WebContainerAuthorizer; + +/** + * Authorizer for wikis whose users log in with OpenID Connect. The login is done by filters and not by constraints of the web + * application descriptor, so this authorizer declares that the container handles the login, and takes the names of the roles + * from the property {@code jspwiki.oidc.roles}, a comma separated list that defaults to {@code Admin,Authenticated}. + */ +public class OidcAuthorizer extends WebContainerAuthorizer { + + /** Property with the comma separated names of the roles the identity provider may grant. */ + public static final String PROP_ROLES = "jspwiki.oidc.roles"; + + private static final String DEFAULT_ROLES = "Admin,Authenticated"; + + /** {@inheritDoc} */ + @Override + public void initialize( final Engine engine, final Properties props ) { + super.initialize( engine, props ); + m_containerAuthorized = true; + m_containerRoles = Arrays.stream( props.getProperty( PROP_ROLES, DEFAULT_ROLES ).split( "," ) ) + .map( String::trim ) + .filter( name -> !name.isEmpty() ) + .map( Role::new ) + .toArray( Role[]::new ); + } + +} diff --git a/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcConfigFactory.java b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcConfigFactory.java new file mode 100644 index 0000000000..ed1c68c081 --- /dev/null +++ b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcConfigFactory.java @@ -0,0 +1,72 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import org.pac4j.core.client.Client; +import org.pac4j.core.client.Clients; +import org.pac4j.core.config.Config; +import org.pac4j.core.config.ConfigFactory; +import org.pac4j.core.context.CallContext; +import org.pac4j.core.engine.DefaultLogoutLogic; +import org.pac4j.core.http.callback.NoParameterCallbackUrlResolver; +import org.pac4j.core.http.url.DefaultUrlResolver; +import org.pac4j.core.http.url.UrlResolver; +import org.pac4j.oidc.client.OidcClient; +import org.pac4j.oidc.config.OidcConfiguration; + +import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod; + +/** + * Builds the pac4j configuration for any OpenID Connect provider, as Keycloak, Google or Microsoft Entra ID, from + * {@code jspwiki-oidc.properties}. + */ +public class OidcConfigFactory implements ConfigFactory { + + /** {@inheritDoc} */ + @Override + public Config build( final Object... parameters ) { + final OidcSettings settings = OidcSettings.load(); + final OidcConfiguration oidc = new OidcConfiguration(); + oidc.setClientId( settings.clientId() ); + oidc.setSecret( settings.secret() ); + oidc.setScope( settings.scope() ); + oidc.setDiscoveryURI( settings.discoveryUri() ); + oidc.setClientAuthenticationMethod( ClientAuthenticationMethod.CLIENT_SECRET_BASIC ); + final OidcClient client = new OidcClient( oidc ); + client.setName( OidcSettings.CLIENT_NAME ); + if( settings.rolesClaim() != null ) { + client.addAuthorizationGenerator( new ClaimRolesAuthorizationGenerator( settings.rolesClaim(), settings.roleMapping() ) ); + } + final UrlResolver urlResolver = new DefaultUrlResolver( true ); + client.setUrlResolver( urlResolver ); + final Clients clients = new Clients( settings.callbackUrl(), client ); + // there is a single client, so the callback URL needs no parameter and can be registered as is in the provider + clients.setCallbackUrlResolver( new NoParameterCallbackUrlResolver() ); + final Config config = new Config( clients ); + // the identity provider needs an absolute URL to return to after the logout + config.setLogoutLogic( new DefaultLogoutLogic() { + @Override + protected String enhanceRedirectUrl( final CallContext ctx, final Config config, final Client client, final String redirectUrl ) { + return urlResolver.compute( redirectUrl, ctx.webContext() ); + } + } ); + return config; + } + +} diff --git a/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcIdentityFilter.java b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcIdentityFilter.java new file mode 100644 index 0000000000..5020b93ee1 --- /dev/null +++ b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcIdentityFilter.java @@ -0,0 +1,86 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.io.IOException; +import java.util.Optional; +import java.util.Set; + +import org.pac4j.core.profile.ProfileManager; +import org.pac4j.core.profile.UserProfile; +import org.pac4j.jee.context.JEEContext; +import org.pac4j.jee.context.session.JEESessionStore; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +/** + * Hands the user logged in with OpenID Connect to the wiki. It has to run before {@code WikiServletFilter}, which takes + * the user from {@code getRemoteUser()} and {@code getUserPrincipal()} of the request, as it does with a container login. + */ +public class OidcIdentityFilter implements Filter { + + private String usernameClaim; + + /** {@inheritDoc} */ + @Override + public void init( final FilterConfig filterConfig ) { + usernameClaim = OidcSettings.load().usernameClaim(); + } + + /** {@inheritDoc} */ + @Override + public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException { + final HttpServletRequest req = ( HttpServletRequest )request; + if( req.getSession( false ) == null ) { + chain.doFilter( request, response ); + return; + } + final JEEContext context = new JEEContext( req, ( HttpServletResponse )response ); + final ProfileManager profiles = new ProfileManager( context, new JEESessionStore() ); + final Optional< UserProfile > profile = profiles.getProfile(); + if( profile.isPresent() ) { + final UserProfile user = profile.get(); + chain.doFilter( new OidcRequestWrapper( req, userName( user, usernameClaim ), Set.copyOf( user.getRoles() ) ), response ); + } else { + chain.doFilter( request, response ); + } + } + + /** + * Name of the user in the wiki: the claim configured for it, or else the e-mail address, or else the identifier of the user at + * the provider. + */ + static String userName( final UserProfile profile, final String claim ) { + for( final String name : new String[] { claim, "email" } ) { + final Object value = profile.getAttribute( name ); + if( value != null && !value.toString().isBlank() ) { + return value.toString().trim(); + } + } + return profile.getId(); + } + +} diff --git a/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcRequestWrapper.java b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcRequestWrapper.java new file mode 100644 index 0000000000..527ba11417 --- /dev/null +++ b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcRequestWrapper.java @@ -0,0 +1,59 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.security.Principal; +import java.util.Set; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; + +/** + * Presents the identity of an OpenID Connect login to the wiki as if the container had authenticated the user. + */ +class OidcRequestWrapper extends HttpServletRequestWrapper { + + private final Principal principal; + private final Set< String > roles; + + OidcRequestWrapper( final HttpServletRequest request, final String name, final Set< String > roles ) { + super( request ); + this.principal = () -> name; + this.roles = roles; + } + + /** {@inheritDoc} */ + @Override + public String getRemoteUser() { + return principal.getName(); + } + + /** {@inheritDoc} */ + @Override + public Principal getUserPrincipal() { + return principal; + } + + /** {@inheritDoc} */ + @Override + public boolean isUserInRole( final String role ) { + return roles.contains( role ) || super.isUserInRole( role ); + } + +} diff --git a/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcSettings.java b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcSettings.java new file mode 100644 index 0000000000..24398f0bbf --- /dev/null +++ b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcSettings.java @@ -0,0 +1,125 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + +/** + * Settings of the OpenID Connect login, read from {@code jspwiki-oidc.properties}, which has to be in the classpath of the web + * application. + */ +final class OidcSettings { + + static final String CONFIG_FILE = "/jspwiki-oidc.properties"; + + /** Name of the pac4j client, the one the filters of web.xml refer to. */ + static final String CLIENT_NAME = "jspwiki-oidc"; + + private static final String DEFAULT_SCOPE = "openid email profile"; + private static final String DEFAULT_USERNAME_CLAIM = "preferred_username"; + + private final Properties props; + + OidcSettings( final Properties props ) { + this.props = props; + } + + /** + * Loads the settings from the classpath. + * + * @return the settings + * @throws IllegalStateException if the file is missing or cannot be read + */ + static OidcSettings load() { + final Properties props = new Properties(); + try( InputStream in = OidcSettings.class.getResourceAsStream( CONFIG_FILE ) ) { + if( in == null ) { + throw new IllegalStateException( CONFIG_FILE + " not found in the classpath" ); + } + props.load( in ); + } catch( final IOException e ) { + throw new IllegalStateException( "Could not read " + CONFIG_FILE, e ); + } + return new OidcSettings( props ); + } + + String clientId() { + return required( "oidc.clientId" ); + } + + String secret() { + return required( "oidc.secret" ); + } + + String discoveryUri() { + return required( "oidc.discoveryUri" ); + } + + String callbackUrl() { + return required( "oidc.callbackUrl" ); + } + + String scope() { + return props.getProperty( "oidc.scope", DEFAULT_SCOPE ).trim(); + } + + /** @return the claim with the name of the user, {@code preferred_username} by default */ + String usernameClaim() { + return props.getProperty( "oidc.usernameClaim", DEFAULT_USERNAME_CLAIM ).trim(); + } + + /** @return the claim with the roles, which may be a dotted path, or {@code null} if the provider does not send roles */ + String rolesClaim() { + final String claim = props.getProperty( "oidc.rolesClaim" ); + return claim == null || claim.isBlank() ? null : claim.trim(); + } + + /** + * Mapping from the values of the roles claim to the names of the roles of the wiki, for the providers that send identifiers + * instead of names. It is written {@code value=Role,value2=Role2}. + * + * @return the mapping, empty if there is none + */ + Map< String, String > roleMapping() { + final Map< String, String > mapping = new LinkedHashMap<>(); + final String value = props.getProperty( "oidc.roleMapping" ); + if( value != null ) { + for( final String pair : value.split( "," ) ) { + final int eq = pair.indexOf( '=' ); + if( eq > 0 && eq < pair.length() - 1 ) { + mapping.put( pair.substring( 0, eq ).trim(), pair.substring( eq + 1 ).trim() ); + } + } + } + return mapping; + } + + private String required( final String key ) { + final String value = props.getProperty( key ); + if( value == null || value.isBlank() ) { + throw new IllegalStateException( CONFIG_FILE + " does not define " + key ); + } + return value.trim(); + } + +} diff --git a/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/ClaimRolesAuthorizationGeneratorTest.java b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/ClaimRolesAuthorizationGeneratorTest.java new file mode 100644 index 0000000000..a613eec569 --- /dev/null +++ b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/ClaimRolesAuthorizationGeneratorTest.java @@ -0,0 +1,69 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class ClaimRolesAuthorizationGeneratorTest { + + @Test + void readsAClaimWithAListOfRoles() { + final ClaimRolesAuthorizationGenerator generator = new ClaimRolesAuthorizationGenerator( "roles", Map.of() ); + Assertions.assertEquals( Set.of( "Admin", "Editors" ), generator.rolesFrom( Map.of( "roles", List.of( "Admin", "Editors" ) ) ) ); + } + + @Test + void readsAClaimWithASingleRole() { + final ClaimRolesAuthorizationGenerator generator = new ClaimRolesAuthorizationGenerator( "roles", Map.of() ); + Assertions.assertEquals( Set.of( "Admin" ), generator.rolesFrom( Map.of( "roles", "Admin" ) ) ); + } + + @Test + void followsADottedPathThroughNestedClaims() { + final ClaimRolesAuthorizationGenerator generator = new ClaimRolesAuthorizationGenerator( "realm_access.roles", Map.of() ); + final Map< String, Object > claims = Map.of( "realm_access", Map.of( "roles", List.of( "Authenticated", "Admin" ) ) ); + Assertions.assertEquals( Set.of( "Authenticated", "Admin" ), generator.rolesFrom( claims ) ); + } + + @Test + void prefersAClaimWhoseNameHasDots() { + final ClaimRolesAuthorizationGenerator generator = new ClaimRolesAuthorizationGenerator( "https://example.org/roles", Map.of() ); + Assertions.assertEquals( Set.of( "Admin" ), generator.rolesFrom( Map.of( "https://example.org/roles", List.of( "Admin" ) ) ) ); + } + + @Test + void mapsIdentifiersToRolesAndKeepsTheOtherValues() { + final ClaimRolesAuthorizationGenerator generator = new ClaimRolesAuthorizationGenerator( "groups", Map.of( "1111-aaaa", "Admin" ) ); + Assertions.assertEquals( Set.of( "Admin", "Readers" ), generator.rolesFrom( Map.of( "groups", List.of( "1111-aaaa", "Readers" ) ) ) ); + } + + @Test + void givesNoRolesWhenTheClaimIsMissingOrBlank() { + final ClaimRolesAuthorizationGenerator generator = new ClaimRolesAuthorizationGenerator( "roles", Map.of() ); + Assertions.assertTrue( generator.rolesFrom( Map.of() ).isEmpty() ); + Assertions.assertTrue( generator.rolesFrom( Map.of( "roles", List.of( " ", "" ) ) ).isEmpty() ); + Assertions.assertTrue( generator.rolesFrom( Map.of( "other", "x" ) ).isEmpty() ); + } + +} diff --git a/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcAuthorizerTest.java b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcAuthorizerTest.java new file mode 100644 index 0000000000..3fd7eb0732 --- /dev/null +++ b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcAuthorizerTest.java @@ -0,0 +1,57 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.util.Arrays; +import java.util.Properties; +import java.util.stream.Collectors; + +import org.apache.wiki.api.core.Engine; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class OidcAuthorizerTest { + + private OidcAuthorizer initialized( final Properties props ) { + final OidcAuthorizer authorizer = new OidcAuthorizer(); + authorizer.initialize( Mockito.mock( Engine.class ), props ); + return authorizer; + } + + @Test + void declaresThatTheContainerHandlesTheLogin() { + Assertions.assertTrue( initialized( new Properties() ).isContainerAuthorized() ); + } + + @Test + void knowsAdminAndAuthenticatedByDefault() { + final String names = Arrays.stream( initialized( new Properties() ).getRoles() ).map( r -> r.getName() ).sorted().collect( Collectors.joining( "," ) ); + Assertions.assertEquals( "Admin,Authenticated", names ); + } + + @Test + void takesTheRolesFromTheProperty() { + final Properties props = new Properties(); + props.setProperty( OidcAuthorizer.PROP_ROLES, " Editors , Admin ,," ); + final String names = Arrays.stream( initialized( props ).getRoles() ).map( r -> r.getName() ).sorted().collect( Collectors.joining( "," ) ); + Assertions.assertEquals( "Admin,Editors", names ); + } + +} diff --git a/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcIdentityFilterTest.java b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcIdentityFilterTest.java new file mode 100644 index 0000000000..c1f5345aff --- /dev/null +++ b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcIdentityFilterTest.java @@ -0,0 +1,53 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.pac4j.core.profile.CommonProfile; + +class OidcIdentityFilterTest { + + private CommonProfile profile() { + final CommonProfile profile = new CommonProfile(); + profile.setId( "subject-1" ); + return profile; + } + + @Test + void usesTheConfiguredClaimAsTheName() { + final CommonProfile profile = profile(); + profile.addAttribute( "preferred_username", "kcuser" ); + profile.addAttribute( "email", "kcuser@example.org" ); + Assertions.assertEquals( "kcuser", OidcIdentityFilter.userName( profile, "preferred_username" ) ); + } + + @Test + void fallsBackToTheEmailAddress() { + final CommonProfile profile = profile(); + profile.addAttribute( "email", "someone@example.org" ); + Assertions.assertEquals( "someone@example.org", OidcIdentityFilter.userName( profile, "preferred_username" ) ); + } + + @Test + void fallsBackToTheIdentifierOfTheUser() { + Assertions.assertEquals( "subject-1", OidcIdentityFilter.userName( profile(), "preferred_username" ) ); + } + +} diff --git a/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcRequestWrapperTest.java b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcRequestWrapperTest.java new file mode 100644 index 0000000000..76b2149107 --- /dev/null +++ b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcRequestWrapperTest.java @@ -0,0 +1,52 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.util.Set; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import jakarta.servlet.http.HttpServletRequest; + +class OidcRequestWrapperTest { + + private final HttpServletRequest request = Mockito.mock( HttpServletRequest.class ); + private final OidcRequestWrapper wrapper = new OidcRequestWrapper( request, "kcuser", Set.of( "Authenticated" ) ); + + @Test + void presentsTheLoggedInUserAsContainerUser() { + Assertions.assertEquals( "kcuser", wrapper.getRemoteUser() ); + Assertions.assertEquals( "kcuser", wrapper.getUserPrincipal().getName() ); + } + + @Test + void grantsTheRolesOfTheIdentityProvider() { + Assertions.assertTrue( wrapper.isUserInRole( "Authenticated" ) ); + Assertions.assertFalse( wrapper.isUserInRole( "Admin" ) ); + } + + @Test + void keepsTheRolesOfTheWrappedRequest() { + Mockito.when( request.isUserInRole( "Admin" ) ).thenReturn( true ); + Assertions.assertTrue( wrapper.isUserInRole( "Admin" ) ); + } + +} diff --git a/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcSettingsTest.java b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcSettingsTest.java new file mode 100644 index 0000000000..690cdb90c8 --- /dev/null +++ b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcSettingsTest.java @@ -0,0 +1,68 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you 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.apache.wiki.oidc; + +import java.util.Properties; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class OidcSettingsTest { + + private Properties required() { + final Properties props = new Properties(); + props.setProperty( "oidc.clientId", "id" ); + props.setProperty( "oidc.secret", "secret" ); + props.setProperty( "oidc.discoveryUri", "https://idp.example.org/.well-known/openid-configuration" ); + props.setProperty( "oidc.callbackUrl", "/oidc/callback" ); + return props; + } + + @Test + void usesDefaults() { + final OidcSettings settings = new OidcSettings( required() ); + Assertions.assertEquals( "openid email profile", settings.scope() ); + Assertions.assertEquals( "preferred_username", settings.usernameClaim() ); + Assertions.assertNull( settings.rolesClaim() ); + Assertions.assertTrue( settings.roleMapping().isEmpty() ); + } + + @Test + void failsWhenARequiredSettingIsMissing() { + final Properties props = required(); + props.remove( "oidc.discoveryUri" ); + final IllegalStateException e = Assertions.assertThrows( IllegalStateException.class, () -> new OidcSettings( props ).discoveryUri() ); + Assertions.assertTrue( e.getMessage().contains( "oidc.discoveryUri" ) ); + } + + @Test + void readsTheClaimsAndTheRoleMapping() { + final Properties props = required(); + props.setProperty( "oidc.usernameClaim", " email " ); + props.setProperty( "oidc.rolesClaim", "roles" ); + props.setProperty( "oidc.roleMapping", "1111-aaaa = Admin, 2222-bbbb=Editors,broken,=x,y=" ); + final OidcSettings settings = new OidcSettings( props ); + Assertions.assertEquals( "email", settings.usernameClaim() ); + Assertions.assertEquals( "roles", settings.rolesClaim() ); + Assertions.assertEquals( 2, settings.roleMapping().size() ); + Assertions.assertEquals( "Admin", settings.roleMapping().get( "1111-aaaa" ) ); + Assertions.assertEquals( "Editors", settings.roleMapping().get( "2222-bbbb" ) ); + } + +} diff --git a/jspwiki-oidc/src/test/resources/WEB-INF/web.xml b/jspwiki-oidc/src/test/resources/WEB-INF/web.xml new file mode 100644 index 0000000000..703b4cb02b --- /dev/null +++ b/jspwiki-oidc/src/test/resources/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + + jspwiki-oidc test + diff --git a/jspwiki-war/pom.xml b/jspwiki-war/pom.xml index 2bfaa2ccea..9007912542 100644 --- a/jspwiki-war/pom.xml +++ b/jspwiki-war/pom.xml @@ -270,4 +270,18 @@ + + + + + oidc + + + ${project.groupId} + jspwiki-oidc + ${project.version} + + + + diff --git a/jspwiki-war/src/main/webapp/WEB-INF/web.xml b/jspwiki-war/src/main/webapp/WEB-INF/web.xml index afce534d0d..a5f1c2d87e 100644 --- a/jspwiki-war/src/main/webapp/WEB-INF/web.xml +++ b/jspwiki-war/src/main/webapp/WEB-INF/web.xml @@ -74,6 +74,90 @@ org.apache.wiki.ui.WikiJSPFilter + + + WikiServletFilter /attach/* diff --git a/pom.xml b/pom.xml index e4f24c55df..997fec5399 100644 --- a/pom.xml +++ b/pom.xml @@ -146,6 +146,7 @@ jspwiki-http jspwiki-wysiwyg jspwiki-main + jspwiki-oidc jspwiki-markdown jspwiki-tika-searchprovider jspwiki-kendra-searchprovider