From 96528a787cb8ad16f27b3d448ebc2dcab6d27842 Mon Sep 17 00:00:00 2001 From: Daniel Yohan Date: Tue, 22 Dec 2020 10:42:16 -0300 Subject: [PATCH] Added user migration provider --- .gitignore | 15 + Dockerfile | 9 + .../.mvn/wrapper/MavenWrapperDownloader.java | 118 +++++++ .../.mvn/wrapper/maven-wrapper.properties | 2 + keycloak-user-migration/README.md | 159 +++++++++ keycloak-user-migration/mvnw | 322 ++++++++++++++++++ keycloak-user-migration/mvnw.cmd | 182 ++++++++++ keycloak-user-migration/pom.xml | 164 +++++++++ .../rest/ConfigurationProperties.java | 48 +++ .../providers/rest/LegacyProvider.java | 115 +++++++ .../providers/rest/LegacyProviderFactory.java | 32 ++ .../providers/rest/remote/LegacyUser.java | 130 +++++++ .../rest/remote/LegacyUserService.java | 12 + .../rest/remote/UserModelFactory.java | 156 +++++++++ .../rest/rest/BearerTokenRequestFilter.java | 18 + .../providers/rest/rest/RestUserClient.java | 18 + .../providers/rest/rest/RestUserService.java | 54 +++ .../providers/rest/rest/UserPasswordDto.java | 41 +++ ...eycloak.storage.UserStorageProviderFactory | 1 + .../rest/ConfigurationPropertiesTest.java | 14 + .../rest/LegacyProviderFactoryTest.java | 53 +++ .../providers/rest/LegacyProviderTest.java | 188 ++++++++++ .../providers/rest/remote/LegacyUserTest.java | 89 +++++ .../providers/rest/remote/TestUserModel.java | 236 +++++++++++++ .../rest/remote/UserModelFactoryTest.java | 298 ++++++++++++++++ .../rest/BearerTokenRequestFilterTest.java | 35 ++ .../rest/rest/RestUserServiceTest.java | 142 ++++++++ .../rest/rest/UserPasswordDtoTest.java | 30 ++ 28 files changed, 2681 insertions(+) create mode 100644 .gitignore create mode 100644 keycloak-user-migration/.mvn/wrapper/MavenWrapperDownloader.java create mode 100644 keycloak-user-migration/.mvn/wrapper/maven-wrapper.properties create mode 100644 keycloak-user-migration/README.md create mode 100755 keycloak-user-migration/mvnw create mode 100644 keycloak-user-migration/mvnw.cmd create mode 100644 keycloak-user-migration/pom.xml create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/ConfigurationProperties.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/LegacyProvider.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderFactory.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUser.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUserService.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/UserModelFactory.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/BearerTokenRequestFilter.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserClient.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserService.java create mode 100644 keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/UserPasswordDto.java create mode 100644 keycloak-user-migration/src/main/resources/META-INF/services/org.keycloak.storage.UserStorageProviderFactory create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/ConfigurationPropertiesTest.java create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderFactoryTest.java create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderTest.java create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUserTest.java create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/TestUserModel.java create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/UserModelFactoryTest.java create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/BearerTokenRequestFilterTest.java create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserServiceTest.java create mode 100644 keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/UserPasswordDtoTest.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67cb9ba --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +**/target/ +/target/ +*/target/* +.classpath +.project +.settings +.idea + +# Package Files # +*.jar +*.war +*.ear + +*.iml +*.idea \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 02b6e93..a8ce2e3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,13 @@ FROM quay.io/keycloak/keycloak:11.0.3 +USER root + +COPY ./keycloak-user-migration/ /project +RUN cd /project && ./mvnw clean package + +FROM quay.io/keycloak/keycloak:11.0.3 +USER root + +COPY --from=0 /project/target/*.jar /opt/jboss/keycloak/standalone/deployments/app.jar COPY ./themes/ilhasoft/ /opt/jboss/keycloak/themes/ilhasoft/ #COPY ./standalone.xml /opt/jboss/keycloak/standalone/configuration/standalone.xml diff --git a/keycloak-user-migration/.mvn/wrapper/MavenWrapperDownloader.java b/keycloak-user-migration/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..a45eb6b --- /dev/null +++ b/keycloak-user-migration/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://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. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/keycloak-user-migration/.mvn/wrapper/maven-wrapper.properties b/keycloak-user-migration/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/keycloak-user-migration/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/keycloak-user-migration/README.md b/keycloak-user-migration/README.md new file mode 100644 index 0000000..025998b --- /dev/null +++ b/keycloak-user-migration/README.md @@ -0,0 +1,159 @@ +# Keycloak user migration example + +![Code Soapbox logo](readme-images/logo.png) + +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=alert_status)](https://sonarcloud.io/dashboard?id=keycloak-user-migration) +[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=keycloak-user-migration) +[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=keycloak-user-migration) +[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=security_rating)](https://sonarcloud.io/dashboard?id=keycloak-user-migration) +[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=keycloak-user-migration) +[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=bugs)](https://sonarcloud.io/dashboard?id=keycloak-user-migration) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=coverage)](https://sonarcloud.io/dashboard?id=keycloak-user-migration) + +## Introduction + +This is a user migration plugin for Keycloak. Read more at: + +https://codesoapbox.dev/keycloak-user-migration + +## Compatibility + +| Keycloak Version | Commit | +|------------------|--------------------------------------------------------------------------------------------------------------------------------------------------| +| 11.X | Current | +| 9.X | [c9c64162b91cedc29d8bf360c3df50b69fdb4c6b](https://github.com/daniel-frak/keycloak-user-migration/tree/c9c64162b91cedc29d8bf360c3df50b69fdb4c6b) | + +## Prerequisites - REST endpoints in the legacy system + +You must provide two REST endpoints (GET and POST) in your legacy authentication system under the URI `${restClientUri +}/{$username}`, where `${restClientUri}` is a configurable base URL for the endpoints and `{$username}` is the +username of the user that is attempting to sign in. + +### GET +The GET request will have to return user data as a JSON response in the form: +```json +{ + "id": "string", + "username": "string", + "email": "string", + "firstName": "string", + "lastName": "string", + "enabled": "boolean", + "emailVerified": "boolean", + "attributes": { + "key": ["value"] + }, + "roles": ["string"], + "groups": ["string"] +} +``` + +Any HTTP status other than `200` will be interpreted as the user not having been found. + +The `id` attribute in the above response is optional. If it's not set Keycloak will generate a new user id automatically. + +### POST +The POST request is for password validation. It will have to accept the following body: +```json +{ + "password": "string" +} +``` + +...And return HTTP status 200 if the password is correct. Any other response will be treated as invalid credentials. + +### Example REST client behavior + +Let's assume we have configured the legacy REST service under the URL `http://www.old-legacy-system.com/auth`. + +If a user with the username `bob` and the password `password123` tries to log in through Keycloak for the first time +(giving correct credentials), a GET request will be performed to `http://www.old-legacy-system.com/auth/bob`. +The response might look like this: +```json +{ + "username": "bob", + "email": "bob@company.com", + "firstName": "Bob", + "lastName": "Smith", + "enabled": "true", + "emailVerified": "true", + "attributes": { + "position": ["rockstar-developer"], + "likes": ["cats", "dogs", "cookies"] + }, + "roles": ["admin"], + "groups": ["migrated_users"] +} +``` + +As the user has been found, a POST request will be performed to `http://www.old-legacy-system.com/auth/bob`, with +the body: +```json +{ + "password": "password123" +} +``` + +As this is the correct password, the user will be logged in. In the background, his information will be migrated to +Keycloak. + +## Launching and configuring the example +1. Navigate to `./docker` +2. Execute `docker-compose up` +3. Open `http://localhost:8024/auth/admin/` in a browser +4. Log in with the credentials: +* User: `admin` +* Password: `admin` +5. Navigate to "User federation": + +![Sidebar](readme-images/sidebar.png) + +6. Choose "User migration using a REST client" from the "Add provider..." dropdown: + +![User federation dropdown](readme-images/user-federation.png) + +7. Provide the legacy system endpoint URI in the "Rest client URI" field: + +![Rest client URI input](readme-images/field_rest_client_uri.png) + +8. Click "save": + +![Save button](readme-images/save_btn.png) + +User migration should now work - Keycloak will recognize all users from your legacy authentication system and migrate +them automatically. + +## Optional - additional configuration + +Additional configuration options are available for fine-tuning the migration. + +![Additional configuration](readme-images/config.png) + +### API Token + +The migration endpoint can be secured with an API token. The configured value will be sent as a bearer token in the authorization header. + +If the configured token value is set to `SECRET_API_TOKEN` when making the request to the migration endpoints, the rest client will send the following authorization header: +``` +Authorization: Bearer SECRET_API_TOKEN +``` + +### Legacy role conversion + +If role names in Keycloak do not perfectly match those in the legacy system, you can configure the provider to +automatically map legacy roles to Keycloak roles, by specifying the mapping in the format `legacyRole:keycloakRole`. + +### Migrate unmapped roles + +This switch can be toggled to decide whether roles which are not defined in the legacy role conversion map should be + migrated anyway or simply ignored. + +### Group role conversion + +If group names in Keycloak do not perfectly match those in the legacy system, you can configure the provider to +automatically map legacy groups to Keycloak groups, by specifying the mapping in the format `legacyGroup:keycloakGroup`. + +### Migrate unmapped groups + +This switch can be toggled to decide whether groups which are not defined in the legacy group conversion map should be + migrated anyway or simply ignored. diff --git a/keycloak-user-migration/mvnw b/keycloak-user-migration/mvnw new file mode 100755 index 0000000..3c8a553 --- /dev/null +++ b/keycloak-user-migration/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# 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 +# +# https://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/keycloak-user-migration/mvnw.cmd b/keycloak-user-migration/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/keycloak-user-migration/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/keycloak-user-migration/pom.xml b/keycloak-user-migration/pom.xml new file mode 100644 index 0000000..895f705 --- /dev/null +++ b/keycloak-user-migration/pom.xml @@ -0,0 +1,164 @@ + + + 4.0.0 + + com.danielfrak.code.keycloak.providers + keycloak-rest-provider + 1.0-SNAPSHOT + + 11 + 11.0.0 + 4.4.1.Final + + ${java.version} + ${java.version} + UTF-8 + + 0.8.5 + + + + + + org.keycloak + keycloak-core + ${keycloak.version} + provided + + + + + org.keycloak + keycloak-server-spi + ${keycloak.version} + provided + + + + + org.jboss.logging + jboss-logging + 3.4.1.Final + provided + + + + + org.junit.jupiter + junit-jupiter + 5.5.2 + test + + + + + org.junit.platform + junit-platform-engine + 1.5.2 + test + + + + + org.mockito + mockito-junit-jupiter + 3.2.4 + test + + + + + org.mockito + mockito-core + 3.2.4 + test + + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + + + + + nl.jqno.equalsverifier + equalsverifier + 3.4.1 + test + + + + + + + maven-surefire-plugin + 2.22.2 + + + org.junit.platform + junit-platform-surefire-provider + 1.3.2 + + + + + + + + + sonar-cloud + + keycloak-user-migration + codesoapbox + https://sonarcloud.io + + + + + + code-coverage + + test + test + false + false + false + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + + prepare-agent + + + + report + post-integration-test + + report + + + + + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + + + + \ No newline at end of file diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/ConfigurationProperties.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/ConfigurationProperties.java new file mode 100644 index 0000000..2732ea5 --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/ConfigurationProperties.java @@ -0,0 +1,48 @@ +package com.danielfrak.code.keycloak.providers.rest; + +import org.keycloak.provider.ProviderConfigProperty; + +import java.util.List; + +import static org.keycloak.provider.ProviderConfigProperty.*; + +public final class ConfigurationProperties { + + public static final String PROVIDER_NAME = "User migration using a REST client"; + public static final String URI_PROPERTY = "URI"; + public static final String API_TOKEN_PROPERTY = "API_TOKEN"; + public static final String ROLE_MAP_PROPERTY = "ROLE_MAP"; + public static final String GROUP_MAP_PROPERTY = "GROUP_MAP"; + public static final String MIGRATE_UNMAPPED_ROLES_PROPERTY = "MIGRATE_UNMAPPED_ROLES"; + public static final String MIGRATE_UNMAPPED_GROUPS_PROPERTY = "MIGRATE_UNMAPPED_GROUPS"; + + private static final List PROPERTIES = List.of( + new ProviderConfigProperty(URI_PROPERTY, + "Rest client URI (required)", "URI of the legacy system endpoints", + STRING_TYPE, null), + new ProviderConfigProperty(API_TOKEN_PROPERTY, + "Rest client API token", "Bearer token", + PASSWORD, null), + new ProviderConfigProperty(ROLE_MAP_PROPERTY, + "Legacy role conversion", "Role conversion in the format 'legacyRole:newRole'", + MULTIVALUED_STRING_TYPE, null), + new ProviderConfigProperty(MIGRATE_UNMAPPED_ROLES_PROPERTY, + "Migrate unmapped roles", + "Whether or not to migrate roles not found in the field above", + BOOLEAN_TYPE, true), + new ProviderConfigProperty(GROUP_MAP_PROPERTY, + "Legacy group conversion", "Group conversion in the format 'legacyGroup:newGroup'", + MULTIVALUED_STRING_TYPE, null), + new ProviderConfigProperty(MIGRATE_UNMAPPED_GROUPS_PROPERTY, + "Migrate unmapped groups", + "Whether or not to migrate groups not found in the field above", + BOOLEAN_TYPE, true) + ); + + private ConfigurationProperties() { + } + + public static List getConfigProperties() { + return PROPERTIES; + } +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/LegacyProvider.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/LegacyProvider.java new file mode 100644 index 0000000..0b48c71 --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/LegacyProvider.java @@ -0,0 +1,115 @@ +package com.danielfrak.code.keycloak.providers.rest; + +import com.danielfrak.code.keycloak.providers.rest.remote.LegacyUser; +import com.danielfrak.code.keycloak.providers.rest.remote.LegacyUserService; +import com.danielfrak.code.keycloak.providers.rest.remote.UserModelFactory; +import org.jboss.logging.Logger; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialInputUpdater; +import org.keycloak.credential.CredentialInputValidator; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; +import org.keycloak.models.credential.PasswordCredentialModel; +import org.keycloak.storage.UserStorageProvider; +import org.keycloak.storage.user.UserLookupProvider; + +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; + +/** + * Provides legacy user migration functionality + */ +public class LegacyProvider implements UserStorageProvider, + UserLookupProvider, + CredentialInputUpdater, + CredentialInputValidator { + + private static final Logger LOG = Logger.getLogger(LegacyProvider.class); + private static final Set supportedCredentialTypes = Collections.singleton(PasswordCredentialModel.TYPE); + private final KeycloakSession session; + private final LegacyUserService legacyUserService; + private final UserModelFactory userModelFactory; + + public LegacyProvider(KeycloakSession session, LegacyUserService legacyUserService, + UserModelFactory userModelFactory) { + this.session = session; + this.legacyUserService = legacyUserService; + this.userModelFactory = userModelFactory; + } + + @Override + public UserModel getUserByUsername(String username, RealmModel realm) { + return getUserModel(realm, username, () -> legacyUserService.findByUsername(username)); + } + + private UserModel getUserModel(RealmModel realm, String username, Supplier> user) { + return user.get() + .map(u -> userModelFactory.create(u, realm)) + .orElseGet(() -> { + LOG.warnf("User not found in external repository: %s", username); + return null; + }); + } + + @Override + public UserModel getUserByEmail(String email, RealmModel realm) { + return getUserModel(realm, email, () -> legacyUserService.findByEmail(email)); + } + + @Override + public boolean isValid(RealmModel realmModel, UserModel userModel, CredentialInput input) { + if (!supportsCredentialType(input.getType())) { + return false; + } + + if (legacyUserService.isPasswordValid(userModel.getUsername(), input.getChallengeResponse())) { + session.userCredentialManager().updateCredential(realmModel, userModel, input); + return true; + } + + return false; + } + + @Override + public boolean supportsCredentialType(String s) { + return supportedCredentialTypes.contains(s); + } + + @Override + public UserModel getUserById(String id, RealmModel realm) { + throw new UnsupportedOperationException("User lookup by id not implemented"); + } + + @Override + public boolean isConfiguredFor(RealmModel realmModel, UserModel userModel, String s) { + return false; + } + + @Override + public void close() { + // Not needed + } + + @Override + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + String link = user.getFederationLink(); + if (link != null && !link.isBlank()) { + user.setFederationLink(null); + } + return false; + } + + @Override + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + // Not needed + } + + @Override + public Set getDisableableCredentialTypes(RealmModel realm, UserModel user) { + return Collections.emptySet(); + } + +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderFactory.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderFactory.java new file mode 100644 index 0000000..50f28ca --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderFactory.java @@ -0,0 +1,32 @@ +package com.danielfrak.code.keycloak.providers.rest; + +import com.danielfrak.code.keycloak.providers.rest.remote.UserModelFactory; +import com.danielfrak.code.keycloak.providers.rest.rest.RestUserService; +import org.keycloak.component.ComponentModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.provider.ProviderConfigProperty; +import org.keycloak.storage.UserStorageProviderFactory; + +import javax.ws.rs.client.ClientBuilder; +import java.util.List; + +import static com.danielfrak.code.keycloak.providers.rest.ConfigurationProperties.PROVIDER_NAME; + +public class LegacyProviderFactory implements UserStorageProviderFactory { + + @Override + public List getConfigProperties() { + return ConfigurationProperties.getConfigProperties(); + } + + @Override + public LegacyProvider create(KeycloakSession session, ComponentModel model) { + var userModelFactory = new UserModelFactory(session, model); + return new LegacyProvider(session, new RestUserService(model, ClientBuilder.newClient()), userModelFactory); + } + + @Override + public String getId() { + return PROVIDER_NAME; + } +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUser.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUser.java new file mode 100644 index 0000000..b49fe79 --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUser.java @@ -0,0 +1,130 @@ +package com.danielfrak.code.keycloak.providers.rest.remote; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * A user in the old authentication system + */ +public class LegacyUser { + + private String id; + private String username; + private String email; + private String firstName; + private String lastName; + private boolean isEnabled; + private boolean isEmailVerified; + private Map> attributes; + private List roles; + private List groups; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public boolean isEnabled() { + return isEnabled; + } + + public void setEnabled(boolean enabled) { + isEnabled = enabled; + } + + public boolean isEmailVerified() { + return isEmailVerified; + } + + public void setEmailVerified(boolean emailVerified) { + isEmailVerified = emailVerified; + } + + public Map> getAttributes() { + return attributes; + } + + public void setAttributes(Map> attributes) { + this.attributes = attributes; + } + + public List getRoles() { + return roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } + + public List getGroups() { + return groups; + } + + public void setGroups(List groups) { + this.groups = groups; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LegacyUser legacyUser = (LegacyUser) o; + + return isEnabled == legacyUser.isEnabled && + isEmailVerified == legacyUser.isEmailVerified && + Objects.equals(id, legacyUser.id) && + Objects.equals(username, legacyUser.username) && + Objects.equals(email, legacyUser.email) && + Objects.equals(firstName, legacyUser.firstName) && + Objects.equals(lastName, legacyUser.lastName) && + Objects.equals(attributes, legacyUser.attributes) && + Objects.equals(roles, legacyUser.roles) && + Objects.equals(groups, legacyUser.groups); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, email, firstName, lastName, isEnabled, isEmailVerified, attributes, + roles, groups); + } +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUserService.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUserService.java new file mode 100644 index 0000000..60efaf0 --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUserService.java @@ -0,0 +1,12 @@ +package com.danielfrak.code.keycloak.providers.rest.remote; + +import java.util.Optional; + +public interface LegacyUserService { + + Optional findByEmail(String email); + + Optional findByUsername(String username); + + boolean isPasswordValid(String username, String password); +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/UserModelFactory.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/UserModelFactory.java new file mode 100644 index 0000000..3f447ec --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/remote/UserModelFactory.java @@ -0,0 +1,156 @@ +package com.danielfrak.code.keycloak.providers.rest.remote; + +import org.jboss.logging.Logger; +import org.keycloak.component.ComponentModel; +import org.keycloak.models.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Stream; + +import static com.danielfrak.code.keycloak.providers.rest.ConfigurationProperties.*; + +public class UserModelFactory { + + private static final Logger LOG = Logger.getLogger(UserModelFactory.class); + + private final KeycloakSession session; + private final ComponentModel model; + + /** + * String format: + * legacyRole:newRole + */ + private final Map roleMap; + /** + * String format: + * legacyGroup:newGroup + */ + private final Map groupMap; + + public UserModelFactory(KeycloakSession session, ComponentModel model) { + this.session = session; + this.model = model; + this.roleMap = legacyMap(model, ROLE_MAP_PROPERTY); + this.groupMap = legacyMap(model, GROUP_MAP_PROPERTY); + } + + /** + * Returns a map of legacy props to new one + */ + private Map legacyMap(ComponentModel model, String property) { + Map newRoleMap = new HashMap<>(); + List pairs = model.getConfig().getList(property); + for (String pair : pairs) { + String[] keyValue = pair.split(":"); + newRoleMap.put(keyValue[0], keyValue[1]); + } + return newRoleMap; + } + + public UserModel create(LegacyUser legacyUser, RealmModel realm) { + LOG.infof("Creating user model for: %s", legacyUser.getUsername()); + + UserModel userModel; + if (legacyUser.getId() == null) { + userModel = session.userLocalStorage().addUser(realm, legacyUser.getUsername()); + } else { + userModel = session.userLocalStorage().addUser( + realm, + legacyUser.getId(), + legacyUser.getUsername(), + true, + false + ); + } + + validateUsernamesEqual(legacyUser, userModel); + + userModel.setFederationLink(model.getId()); + userModel.setEnabled(legacyUser.isEnabled()); + userModel.setEmail(legacyUser.getEmail()); + userModel.setEmailVerified(legacyUser.isEmailVerified()); + userModel.setFirstName(legacyUser.getFirstName()); + userModel.setLastName(legacyUser.getLastName()); + + if (legacyUser.getAttributes() != null) { + legacyUser.getAttributes() + .forEach(userModel::setAttribute); + } + + getRoleModels(legacyUser, realm) + .forEach(userModel::grantRole); + + getGroupModels(legacyUser, realm) + .forEach(userModel::joinGroup); + + return userModel; + } + + private void validateUsernamesEqual(LegacyUser legacyUser, UserModel userModel) { + if (!userModel.getUsername().equals(legacyUser.getUsername())) { + throw new IllegalStateException(String.format("Local and remote users differ: [%s != %s]", + userModel.getUsername(), + legacyUser.getUsername())); + } + } + + private Stream getRoleModels(LegacyUser legacyUser, RealmModel realm) { + if (legacyUser.getRoles() == null) { + return Stream.empty(); + } + return legacyUser.getRoles().stream() + .map(r -> getRoleModel(realm, r)) + .filter(Optional::isPresent) + .map(Optional::get); + } + + private Optional getRoleModel(RealmModel realm, String role) { + if (roleMap.containsKey(role)) { + role = roleMap.get(role); + } else if (!isParseEnabledFor(MIGRATE_UNMAPPED_ROLES_PROPERTY)) { + return Optional.empty(); + } + if (role == null || role.equals("")) { + return Optional.empty(); + } + RoleModel roleModel = realm.getRole(role); + return Optional.ofNullable(roleModel); + } + + private Stream getGroupModels(LegacyUser legacyUser, RealmModel realm) { + if (legacyUser.getGroups() == null) { + return Stream.empty(); + } + + return legacyUser.getGroups().stream() + .map(group -> getGroupModel(realm, group)) + .filter(Optional::isPresent) + .map(Optional::get); + } + + private Optional getGroupModel(RealmModel realm, String group) { + if (groupMap.containsKey(group)) { + group = groupMap.get(group); + } else if (!isParseEnabledFor(MIGRATE_UNMAPPED_GROUPS_PROPERTY)) { + return Optional.empty(); + } + if (group == null || group.equals("")) { + return Optional.empty(); + } + + GroupModel realmGroup = realm.getGroupById(group); + + if (realmGroup == null) { + realmGroup = realm.createGroup(group); + } + + return Optional.of(realmGroup); + } + + private boolean isParseEnabledFor(String config) { + return Boolean.parseBoolean(model.getConfig().getFirst(config)); + } +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/BearerTokenRequestFilter.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/BearerTokenRequestFilter.java new file mode 100644 index 0000000..a3a40ea --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/BearerTokenRequestFilter.java @@ -0,0 +1,18 @@ +package com.danielfrak.code.keycloak.providers.rest.rest; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; + +public class BearerTokenRequestFilter implements ClientRequestFilter { + + private final String token; + + public BearerTokenRequestFilter(String token) { + this.token = token; + } + + @Override + public void filter(ClientRequestContext requestContext) { + requestContext.getHeaders().add("Authorization", "Bearer " + this.token); + } +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserClient.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserClient.java new file mode 100644 index 0000000..26584ad --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserClient.java @@ -0,0 +1,18 @@ +package com.danielfrak.code.keycloak.providers.rest.rest; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface RestUserClient { + + @GET + @Path("/{username}/") + Response findByUsername(@PathParam("username") String username); + + @POST + @Path("/{username}/") + Response validatePassword(@PathParam("username") String username, UserPasswordDto passwordDto); +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserService.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserService.java new file mode 100644 index 0000000..8345d7b --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserService.java @@ -0,0 +1,54 @@ +package com.danielfrak.code.keycloak.providers.rest.rest; + +import com.danielfrak.code.keycloak.providers.rest.remote.LegacyUser; +import com.danielfrak.code.keycloak.providers.rest.remote.LegacyUserService; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.keycloak.component.ComponentModel; + +import javax.ws.rs.client.Client; +import javax.ws.rs.core.Response; +import java.util.Optional; + +import static com.danielfrak.code.keycloak.providers.rest.ConfigurationProperties.API_TOKEN_PROPERTY; +import static com.danielfrak.code.keycloak.providers.rest.ConfigurationProperties.URI_PROPERTY; + +public class RestUserService implements LegacyUserService { + + private final RestUserClient client; + + public RestUserService(ComponentModel model, Client restEasyClient) { + String uri = model.getConfig().getFirst(URI_PROPERTY); + String token = model.getConfig().getFirst(API_TOKEN_PROPERTY); + this.client = buildClient(restEasyClient, uri, token); + } + + private RestUserClient buildClient(Client restEasyClient, String uri, String token) { + if (token != null && !token.isEmpty()) { + restEasyClient.register(new BearerTokenRequestFilter(token)); + } + + ResteasyWebTarget target = (ResteasyWebTarget) restEasyClient.target(uri); + + return target.proxy(RestUserClient.class); + } + + @Override + public Optional findByEmail(String email) { + return findByUsername(email); + } + + @Override + public Optional findByUsername(String username) { + final Response response = client.findByUsername(username); + if (response.getStatus() != 200) { + return Optional.empty(); + } + return Optional.ofNullable(response.readEntity(LegacyUser.class)); + } + + @Override + public boolean isPasswordValid(String username, String password) { + final Response response = client.validatePassword(username, new UserPasswordDto(password)); + return response.getStatus() == 200; + } +} diff --git a/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/UserPasswordDto.java b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/UserPasswordDto.java new file mode 100644 index 0000000..7e08dd2 --- /dev/null +++ b/keycloak-user-migration/src/main/java/com/danielfrak/code/keycloak/providers/rest/rest/UserPasswordDto.java @@ -0,0 +1,41 @@ +package com.danielfrak.code.keycloak.providers.rest.rest; + +import java.util.Objects; + +public final class UserPasswordDto { + + private String password; + + public UserPasswordDto() { + } + + public UserPasswordDto(String password) { + this.password = password; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserPasswordDto that = (UserPasswordDto) o; + + return Objects.equals(password, that.password); + } + + @Override + public int hashCode() { + return Objects.hash(password); + } +} diff --git a/keycloak-user-migration/src/main/resources/META-INF/services/org.keycloak.storage.UserStorageProviderFactory b/keycloak-user-migration/src/main/resources/META-INF/services/org.keycloak.storage.UserStorageProviderFactory new file mode 100644 index 0000000..2c9ef7d --- /dev/null +++ b/keycloak-user-migration/src/main/resources/META-INF/services/org.keycloak.storage.UserStorageProviderFactory @@ -0,0 +1 @@ +com.danielfrak.code.keycloak.providers.rest.LegacyProviderFactory \ No newline at end of file diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/ConfigurationPropertiesTest.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/ConfigurationPropertiesTest.java new file mode 100644 index 0000000..6cde365 --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/ConfigurationPropertiesTest.java @@ -0,0 +1,14 @@ +package com.danielfrak.code.keycloak.providers.rest; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ConfigurationPropertiesTest { + + @Test + void shouldGetConfigProperties() { + var result = ConfigurationProperties.getConfigProperties(); + assertNotNull(result); + } +} \ No newline at end of file diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderFactoryTest.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderFactoryTest.java new file mode 100644 index 0000000..c875829 --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderFactoryTest.java @@ -0,0 +1,53 @@ +package com.danielfrak.code.keycloak.providers.rest; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.component.ComponentModel; +import org.keycloak.models.KeycloakSession; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static com.danielfrak.code.keycloak.providers.rest.ConfigurationProperties.PROVIDER_NAME; +import static com.danielfrak.code.keycloak.providers.rest.ConfigurationProperties.URI_PROPERTY; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class LegacyProviderFactoryTest { + + private LegacyProviderFactory legacyProviderFactory; + + @Mock + private KeycloakSession session; + + @Mock + private ComponentModel model; + + @BeforeEach + void setUp() { + legacyProviderFactory = new LegacyProviderFactory(); + } + + @Test + void getConfigProperties() { + assertEquals(ConfigurationProperties.getConfigProperties(), legacyProviderFactory.getConfigProperties()); + } + + @Test + void create() { + final MultivaluedHashMap config = new MultivaluedHashMap<>(); + config.putSingle(URI_PROPERTY, "http://localhost"); + when(model.getConfig()) + .thenReturn(config); + var provider = legacyProviderFactory.create(session, model); + assertNotNull(provider); + } + + @Test + void getId() { + assertEquals(PROVIDER_NAME, legacyProviderFactory.getId()); + } +} \ No newline at end of file diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderTest.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderTest.java new file mode 100644 index 0000000..97db62c --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/LegacyProviderTest.java @@ -0,0 +1,188 @@ +package com.danielfrak.code.keycloak.providers.rest; + +import com.danielfrak.code.keycloak.providers.rest.remote.LegacyUser; +import com.danielfrak.code.keycloak.providers.rest.remote.LegacyUserService; +import com.danielfrak.code.keycloak.providers.rest.remote.UserModelFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.RealmModel; +import org.keycloak.models.UserCredentialManager; +import org.keycloak.models.UserModel; +import org.keycloak.models.credential.PasswordCredentialModel; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class LegacyProviderTest { + + private LegacyProvider legacyProvider; + + @Mock + private KeycloakSession session; + + @Mock + private LegacyUserService legacyUserService; + + @Mock + private UserModelFactory userModelFactory; + + @Mock + private RealmModel realmModel; + + @Mock + private UserModel userModel; + + @BeforeEach + void setUp() { + legacyProvider = new LegacyProvider(session, legacyUserService, userModelFactory); + } + + @Test + void getsUserByUsername() { + final String username = "user"; + final LegacyUser user = new LegacyUser(); + when(legacyUserService.findByUsername(username)) + .thenReturn(Optional.of(user)); + when(userModelFactory.create(user, realmModel)) + .thenReturn(userModel); + + var result = legacyProvider.getUserByUsername(username, realmModel); + + assertEquals(userModel, result); + } + + @Test + void getsUserByEmail() { + final String email = "email"; + final LegacyUser user = new LegacyUser(); + when(legacyUserService.findByEmail(email)) + .thenReturn(Optional.of(user)); + when(userModelFactory.create(user, realmModel)) + .thenReturn(userModel); + + var result = legacyProvider.getUserByEmail(email, realmModel); + + assertEquals(userModel, result); + } + + @Test + void isValidReturnsFalseOnWrongCredentialType() { + var input = mock(CredentialInput.class); + when(input.getType()) + .thenReturn(CredentialModel.KERBEROS); + + var result = legacyProvider.isValid(realmModel, userModel, input); + + assertFalse(result); + } + + @Test + void isValidReturnsFalseWhenInvalidCredentialValue() { + var input = mock(CredentialInput.class); + when(input.getType()) + .thenReturn(PasswordCredentialModel.TYPE); + + final String username = "user"; + final String password = "password"; + + when(userModel.getUsername()) + .thenReturn(username); + when(input.getChallengeResponse()) + .thenReturn(password); + when(legacyUserService.isPasswordValid(username, password)) + .thenReturn(false); + + var result = legacyProvider.isValid(realmModel, userModel, input); + + assertFalse(result); + } + + @Test + void isValidReturnsTrueWhenUserValidated() { + var input = mock(CredentialInput.class); + when(input.getType()) + .thenReturn(PasswordCredentialModel.TYPE); + + final String username = "user"; + final String password = "password"; + + when(userModel.getUsername()) + .thenReturn(username); + when(input.getChallengeResponse()) + .thenReturn(password); + when(legacyUserService.isPasswordValid(username, password)) + .thenReturn(true); + + when(session.userCredentialManager()) + .thenReturn(mock(UserCredentialManager.class)); + + var result = legacyProvider.isValid(realmModel, userModel, input); + + assertTrue(result); + } + + @Test + void supportsPasswordCredentialType() { + assertTrue(legacyProvider.supportsCredentialType(PasswordCredentialModel.TYPE)); + } + + @Test + void isConfiguredForShouldAlwaysReturnFalse() { + assertFalse(legacyProvider.isConfiguredFor(mock(RealmModel.class), mock(UserModel.class), + "someString")); + } + + @Test + void getUserByIdShouldThrowException() { + var realm = mock(RealmModel.class); + assertThrows(UnsupportedOperationException.class, () -> legacyProvider.getUserById("someId", realm)); + } + + @Test + void removeFederationLinkWhenCredentialUpdates() { + var input = mock(CredentialInput.class); + when(userModel.getFederationLink()) + .thenReturn("someId"); + + assertFalse(legacyProvider.updateCredential(realmModel, userModel, input)); + + verify(userModel) + .setFederationLink(null); + } + + @Test + void doNotRemoveFederationLinkWhenBlankAndCredentialUpdates() { + var input = mock(CredentialInput.class); + when(userModel.getFederationLink()) + .thenReturn(" "); + + assertFalse(legacyProvider.updateCredential(realmModel, userModel, input)); + + verify(userModel, never()) + .setFederationLink(null); + } + + @Test + void doNotRemoveFederationLinkWhenNullAndCredentialUpdates() { + var input = mock(CredentialInput.class); + when(userModel.getFederationLink()) + .thenReturn(null); + + assertFalse(legacyProvider.updateCredential(realmModel, userModel, input)); + + verify(userModel, never()) + .setFederationLink(null); + } +} \ No newline at end of file diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUserTest.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUserTest.java new file mode 100644 index 0000000..76e087d --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/LegacyUserTest.java @@ -0,0 +1,89 @@ +package com.danielfrak.code.keycloak.providers.rest.remote; + +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static java.util.Collections.singletonList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LegacyUserTest { + + @Test + void shouldGetAndSetUsername() { + var user = new LegacyUser(); + var expectedValue = "someValue"; + user.setUsername(expectedValue); + assertEquals(expectedValue, user.getUsername()); + } + + @Test + void shouldGetAndSetEmail() { + var user = new LegacyUser(); + var expectedValue = "someValue"; + user.setEmail(expectedValue); + assertEquals(expectedValue, user.getEmail()); + } + + @Test + void shouldGetAndSetFirstName() { + var user = new LegacyUser(); + var expectedValue = "someValue"; + user.setFirstName(expectedValue); + assertEquals(expectedValue, user.getFirstName()); + } + + @Test + void shouldGetAndSetLastName() { + var user = new LegacyUser(); + var expectedValue = "someValue"; + user.setLastName(expectedValue); + assertEquals(expectedValue, user.getLastName()); + } + + @Test + void shouldGetAndSetEnabled() { + var user = new LegacyUser(); + user.setEnabled(true); + assertTrue(user.isEnabled()); + } + + @Test + void shouldGetAndSetEmailVerified() { + var user = new LegacyUser(); + user.setEmailVerified(true); + assertTrue(user.isEmailVerified()); + } + + @Test + void shouldGetAndSetAttributes() { + var user = new LegacyUser(); + var expectedValue = Map.of("attribute1", singletonList("value1")); + user.setAttributes(expectedValue); + assertEquals(expectedValue, user.getAttributes()); + } + + @Test + void shouldGetAndSetRoles() { + var user = new LegacyUser(); + var expectedValue = singletonList("value1"); + user.setRoles(expectedValue); + assertEquals(expectedValue, user.getRoles()); + } + + @Test + void shouldGetAndSetGroups() { + var user = new LegacyUser(); + var expectedValue = singletonList("value1"); + user.setGroups(expectedValue); + assertEquals(expectedValue, user.getGroups()); + } + + @Test + void testEquals() { + EqualsVerifier.simple().forClass(LegacyUser.class) + .verify(); + } +} \ No newline at end of file diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/TestUserModel.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/TestUserModel.java new file mode 100644 index 0000000..1fd7b1e --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/TestUserModel.java @@ -0,0 +1,236 @@ +package com.danielfrak.code.keycloak.providers.rest.remote; + +import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; +import org.keycloak.models.RoleModel; +import org.keycloak.models.UserModel; + +import java.util.*; + +public class TestUserModel implements UserModel { + + private String id; + private String username; + private String email; + private String firstName; + private String lastName; + private boolean isEnabled; + private boolean isEmailVerified; + private Map> attributes = new HashMap<>(); + private Set roles = new HashSet<>(); + private Set groups = new HashSet<>(); + private String federationLink; + + public TestUserModel(String username) { + this.username = username; + } + + public TestUserModel(String username, String id) { + this.username = username; + this.id = id; + } + + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public void setUsername(String username) { + this.username = username; + } + + @Override + public Long getCreatedTimestamp() { + return null; + } + + @Override + public void setCreatedTimestamp(Long timestamp) { + + } + + @Override + public String getEmail() { + return email; + } + + @Override + public void setEmail(String email) { + this.email = email; + } + + @Override + public String getFirstName() { + return firstName; + } + + @Override + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + @Override + public String getLastName() { + return lastName; + } + + @Override + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public boolean isEnabled() { + return isEnabled; + } + + @Override + public void setEnabled(boolean enabled) { + isEnabled = enabled; + } + + @Override + public void setSingleAttribute(String name, String value) { + throw new RuntimeException("Not implemented"); + } + + @Override + public void setAttribute(String name, List values) { + attributes.put(name, values); + } + + @Override + public void removeAttribute(String name) { + throw new RuntimeException("Not implemented"); + } + + @Override + public String getFirstAttribute(String name) { + throw new RuntimeException("Not implemented"); + } + + @Override + public List getAttribute(String name) { + throw new RuntimeException("Not implemented"); + } + + @Override + public boolean isEmailVerified() { + return isEmailVerified; + } + + @Override + public void setEmailVerified(boolean emailVerified) { + isEmailVerified = emailVerified; + } + + @Override + public Set getGroups() { + return groups; + } + + @Override + public void joinGroup(GroupModel group) { + groups.add(group); + } + + @Override + public void leaveGroup(GroupModel group) { + throw new RuntimeException("Not implemented"); + } + + @Override + public boolean isMemberOf(GroupModel group) { + throw new RuntimeException("Not implemented"); + } + + @Override + public String getFederationLink() { + return federationLink; + } + + @Override + public void setFederationLink(String link) { + this.federationLink = link; + } + + @Override + public String getServiceAccountClientLink() { + throw new RuntimeException("Not implemented"); + } + + @Override + public void setServiceAccountClientLink(String clientInternalId) { + throw new RuntimeException("Not implemented"); + } + + @Override + public Map> getAttributes() { + return attributes; + } + + @Override + public Set getRequiredActions() { + throw new RuntimeException("Not implemented"); + } + + @Override + public void addRequiredAction(String action) { + throw new RuntimeException("Not implemented"); + } + + @Override + public void removeRequiredAction(String action) { + throw new RuntimeException("Not implemented"); + } + + @Override + public void addRequiredAction(RequiredAction action) { + throw new RuntimeException("Not implemented"); + } + + @Override + public void removeRequiredAction(RequiredAction action) { + throw new RuntimeException("Not implemented"); + } + + @Override + public Set getRealmRoleMappings() { + return roles; + } + + @Override + public Set getClientRoleMappings(ClientModel app) { + throw new RuntimeException("Not implemented"); + } + + @Override + public boolean hasRole(RoleModel role) { + return roles.contains(role); + } + + @Override + public void grantRole(RoleModel role) { + roles.add(role); + } + + @Override + public Set getRoleMappings() { + return roles; + } + + @Override + public void deleteRoleMapping(RoleModel role) { + throw new RuntimeException("Not implemented"); + } +} diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/UserModelFactoryTest.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/UserModelFactoryTest.java new file mode 100644 index 0000000..92ca8b3 --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/remote/UserModelFactoryTest.java @@ -0,0 +1,298 @@ +package com.danielfrak.code.keycloak.providers.rest.remote; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.component.ComponentModel; +import org.keycloak.models.*; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static com.danielfrak.code.keycloak.providers.rest.ConfigurationProperties.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UserModelFactoryTest { + + private static String MODEL_ID = "modelId"; + + private UserModelFactory userModelFactory; + + private MultivaluedHashMap config; + + @Mock + private KeycloakSession session; + @Mock + private ComponentModel model; + + @BeforeEach + void setUp() { + config = new MultivaluedHashMap<>(); + config.put(ROLE_MAP_PROPERTY, List.of("oldRole:newRole")); + config.put(GROUP_MAP_PROPERTY, List.of("oldGroup:newGroup")); + + when(model.getConfig()) + .thenReturn(config); + userModelFactory = new UserModelFactory(session, model); + + when(model.getId()) + .thenReturn(MODEL_ID); + } + + @Test + void createsUser() { + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, username)) + .thenReturn(new TestUserModel(username)); + + LegacyUser legacyUser = createLegacyUser(username); + var result = userModelFactory.create(legacyUser, realm); + + assertNotNull(result); + } + + @Test + void migratesBasicAttributes() { + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, username)) + .thenReturn(new TestUserModel(username)); + + LegacyUser legacyUser = createLegacyUser(username); + var result = userModelFactory.create(legacyUser, realm); + + assertEquals(legacyUser.getUsername(), result.getUsername()); + assertEquals(legacyUser.getEmail(), result.getEmail()); + assertEquals(legacyUser.isEmailVerified(), result.isEmailVerified()); + assertEquals(legacyUser.isEnabled(), result.isEnabled()); + assertEquals(legacyUser.getFirstName(), result.getFirstName()); + assertEquals(legacyUser.getLastName(), result.getLastName()); + } + + @Test + void migratesLegacyUserId() { + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + final String id = "legacy-user-id"; + final LegacyUser legacyUser = createLegacyUser(username, id); + final TestUserModel testUserModel = new TestUserModel(username, id); + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, legacyUser.getId(), username, true, false)) + .thenReturn(testUserModel); + + var result = userModelFactory.create(legacyUser, realm); + + assertEquals(legacyUser.getId(), result.getId()); + } + + private LegacyUser createLegacyUser(String username) { + return createLegacyUser(username, null); + } + + private LegacyUser createLegacyUser(String username, String id) { + var legacyUser = new LegacyUser(); + legacyUser.setId(id); + legacyUser.setUsername(username); + legacyUser.setEmail("user@email.com"); + legacyUser.setEmailVerified(true); + legacyUser.setEnabled(true); + legacyUser.setFirstName("John"); + legacyUser.setLastName("Smith"); + return legacyUser; + } + + @Test + void migratesRolesWithoutUnmapped() { + config.putSingle(MIGRATE_UNMAPPED_ROLES_PROPERTY, "false"); + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + final RoleModel newRoleModel = mock(RoleModel.class); + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, username)) + .thenReturn(new TestUserModel(username)); + when(realm.getRole("newRole")) + .thenReturn(newRoleModel); + + LegacyUser legacyUser = createLegacyUser(username); + legacyUser.setRoles(List.of("oldRole", "anotherRole")); + + var result = userModelFactory.create(legacyUser, realm); + + assertEquals(Set.of(newRoleModel), result.getRoleMappings()); + } + + @Test + void migratesGroupsWithoutUnmapped() { + config.putSingle(MIGRATE_UNMAPPED_GROUPS_PROPERTY, "false"); + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + final GroupModel newGroupModel = mock(GroupModel.class); + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, username)) + .thenReturn(new TestUserModel(username)); + when(realm.getGroupById("newGroup")) + .thenReturn(newGroupModel); + + LegacyUser legacyUser = createLegacyUser(username); + legacyUser.setGroups(List.of("oldGroup", "anotherGroup")); + + var result = userModelFactory.create(legacyUser, realm); + + assertEquals(Set.of(newGroupModel), result.getGroups()); + } + + @Test + void migratesUnmappedRoles() { + config.putSingle(MIGRATE_UNMAPPED_ROLES_PROPERTY, "true"); + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + final RoleModel newRoleModel = mock(RoleModel.class); + final RoleModel anotherRoleModel = mock(RoleModel.class); + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, username)) + .thenReturn(new TestUserModel(username)); + when(realm.getRole("newRole")) + .thenReturn(newRoleModel); + when(realm.getRole("anotherRole")) + .thenReturn(anotherRoleModel); + + LegacyUser legacyUser = createLegacyUser(username); + legacyUser.setRoles(List.of("oldRole", "anotherRole")); + + var result = userModelFactory.create(legacyUser, realm); + + assertEquals(Set.of(newRoleModel, anotherRoleModel), result.getRoleMappings()); + } + + @Test + void migratesUnmappedGroups() { + config.putSingle(MIGRATE_UNMAPPED_GROUPS_PROPERTY, "true"); + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + final GroupModel newGroupModel = mock(GroupModel.class); + final GroupModel anotherGroupModel = mock(GroupModel.class); + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, username)) + .thenReturn(new TestUserModel(username)); + when(realm.getGroupById(anyString())).thenReturn(null); + when(realm.createGroup("newGroup")).thenReturn(newGroupModel); + when(realm.createGroup("anotherGroup")).thenReturn(anotherGroupModel); + + LegacyUser legacyUser = createLegacyUser(username); + legacyUser.setGroups(List.of("newGroup", "anotherGroup")); + + var result = userModelFactory.create(legacyUser, realm); + + assertEquals(Set.of(newGroupModel, anotherGroupModel), result.getGroups()); + } + + @Test + void migrateUserWithNullGroups() { + config.putSingle(MIGRATE_UNMAPPED_GROUPS_PROPERTY, "true"); + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + + when(session.userLocalStorage()).thenReturn(userProvider); + when(userProvider.addUser(realm, username)).thenReturn(new TestUserModel(username)); + + LegacyUser legacyUser = createLegacyUser(username); + List groups = new ArrayList<>(); + groups.add(null); + groups.add(""); + legacyUser.setGroups(groups); + + var result = userModelFactory.create(legacyUser, realm); + + assertTrue(result.getGroups().isEmpty()); + } + + @Test + void migrateUserWithNullRoles() { + config.putSingle(MIGRATE_UNMAPPED_ROLES_PROPERTY, "true"); + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + + when(session.userLocalStorage()).thenReturn(userProvider); + when(userProvider.addUser(realm, username)).thenReturn(new TestUserModel(username)); + + LegacyUser legacyUser = createLegacyUser(username); + List roles = new ArrayList<>(); + roles.add(null); + roles.add(""); + legacyUser.setRoles(roles); + + var result = userModelFactory.create(legacyUser, realm); + + assertTrue(result.getRoleMappings().isEmpty()); + } + + @Test + void migratesAttribute() { + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, username)) + .thenReturn(new TestUserModel(username)); + + LegacyUser legacyUser = createLegacyUser(username); + legacyUser.setAttributes(Map.of("someAttribute", List.of("someValue"))); + var result = userModelFactory.create(legacyUser, realm); + + assertEquals(legacyUser.getAttributes(), result.getAttributes()); + } + + @Test + void setsFederationLink() { + final UserProvider userProvider = mock(UserProvider.class); + final RealmModel realm = mock(RealmModel.class); + final String username = "user"; + + when(session.userLocalStorage()) + .thenReturn(userProvider); + when(userProvider.addUser(realm, username)) + .thenReturn(new TestUserModel(username)); + + LegacyUser legacyUser = createLegacyUser(username); + var result = userModelFactory.create(legacyUser, realm); + + assertEquals(MODEL_ID, result.getFederationLink()); + } +} \ No newline at end of file diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/BearerTokenRequestFilterTest.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/BearerTokenRequestFilterTest.java new file mode 100644 index 0000000..f15ca65 --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/BearerTokenRequestFilterTest.java @@ -0,0 +1,35 @@ +package com.danielfrak.code.keycloak.providers.rest.rest; + +import org.jboss.resteasy.specimpl.MultivaluedMapImpl; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.core.MultivaluedMap; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class BearerTokenRequestFilterTest { + @Mock + private ClientRequestContext context; + + @Test + void filter() { + String token = "secret-api-token"; + String expectedAuthorizationHeader = "Bearer " + token; + + BearerTokenRequestFilter requestFilter = new BearerTokenRequestFilter(token); + MultivaluedMap headers = new MultivaluedMapImpl<>(); + when(context.getHeaders()).thenReturn(headers); + + requestFilter.filter(context); + + Object result = headers.getFirst("Authorization"); + assertNotNull(result); + assertEquals(expectedAuthorizationHeader, result.toString()); + } +} diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserServiceTest.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserServiceTest.java new file mode 100644 index 0000000..a3508d2 --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/RestUserServiceTest.java @@ -0,0 +1,142 @@ +package com.danielfrak.code.keycloak.providers.rest.rest; + +import com.danielfrak.code.keycloak.providers.rest.remote.LegacyUser; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.component.ComponentModel; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import javax.ws.rs.client.Client; +import javax.ws.rs.core.Response; + +import static com.danielfrak.code.keycloak.providers.rest.ConfigurationProperties.URI_PROPERTY; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RestUserServiceTest { + + private RestUserService restUserService; + + @Mock + private ComponentModel model; + + @Mock + private RestUserClient client; + + @BeforeEach + void setUp() { + var uri = "someUri"; + var config = new MultivaluedHashMap(); + config.putSingle(URI_PROPERTY, uri); + var restEasyClient = mock(Client.class); + var resteasyWebTarget = mock(ResteasyWebTarget.class); + + when(model.getConfig()).thenReturn(config); + when(restEasyClient.target(uri)) + .thenReturn(resteasyWebTarget); + when(resteasyWebTarget.proxy(RestUserClient.class)) + .thenReturn(client); + + restUserService = new RestUserService(model, restEasyClient); + } + + @Test + void shouldFindByEmail() { + var email = "someEmail"; + var expectedResult = new LegacyUser(); + var response = mock(Response.class); + + when(client.findByUsername(email)) + .thenReturn(response); + when(response.getStatus()) + .thenReturn(200); + when(response.readEntity(LegacyUser.class)) + .thenReturn(expectedResult); + + var result = restUserService.findByEmail(email); + assertTrue(result.isPresent()); + assertEquals(expectedResult, result.get()); + } + + @Test + void findByEmailShouldReturnEmptyOptionalIfNotFound() { + var email = "someEmail"; + var response = mock(Response.class); + + when(client.findByUsername(email)) + .thenReturn(response); + when(response.getStatus()) + .thenReturn(404); + + var result = restUserService.findByEmail(email); + assertTrue(result.isEmpty()); + } + + @Test + void shouldFindByUsername() { + var username = "someUsername"; + var expectedResult = new LegacyUser(); + var response = mock(Response.class); + + when(client.findByUsername(username)) + .thenReturn(response); + when(response.getStatus()) + .thenReturn(200); + when(response.readEntity(LegacyUser.class)) + .thenReturn(expectedResult); + + var result = restUserService.findByUsername(username); + assertTrue(result.isPresent()); + assertEquals(expectedResult, result.get()); + } + + @Test + void findByUsernameShouldReturnEmptyOptionalIfNotFound() { + var username = "someUsername"; + var response = mock(Response.class); + + when(client.findByUsername(username)) + .thenReturn(response); + when(response.getStatus()) + .thenReturn(404); + + var result = restUserService.findByUsername(username); + assertTrue(result.isEmpty()); + } + + @Test + void isPasswordValidShouldReturnTrueForValidPassword() { + var username = "someUsername"; + var somePassword = "somePassword"; + var response = mock(Response.class); + + when(client.validatePassword(username, new UserPasswordDto(somePassword))) + .thenReturn(response); + when(response.getStatus()) + .thenReturn(200); + + var result = restUserService.isPasswordValid(username, somePassword); + assertTrue(result); + } + + @Test + void isPasswordValidShouldReturnFalseForInvalidPassword() { + var username = "someUsername"; + var somePassword = "somePassword"; + var response = mock(Response.class); + + when(client.validatePassword(username, new UserPasswordDto(somePassword))) + .thenReturn(response); + when(response.getStatus()) + .thenReturn(403); + + var result = restUserService.isPasswordValid(username, somePassword); + assertFalse(result); + } +} \ No newline at end of file diff --git a/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/UserPasswordDtoTest.java b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/UserPasswordDtoTest.java new file mode 100644 index 0000000..dfb44b0 --- /dev/null +++ b/keycloak-user-migration/src/test/java/com/danielfrak/code/keycloak/providers/rest/rest/UserPasswordDtoTest.java @@ -0,0 +1,30 @@ +package com.danielfrak.code.keycloak.providers.rest.rest; + +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class UserPasswordDtoTest { + + @Test + void shouldConstructWithPassword() { + var password = "somePassword"; + var dto = new UserPasswordDto(password); + assertEquals(password, dto.getPassword()); + } + + @Test + void shouldSetAndGetPassword() { + var password = "somePassword"; + var dto = new UserPasswordDto(); + dto.setPassword(password); + assertEquals(password, dto.getPassword()); + } + + @Test + void equalsContract() { + EqualsVerifier.simple().forClass(UserPasswordDto.class) + .verify(); + } +} \ No newline at end of file