diff --git a/ChangeLog.md b/ChangeLog.md index 7f9a870113..d07dcb1fd1 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -16,6 +16,15 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> +**2026-11-20 Arturo Bernal (abernal AT apache DOT org)** + +* _3.0.2-git-2_ + +* 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 +* [JSPWIKI-1375](https://issues.apache.org/jira/browse/JSPWIKI-1375): the tests of the OpenID Connect login run the whole login, the identity of the next requests and the logout through the filters of `web.xml` in an embedded Tomcat, against an OpenID Connect provider that runs in the test +* [JSPWIKI-1375](https://issues.apache.org/jira/browse/JSPWIKI-1375): the first login with OpenID Connect creates the profile of the user in the user database of the wiki, with the full name and the e-mail address that the provider sends + **2026-11-19 Arturo Bernal (abernal AT apache DOT org)** * _3.0.2-git-1_ 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 26cb6a0efa..ad73c8ffa7 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 = "1"; + public static final String BUILD = "2"; /** * 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..6bc1abb700 --- /dev/null +++ b/jspwiki-oidc/README.md @@ -0,0 +1,95 @@ + + + +# 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. + +The first time a user logs in, the wiki creates a profile in its user database with the full name (the claim `name`, or else +`given_name` and `family_name`, or else the login name) and the e-mail address (the claim `email`) that the provider sends, so that +the wiki shows the name of the person and can write to them. The profile has no password. A profile that exists is never changed by +the login, and none is created if another user already has the same full name or wiki name. + +## 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..f3b5bec3db --- /dev/null +++ b/jspwiki-oidc/pom.xml @@ -0,0 +1,93 @@ + + + + + + org.apache.jspwiki + jspwiki-builder + 3.0.2-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 + + + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat.version} + 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..9e63be907d --- /dev/null +++ b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcIdentityFilter.java @@ -0,0 +1,113 @@ +/* + 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.apache.wiki.api.core.Engine; +import org.apache.wiki.auth.UserManager; +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.ServletContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; + +/** + * 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 { + + /** Session attribute that says the profile of the user was looked for, so that it is done once per session. */ + private static final String PROVISIONED = "jspwiki.oidc.provisioned"; + + /** Attribute of the servlet context where the wiki keeps its engine. */ + private static final String ENGINE = "org.apache.wiki.WikiEngine"; + + private String usernameClaim; + private ServletContext servletContext; + + /** {@inheritDoc} */ + @Override + public void init( final FilterConfig filterConfig ) { + usernameClaim = OidcSettings.load().usernameClaim(); + servletContext = filterConfig.getServletContext(); + } + + /** {@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(); + final String name = userName( user, usernameClaim ); + provision( req, name, user ); + chain.doFilter( new OidcRequestWrapper( req, name, Set.copyOf( user.getRoles() ) ), response ); + } else { + chain.doFilter( request, response ); + } + } + + /** Creates the profile of the user in the wiki, once per session. Nothing is done if the wiki is not running. */ + private void provision( final HttpServletRequest req, final String name, final UserProfile user ) { + final HttpSession session = req.getSession( false ); + if( session == null || session.getAttribute( PROVISIONED ) != null ) { + return; + } + final Object engine = servletContext == null ? null : servletContext.getAttribute( ENGINE ); + if( engine instanceof Engine ) { + OidcUserProvisioner.provision( ( ( Engine )engine ).getManager( UserManager.class ).getUserDatabase(), name, user ); + session.setAttribute( PROVISIONED, Boolean.TRUE ); + } + } + + /** + * 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/main/java/org/apache/wiki/oidc/OidcUserProvisioner.java b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcUserProvisioner.java new file mode 100644 index 0000000000..00bd9fdcd6 --- /dev/null +++ b/jspwiki-oidc/src/main/java/org/apache/wiki/oidc/OidcUserProvisioner.java @@ -0,0 +1,120 @@ +/* + 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.apache.wiki.auth.NoSuchPrincipalException; +import org.apache.wiki.auth.WikiSecurityException; +import org.apache.wiki.auth.user.UserDatabase; +import org.apache.wiki.auth.user.UserProfile; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Creates the profile of a user in the user database of the wiki the first time the user logs in with OpenID Connect, with the full + * name and the e-mail address that the provider sends, so that the wiki shows the name of the person and can write to them. An + * existing profile is left as it is, because the user may have changed it in the wiki. + */ +final class OidcUserProvisioner { + + private static final Logger LOG = LoggerFactory.getLogger( OidcUserProvisioner.class ); + + private OidcUserProvisioner() { + } + + /** + * Creates the profile if the database has none for the login name. + * + * @param database the user database of the wiki + * @param loginName the name the user has in the wiki + * @param identity the profile that the provider sent + * @return true if a profile was created + */ + static boolean provision( final UserDatabase database, final String loginName, final org.pac4j.core.profile.UserProfile identity ) { + if( loginName == null || loginName.isBlank() ) { + return false; + } + try { + database.findByLoginName( loginName ); + return false; + } catch( final NoSuchPrincipalException e ) { + // not there yet, created below + } + + String fullName = fullName( identity, loginName ); + if( taken( database, fullName ) ) { + fullName = loginName; + } + final String wikiName = fullName.replaceAll( "\\s+", "" ); + if( taken( database, fullName ) || isWikiNameTaken( database, wikiName ) ) { + LOG.warn( "The profile of {} was not created, the name {} is already used by another user", loginName, fullName ); + return false; + } + + final UserProfile profile = database.newProfile(); + profile.setLoginName( loginName ); + profile.setFullname( fullName ); + final Object email = identity.getAttribute( "email" ); + if( email != null && !email.toString().isBlank() ) { + profile.setEmail( email.toString().trim() ); + } + try { + database.save( profile ); + LOG.info( "Created the profile of {} from the OpenID Connect login", loginName ); + return true; + } catch( final WikiSecurityException e ) { + LOG.error( "The profile of {} could not be saved", loginName, e ); + return false; + } + } + + /** The claim {@code name}, or else the given and the family names, or else the login name. */ + private static String fullName( final org.pac4j.core.profile.UserProfile identity, final String loginName ) { + final String name = text( identity.getAttribute( "name" ) ); + if( name != null ) { + return name; + } + final String given = text( identity.getAttribute( "given_name" ) ); + final String family = text( identity.getAttribute( "family_name" ) ); + final String joined = ( ( given == null ? "" : given ) + " " + ( family == null ? "" : family ) ).trim(); + return joined.isEmpty() ? loginName : joined; + } + + private static String text( final Object value ) { + return value == null || value.toString().isBlank() ? null : value.toString().trim(); + } + + private static boolean taken( final UserDatabase database, final String fullName ) { + try { + database.findByFullName( fullName ); + return true; + } catch( final NoSuchPrincipalException e ) { + return false; + } + } + + private static boolean isWikiNameTaken( final UserDatabase database, final String wikiName ) { + try { + database.findByWikiName( wikiName ); + return true; + } catch( final NoSuchPrincipalException e ) { + return false; + } + } + +} 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/FakeOidcProvider.java b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/FakeOidcProvider.java new file mode 100644 index 0000000000..30f39ef512 --- /dev/null +++ b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/FakeOidcProvider.java @@ -0,0 +1,207 @@ +/* + 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.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.jwk.JWKSet; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jose.jwk.gen.RSAKeyGenerator; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +/** + * An OpenID Connect provider that runs in the test: discovery document, keys, authorization endpoint that signs the user in + * without asking anything, token endpoint and end session endpoint. It is just enough for the authorization code flow. + */ +final class FakeOidcProvider { + + static final String CLIENT_ID = "jspwiki-test"; + static final String CLIENT_SECRET = "test-secret"; + + /** Claim with the name of the user. A null value leaves the claim out of the tokens. */ + volatile String username = "kcuser"; + volatile String email = "kcuser@example.org"; + /** Roles in {@code realm_access.roles} of the access token. */ + volatile List< String > roles = List.of( "Admin", "viewer" ); + + /** What the provider saw, for the assertions. */ + volatile String lastScope; + volatile String lastIdTokenHint; + volatile int logouts; + + private final RSAKey key; + private final HttpServer server; + private final Map< String, String > nonces = new ConcurrentHashMap<>(); + + FakeOidcProvider() throws Exception { + key = new RSAKeyGenerator( 2048 ).keyID( "test-key" ).generate(); + server = HttpServer.create( new InetSocketAddress( InetAddress.getLoopbackAddress(), 0 ), 0 ); + server.createContext( "/.well-known/openid-configuration", this::discovery ); + server.createContext( "/jwks", this::jwks ); + server.createContext( "/authorize", this::authorize ); + server.createContext( "/token", this::token ); + server.createContext( "/logout", this::logout ); + server.start(); + } + + String issuer() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + String discoveryUri() { + return issuer() + "/.well-known/openid-configuration"; + } + + void stop() { + server.stop( 0 ); + } + + private void discovery( final HttpExchange exchange ) throws IOException { + final String iss = issuer(); + reply( exchange, 200, "application/json", "{" + + "\"issuer\":\"" + iss + "\"," + + "\"authorization_endpoint\":\"" + iss + "/authorize\"," + + "\"token_endpoint\":\"" + iss + "/token\"," + + "\"jwks_uri\":\"" + iss + "/jwks\"," + + "\"end_session_endpoint\":\"" + iss + "/logout\"," + + "\"response_types_supported\":[\"code\"]," + + "\"subject_types_supported\":[\"public\"]," + + "\"id_token_signing_alg_values_supported\":[\"RS256\"]," + + "\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\"]}" ); + } + + private void jwks( final HttpExchange exchange ) throws IOException { + reply( exchange, 200, "application/json", new JWKSet( key.toPublicJWK() ).toString() ); + } + + /** Signs the user in at once and sends the browser back to the application with a code. */ + private void authorize( final HttpExchange exchange ) throws IOException { + final Map< String, String > query = parameters( exchange.getRequestURI().getRawQuery() ); + if( !CLIENT_ID.equals( query.get( "client_id" ) ) || !"code".equals( query.get( "response_type" ) ) ) { + reply( exchange, 400, "text/plain", "bad authorization request" ); + return; + } + lastScope = query.get( "scope" ); + final String code = UUID.randomUUID().toString(); + nonces.put( code, query.getOrDefault( "nonce", "" ) ); + final String back = query.get( "redirect_uri" ) + ( query.get( "redirect_uri" ).contains( "?" ) ? "&" : "?" ) + + "code=" + code + "&state=" + java.net.URLEncoder.encode( query.get( "state" ), StandardCharsets.UTF_8 ); + redirect( exchange, back ); + } + + private void token( final HttpExchange exchange ) throws IOException { + final String expected = "Basic " + Base64.getEncoder().encodeToString( ( CLIENT_ID + ":" + CLIENT_SECRET ).getBytes( StandardCharsets.UTF_8 ) ); + if( !expected.equals( exchange.getRequestHeaders().getFirst( "Authorization" ) ) ) { + reply( exchange, 401, "application/json", "{\"error\":\"invalid_client\"}" ); + return; + } + final Map< String, String > form = parameters( new String( exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8 ) ); + final String nonce = nonces.remove( form.get( "code" ) ); + if( nonce == null ) { + reply( exchange, 400, "application/json", "{\"error\":\"invalid_grant\"}" ); + return; + } + try { + final JWTClaimsSet.Builder id = base( CLIENT_ID ).claim( "nonce", nonce ); + if( username != null ) { + id.claim( "preferred_username", username ); + } + if( email != null ) { + id.claim( "email", email ); + } + final JWTClaimsSet.Builder access = base( "account" ).claim( "realm_access", Map.of( "roles", roles ) ); + reply( exchange, 200, "application/json", "{\"access_token\":\"" + sign( access ) + "\",\"token_type\":\"Bearer\"," + + "\"expires_in\":300,\"id_token\":\"" + sign( id ) + "\"}" ); + } catch( final Exception e ) { + throw new IOException( e ); + } + } + + private void logout( final HttpExchange exchange ) throws IOException { + final Map< String, String > query = parameters( exchange.getRequestURI().getRawQuery() ); + logouts++; + lastIdTokenHint = query.get( "id_token_hint" ); + final String back = query.get( "post_logout_redirect_uri" ); + if( back == null ) { + reply( exchange, 200, "text/plain", "signed out" ); + } else { + redirect( exchange, back ); + } + } + + private JWTClaimsSet.Builder base( final String audience ) { + final Date now = new Date(); + return new JWTClaimsSet.Builder().issuer( issuer() ).subject( "user-1" ).audience( audience ) + .issueTime( now ).expirationTime( new Date( now.getTime() + 300_000 ) ); + } + + private String sign( final JWTClaimsSet.Builder claims ) throws Exception { + final SignedJWT jwt = new SignedJWT( new JWSHeader.Builder( JWSAlgorithm.RS256 ).keyID( key.getKeyID() ).build(), claims.build() ); + jwt.sign( new RSASSASigner( key ) ); + return jwt.serialize(); + } + + private static Map< String, String > parameters( final String raw ) { + final Map< String, String > map = new HashMap<>(); + if( raw != null ) { + for( final String pair : raw.split( "&" ) ) { + final int eq = pair.indexOf( '=' ); + if( eq > 0 ) { + map.put( pair.substring( 0, eq ), URLDecoder.decode( pair.substring( eq + 1 ), StandardCharsets.UTF_8 ) ); + } + } + } + return map; + } + + private static void redirect( final HttpExchange exchange, final String location ) throws IOException { + exchange.getResponseHeaders().add( "Location", URI.create( location ).toString() ); + exchange.sendResponseHeaders( 302, -1 ); + exchange.close(); + } + + private static void reply( final HttpExchange exchange, final int status, final String type, final String body ) throws IOException { + final byte[] bytes = body.getBytes( StandardCharsets.UTF_8 ); + exchange.getResponseHeaders().add( "Content-Type", type ); + exchange.sendResponseHeaders( status, bytes.length ); + try( OutputStream out = exchange.getResponseBody() ) { + out.write( bytes ); + } + } + +} 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/OidcLoginFlowTest.java b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcLoginFlowTest.java new file mode 100644 index 0000000000..f75d53b049 --- /dev/null +++ b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcLoginFlowTest.java @@ -0,0 +1,201 @@ +/* + 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.net.CookieManager; +import java.net.CookiePolicy; +import java.net.ServerSocket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.apache.catalina.Context; +import org.apache.catalina.startup.Tomcat; +import org.apache.tomcat.util.descriptor.web.FilterDef; +import org.apache.tomcat.util.descriptor.web.FilterMap; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +/** + * Logs in, reads the identity and logs out through the filters of {@code web.xml}, in an embedded Tomcat, against an OpenID Connect + * provider that runs in the test. The wiki itself is not started: a servlet that says what the request knows about the user stands in + * for it, which is what {@code WikiServletFilter} reads. + */ +class OidcLoginFlowTest { + + private static FakeOidcProvider provider; + private static Tomcat tomcat; + private static Path settings; + private static int port; + + private HttpClient browser; + + @BeforeAll + static void start() throws Exception { + provider = new FakeOidcProvider(); + try( ServerSocket free = new ServerSocket( 0 ) ) { + port = free.getLocalPort(); + } + // The settings are read from the classpath, so the file goes where the classpath of the tests starts + settings = Path.of( OidcLoginFlowTest.class.getProtectionDomain().getCodeSource().getLocation().toURI() ).resolve( "jspwiki-oidc.properties" ); + Files.writeString( settings, "oidc.clientId=" + FakeOidcProvider.CLIENT_ID + "\n" + + "oidc.secret=" + FakeOidcProvider.CLIENT_SECRET + "\n" + + "oidc.discoveryUri=" + provider.discoveryUri() + "\n" + + "oidc.callbackUrl=http://localhost:" + port + "/oidc/callback\n" + + "oidc.rolesClaim=realm_access.roles\n", StandardCharsets.UTF_8 ); + + final Path base = Files.createTempDirectory( "oidc-tomcat" ); + tomcat = new Tomcat(); + tomcat.setBaseDir( base.toString() ); + tomcat.setPort( port ); + tomcat.getConnector(); + final Context context = tomcat.addContext( "", base.toString() ); + filter( context, "OidcCallbackFilter", "org.pac4j.jee.filter.CallbackFilter", "/oidc/callback", + "defaultUrl", "/Wiki.jsp", "renewSession", "true", "defaultClient", OidcSettings.CLIENT_NAME ); + filter( context, "OidcSecurityFilter", "org.pac4j.jee.filter.SecurityFilter", "/Login.jsp", + "configFactory", OidcConfigFactory.class.getName(), "clients", OidcSettings.CLIENT_NAME ); + filter( context, "OidcLogoutFilter", "org.pac4j.jee.filter.LogoutFilter", "/Logout.jsp", + "configFactory", OidcConfigFactory.class.getName(), "defaultUrl", "/Wiki.jsp", "localLogout", "true", + "centralLogout", "true", "destroySession", "true" ); + filter( context, "OidcIdentityFilter", OidcIdentityFilter.class.getName(), "/*" ); + Tomcat.addServlet( context, "who", new HttpServlet() { + private static final long serialVersionUID = 1L; + + @Override + protected void doGet( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + resp.setContentType( "text/plain" ); + resp.getWriter().write( "user=" + req.getRemoteUser() + ";admin=" + req.isUserInRole( "Admin" ) + + ";other=" + req.isUserInRole( "Other" ) ); + } + } ); + context.addServletMappingDecoded( "/*", "who" ); + tomcat.start(); + } + + @AfterAll + static void stop() throws Exception { + if( tomcat != null ) { + tomcat.stop(); + tomcat.destroy(); + } + if( provider != null ) { + provider.stop(); + } + if( settings != null ) { + Files.deleteIfExists( settings ); + } + } + + @BeforeEach + void newBrowser() { + provider.username = "kcuser"; + provider.email = "kcuser@example.org"; + provider.roles = List.of( "Admin", "viewer" ); + provider.logouts = 0; + browser = HttpClient.newBuilder().cookieHandler( new CookieManager( null, CookiePolicy.ACCEPT_ALL ) ) + .followRedirects( HttpClient.Redirect.NEVER ).build(); + } + + @Test + void anonymousVisitorHasNoIdentity() throws Exception { + Assertions.assertEquals( "user=null;admin=false;other=false", get( "/Wiki.jsp" ) ); + } + + @Test + void loginPageSendsTheVisitorToTheProviderAndBackWithTheNameAndTheRoles() throws Exception { + Assertions.assertEquals( "user=kcuser;admin=true;other=false", get( "/Login.jsp" ) ); + Assertions.assertTrue( provider.lastScope.contains( "openid" ), provider.lastScope ); + } + + @Test + void identityStaysForTheNextRequestsOfTheSession() throws Exception { + get( "/Login.jsp" ); + + Assertions.assertEquals( "user=kcuser;admin=true;other=false", get( "/Wiki.jsp" ) ); + Assertions.assertEquals( "user=kcuser;admin=true;other=false", get( "/Edit.jsp" ) ); + } + + @Test + void visitorWithoutTheAdminRoleIsNotAdmin() throws Exception { + provider.roles = List.of( "viewer" ); + + Assertions.assertEquals( "user=kcuser;admin=false;other=false", get( "/Login.jsp" ) ); + } + + @Test + void emailIsTheNameWhenTheProviderSendsNoUsername() throws Exception { + provider.username = null; + + Assertions.assertEquals( "user=kcuser@example.org;admin=true;other=false", get( "/Login.jsp" ) ); + } + + @Test + void logoutEndsTheSessionAtTheProviderAndComesBackAnonymous() throws Exception { + get( "/Login.jsp" ); + + final String after = get( "/Logout.jsp" ); + + Assertions.assertEquals( 1, provider.logouts ); + Assertions.assertNotNull( provider.lastIdTokenHint, "the provider is told which session to end" ); + Assertions.assertEquals( "user=null;admin=false;other=false", after ); + Assertions.assertEquals( "user=null;admin=false;other=false", get( "/Wiki.jsp" ) ); + } + + /** Gets the page and follows the redirects, as a browser does, and returns the body of the last answer. */ + private String get( final String path ) throws Exception { + URI uri = URI.create( "http://localhost:" + port + path ); + for( int redirects = 0; redirects < 10; redirects++ ) { + final HttpResponse< String > response = browser.send( HttpRequest.newBuilder( uri ).GET().build(), HttpResponse.BodyHandlers.ofString() ); + if( response.statusCode() / 100 != 3 ) { + Assertions.assertEquals( 200, response.statusCode(), response.body() ); + return response.body(); + } + uri = uri.resolve( response.headers().firstValue( "Location" ).orElseThrow() ); + } + throw new AssertionError( "too many redirects" ); + } + + private static void filter( final Context context, final String name, final String className, final String pattern, final String... params ) { + final FilterDef def = new FilterDef(); + def.setFilterName( name ); + def.setFilterClass( className ); + for( int i = 0; i < params.length; i += 2 ) { + def.addInitParameter( params[ i ], params[ i + 1 ] ); + } + context.addFilterDef( def ); + final FilterMap map = new FilterMap(); + map.setFilterName( name ); + map.addURLPattern( pattern ); + context.addFilterMap( map ); + } + +} 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/java/org/apache/wiki/oidc/OidcUserProvisionerTest.java b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcUserProvisionerTest.java new file mode 100644 index 0000000000..26453ac3d3 --- /dev/null +++ b/jspwiki-oidc/src/test/java/org/apache/wiki/oidc/OidcUserProvisionerTest.java @@ -0,0 +1,120 @@ +/* + 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.apache.wiki.auth.NoSuchPrincipalException; +import org.apache.wiki.auth.user.UserDatabase; +import org.apache.wiki.auth.user.UserProfile; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.pac4j.core.profile.CommonProfile; + +class OidcUserProvisionerTest { + + private UserDatabase database; + private UserProfile created; + + @BeforeEach + void emptyDatabase() throws Exception { + database = Mockito.mock( UserDatabase.class ); + Mockito.when( database.findByLoginName( Mockito.anyString() ) ).thenThrow( new NoSuchPrincipalException( "none" ) ); + Mockito.when( database.findByFullName( Mockito.anyString() ) ).thenThrow( new NoSuchPrincipalException( "none" ) ); + Mockito.when( database.findByWikiName( Mockito.anyString() ) ).thenThrow( new NoSuchPrincipalException( "none" ) ); + created = Mockito.mock( UserProfile.class ); + Mockito.when( database.newProfile() ).thenReturn( created ); + } + + private static CommonProfile identity( final String... attributes ) { + final CommonProfile profile = new CommonProfile(); + profile.setId( "subject-1" ); + for( int i = 0; i < attributes.length; i += 2 ) { + profile.addAttribute( attributes[ i ], attributes[ i + 1 ] ); + } + return profile; + } + + private UserProfile saved() throws Exception { + Mockito.verify( database ).save( created ); + return created; + } + + @Test + void createsTheProfileWithTheNameAndTheEmailOfTheProvider() throws Exception { + Assertions.assertTrue( OidcUserProvisioner.provision( database, "kcuser", identity( "name", "Ana Perez", "email", "ana@example.org" ) ) ); + + final UserProfile profile = saved(); + Mockito.verify( profile ).setLoginName( "kcuser" ); + Mockito.verify( profile ).setFullname( "Ana Perez" ); + Mockito.verify( profile ).setEmail( "ana@example.org" ); + Mockito.verify( profile, Mockito.never() ).setPassword( Mockito.any() ); + } + + @Test + void leavesAnExistingProfileAsItIs() throws Exception { + Mockito.doReturn( Mockito.mock( UserProfile.class ) ).when( database ).findByLoginName( "kcuser" ); + + Assertions.assertFalse( OidcUserProvisioner.provision( database, "kcuser", identity( "name", "Ana Perez" ) ) ); + + Mockito.verify( database, Mockito.never() ).save( Mockito.any() ); + } + + @Test + void usesTheGivenAndTheFamilyNameWhenThereIsNoName() throws Exception { + OidcUserProvisioner.provision( database, "kcuser", identity( "given_name", "Ana", "family_name", "Perez" ) ); + + Mockito.verify( saved() ).setFullname( "Ana Perez" ); + } + + @Test + void usesTheLoginNameWhenTheProviderSendsNoName() throws Exception { + OidcUserProvisioner.provision( database, "kcuser", identity() ); + + final UserProfile profile = saved(); + Mockito.verify( profile ).setFullname( "kcuser" ); + Mockito.verify( profile, Mockito.never() ).setEmail( Mockito.any() ); + } + + @Test + void usesTheLoginNameWhenAnotherUserHasTheFullName() throws Exception { + Mockito.doReturn( Mockito.mock( UserProfile.class ) ).when( database ).findByFullName( "Ana Perez" ); + + OidcUserProvisioner.provision( database, "kcuser", identity( "name", "Ana Perez" ) ); + + Mockito.verify( saved() ).setFullname( "kcuser" ); + } + + @Test + void createsNothingWhenEvenTheLoginNameIsTakenAsAName() throws Exception { + Mockito.doReturn( Mockito.mock( UserProfile.class ) ).when( database ).findByFullName( Mockito.anyString() ); + + Assertions.assertFalse( OidcUserProvisioner.provision( database, "kcuser", identity( "name", "Ana Perez" ) ) ); + + Mockito.verify( database, Mockito.never() ).save( Mockito.any() ); + } + + @Test + void createsNothingWithoutALoginName() throws Exception { + Assertions.assertFalse( OidcUserProvisioner.provision( database, " ", identity( "name", "Ana Perez" ) ) ); + + Mockito.verify( database, Mockito.never() ).save( Mockito.any() ); + } + +} 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 2c0ec67cf8..435a9265c6 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 ace1540292..18b97de44c 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