diff --git a/.github/workflows/release-keycloak-scim.yaml b/.github/workflows/release-keycloak-scim.yaml index 1390d14..c1a0f36 100644 --- a/.github/workflows/release-keycloak-scim.yaml +++ b/.github/workflows/release-keycloak-scim.yaml @@ -3,32 +3,40 @@ name: Build keycloak-scim and release on: push: branches: - - 'main' + - "main" tags: - - 'v*' + - "v*" + workflow_dispatch: jobs: build: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 - - - name: Set up JDK 17 - uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4 - with: - java-version: '17' - distribution: 'temurin' - - - name: Build with Gradle - run: gradle shadowJar - - - name: Create Release with jar file - uses: "marvinpinto/action-automatic-releases@latest" - with: - repo_token: "${{ secrets.GITHUB_TOKEN }}" - automatic_release_tag: "latest" - prerelease: false - title: "keycloak-scim release" - files: | - ./build/libs/*.jar + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + + - name: Set up JDK 17 + uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4 + with: + java-version: "17" + distribution: "temurin" + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v3 + with: + gradle-version: 9.2.1 + cache-disabled: true + + - name: Get version + run: echo "VERSION=$(./gradlew -q properties | grep '^version:' | cut -d' ' -f2)" >> $GITHUB_ENV + + - name: Build with Gradle + run: ./gradlew shadowJar + + - name: Create Release with jar file + uses: softprops/action-gh-release@v1 + with: + tag_name: "v${{ env.VERSION }}" + name: "keycloak-scim ${{ env.VERSION }} release" + files: ./build/libs/*.jar + generate_release_notes: true diff --git a/build.gradle b/build.gradle index 3a17055..c82dac4 100644 --- a/build.gradle +++ b/build.gradle @@ -1,11 +1,11 @@ plugins { id 'java' - id 'com.github.johnrengelman.shadow' version '8.1.1' + id 'com.gradleup.shadow' version '9.2.2' id 'org.openrewrite.rewrite' version '6.24.0' } group = 'sh.libre.scim' -version = '1.0-SNAPSHOT' +version = '1.4' description = 'keycloak-scim' java.sourceCompatibility = JavaVersion.VERSION_17 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..23449a2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e509b2d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/sh/libre/scim/core/Adapter.java b/src/main/java/sh/libre/scim/core/Adapter.java index 638503c..b233820 100644 --- a/src/main/java/sh/libre/scim/core/Adapter.java +++ b/src/main/java/sh/libre/scim/core/Adapter.java @@ -12,10 +12,22 @@ import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleMapperModel; +import org.keycloak.common.util.MultivaluedHashMap; import sh.libre.scim.jpa.ScimResource; +import de.captaingoldfish.scim.sdk.common.resources.ResourceNode; import de.captaingoldfish.scim.sdk.client.ScimRequestBuilder; import de.captaingoldfish.scim.sdk.client.builder.PatchBuilder; -import de.captaingoldfish.scim.sdk.common.resources.ResourceNode; +import java.util.regex.Pattern; +import java.util.List; +import java.util.ArrayList; +import java.util.Set; +import java.util.HashSet; +import java.util.stream.Stream; +import java.util.regex.Pattern; +import java.util.List; +import java.util.ArrayList; +import java.util.Set; +import java.util.HashSet; public abstract class Adapter { @@ -141,5 +153,46 @@ public void apply(ScimResource mapping) { public abstract Stream getResourceStream(); - public abstract Boolean skipRefresh(); + protected Stream getFilteredGroups() { + var model = getModel(); + if (model == null) { + return this.session.groups().getGroupsStream(this.session.getContext().getRealm()); + } + var filterList = model.get("group-filter"); + String filter = filterList != null && !filterList.isEmpty() ? filterList.get(0) : null; + if (filter == null || filter.trim().isEmpty()) { + return this.session.groups().getGroupsStream(this.session.getContext().getRealm()); + } + var patternStrings = filter.split(","); + List patterns = new ArrayList<>(); + for (var p : patternStrings) { + patterns.add(Pattern.compile(p.trim())); + } + Set filteredGroups = new HashSet<>(); + this.session.groups().getGroupsStream(this.session.getContext().getRealm()) + .filter(g -> patterns.stream().anyMatch(p -> p.matcher(g.getName()).matches())) + .forEach(g -> { + addGroupRecursively(filteredGroups, g); + }); + return filteredGroups.stream(); + } + + public Boolean skipRefresh() { + return skip; + } + + private void addGroupRecursively(Set groups, org.keycloak.models.GroupModel group) { + if (groups.add(group)) { + group.getSubGroupsStream().forEach(sub -> addGroupRecursively(groups, sub)); + } + } + + protected MultivaluedHashMap getModel() { + var component = this.session.getContext().getRealm().getComponent(this.componentId); + if (component != null) { + return component.getConfig(); + } + return null; + } + } diff --git a/src/main/java/sh/libre/scim/core/GroupAdapter.java b/src/main/java/sh/libre/scim/core/GroupAdapter.java index ee62f6d..0d00969 100644 --- a/src/main/java/sh/libre/scim/core/GroupAdapter.java +++ b/src/main/java/sh/libre/scim/core/GroupAdapter.java @@ -6,6 +6,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import jakarta.persistence.NoResultException; @@ -20,6 +21,7 @@ import org.jboss.logging.Logger; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; +import org.keycloak.models.UserModel; public class GroupAdapter extends Adapter { @@ -64,9 +66,15 @@ public void apply(Group group) { if (groupMembers != null && groupMembers.size() > 0) { this.members = new HashSet(); for (var groupMember : groupMembers) { - var userMapping = this.query("findByExternalId", groupMember.getValue().get(), "User") - .getSingleResult(); - this.members.add(userMapping.getId()); + var databricksUserId = groupMember.getValue().get(); + try { + // Find the Keycloak user by Databricks user ID (externalId) + var userMapping = query("findByExternalId", databricksUserId, "User"); + var mapping = userMapping.getSingleResult(); + this.members.add(mapping.getId()); + } catch (Exception e) { + LOGGER.warn("Could not find user mapping for Databricks user ID: " + databricksUserId, e); + } } } } @@ -82,11 +90,17 @@ public Group toSCIM(Boolean addMeta) { for (var member : members) { var groupMember = new Member(); try { - var userMapping = this.query("findById", member, "User").getSingleResult(); - groupMember.setValue(userMapping.getExternalId()); - var ref = new URI(String.format("Users/%s", userMapping.getExternalId())); - groupMember.setRef(ref.toString()); - groupMembers.add(groupMember); + var user = session.users().getUserById(realm, member); + if (user != null) { + // Get the Databricks user ID from the mapping + var userMapping = query("findById", user.getId(), "User"); + var mapping = userMapping.getSingleResult(); + String databricksUserId = mapping.getExternalId(); + groupMember.setValue(databricksUserId); + var ref = new URI(String.format("Users/%s", databricksUserId)); + groupMember.setRef(ref.toString()); + groupMembers.add(groupMember); + } } catch (Exception e) { LOGGER.error(e); } @@ -146,7 +160,7 @@ public void createEntity() { @Override public Stream getResourceStream() { - return this.session.groups().getGroupsStream(this.session.getContext().getRealm()); + return getFilteredGroups(); } @Override @@ -161,38 +175,31 @@ public PatchBuilder toPatchBuilder(ScimRequestBuilder scimRequestBuilder, patchBuilder = scimRequestBuilder.patch(url, Group.class); if (members.size() > 0) { for (String member : members) { - var userMapping = this.query("findById", member, "User").getSingleResult(); - groupMembers.add(Member.builder().value(userMapping.getExternalId()).build()); + var user = session.users().getUserById(realm, member); + if (user != null) { + try { + // Get the Databricks user ID from the mapping + var userMapping = query("findById", user.getId(), "User"); + var mapping = userMapping.getSingleResult(); + String databricksUserId = mapping.getExternalId(); + groupMembers.add(Member.builder().value(databricksUserId).build()); + } catch (Exception e) { + LOGGER.error("Failed to get mapping for user " + user.getId(), e); + } + } } patchBuilder.addOperation() .path("members") .op(PatchOp.REPLACE) .valueNodes(groupMembers) - .next() - .op(PatchOp.REPLACE) - .path("displayName") - .value(displayName) - .next() - .op(PatchOp.REPLACE) - .path("externalId") - .value(id) .build(); } else { patchBuilder.addOperation() .path("members") .op(PatchOp.REMOVE) .value(null) - .next() - .op(PatchOp.REPLACE) - .path("displayName") - .value(displayName) - .next() - .op(PatchOp.REPLACE) - .path("externalId") - .value(id) .build(); - - } + } LOGGER.info(patchBuilder.getResource()); return patchBuilder; } diff --git a/src/main/java/sh/libre/scim/core/ScimClient.java b/src/main/java/sh/libre/scim/core/ScimClient.java index d2bfb69..404876f 100644 --- a/src/main/java/sh/libre/scim/core/ScimClient.java +++ b/src/main/java/sh/libre/scim/core/ScimClient.java @@ -1,6 +1,8 @@ package sh.libre.scim.core; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import jakarta.persistence.EntityManager; @@ -21,6 +23,7 @@ import org.keycloak.models.KeycloakSession; import org.keycloak.models.RoleMapperModel; import org.keycloak.storage.user.SynchronizationResult; +import sh.libre.scim.storage.ScimSynchronizationResult; import com.google.common.net.HttpHeaders; @@ -84,9 +87,9 @@ protected String BasicAuthentication(String username, String password) { protected ScimClientConfig genScimClientConfig() { return ScimClientConfig.builder() .httpHeaders(defaultHeaders) - .connectTimeout(5) - .requestTimeout(5) - .socketTimeout(5) + .connectTimeout(30) + .requestTimeout(30) + .socketTimeout(30) .expectedHttpResponseHeaders(expectedResponseHeaders) .hostnameVerifier((s, sslSession) -> true) .build(); @@ -120,18 +123,125 @@ protected List fetchAllResources(String endpoint, Class resourceClass) { + List allResources = new ArrayList<>(); + try { + String listUrl = scimApplicationBaseUrl + "/" + endpoint; + LOGGER.infof("Sending SCIM list request to URL: %s", listUrl); + ServerResponse> pageResponse = scimRequestBuilder + .list(listUrl, resourceClass) + .get() + .sendRequest(); + LOGGER.info("Received response for list request: status=" + pageResponse.getHttpStatus() + ", success=" + pageResponse.isSuccess()); + if (pageResponse.isSuccess()) { + ListResponse page = pageResponse.getResource(); + allResources.addAll(page.getListedResources()); + LOGGER.infof("Fetched %d resources from response", allResources.size()); + // Note: Assuming Databricks returns all resources in one page or we take the first page + } else { + LOGGER.warnf("Failed to fetch resources: HTTP %d - %s", pageResponse.getHttpStatus(), pageResponse.getResponseBody()); + } + } catch (Exception e) { + LOGGER.error("Failed to fetch resources", e); + LOGGER.errorf("Failed to fetch resources: %s", e.getMessage()); + } + return allResources; + } - public > void create(Class aClass, + private > boolean tryMapToExisting(Class aClass, M kcModel) { + var adapter = getAdapter(aClass); + adapter.apply(kcModel); + try { + LOGGER.infof("Fetching all resources for client-side filtering for %s", adapter.getId()); + List allResources = fetchAllResources(adapter.getSCIMEndpoint(), adapter.getResourceClass()); + LOGGER.infof("Fetched %d resources for client-side filtering", allResources.size()); + S existingResource = null; + String targetEmail = ""; + String targetDisplayName = ""; + if (adapter instanceof UserAdapter userAdapter) { + targetEmail = userAdapter.getEmail(); + LOGGER.infof("Target email for mapping: %s", targetEmail); + } else if (adapter instanceof GroupAdapter groupAdapter) { + targetDisplayName = groupAdapter.getDisplayName(); + LOGGER.infof("Target displayName for mapping: %s", targetDisplayName); + } + for (S resource : allResources) { + boolean match = false; + if (adapter instanceof UserAdapter && !targetEmail.isEmpty()) { + if (resource instanceof de.captaingoldfish.scim.sdk.common.resources.User user) { + var emails = user.getEmails(); + if (emails != null) { + for (var email : emails) { + if (email.getValue().isPresent()) { + String resEmail = email.getValue().get(); + LOGGER.debugf("Checking resource email: %s against target: %s", resEmail, targetEmail); + if (targetEmail.equalsIgnoreCase(resEmail)) { + match = true; + break; + } + } + } + } + } + } else if (adapter instanceof GroupAdapter && !targetDisplayName.isEmpty()) { + if (resource instanceof de.captaingoldfish.scim.sdk.common.resources.Group group) { + String resDisplayName = group.getDisplayName().orElse(""); + LOGGER.debugf("Checking resource displayName: %s against target: %s", resDisplayName, targetDisplayName); + if (targetDisplayName.equals(resDisplayName)) { + match = true; + } + } + } + if (match) { + existingResource = resource; + LOGGER.infof("Found existing resource via client filter: %s", existingResource.getId()); + break; + } + } + if (existingResource != null) { + adapter.apply(existingResource); + adapter.saveMapping(); + LOGGER.infof("Mapped to existing resource for %s", adapter.getId()); + this.replace(aClass, kcModel); + return true; + } else { + LOGGER.infof("No existing resources found matching the criteria for %s", adapter.getId()); + } + } catch (Exception e) { + LOGGER.errorf("Failed to check for existing resource for %s: %s", adapter.getId(), e.getMessage(), e); + } + return false; + } + + public > ServerResponse create(Class aClass, M kcModel) { var adapter = getAdapter(aClass); adapter.apply(kcModel); if (adapter.skip) { - return; + return null; } // If mapping exist then it was created by import so skip. if (adapter.query("findById", adapter.getId()).getResultList().size() != 0) { - return; + return null; + } + + // Check if we should map to existing + boolean shouldMap = false; + String mapUsersConfig = this.model.get("map-existing-users"); + LOGGER.infof("map-existing-users config value: '%s'", mapUsersConfig); + if (adapter instanceof UserAdapter && "true".equals(mapUsersConfig)) { + shouldMap = true; + } else if (adapter instanceof GroupAdapter && "true".equals(this.model.get("map-existing-groups"))) { + shouldMap = true; + } + + if (shouldMap) { + if (tryMapToExisting(aClass, kcModel)) { + return null; + } } + + LOGGER.debugf("Creating SCIM resource for %s", adapter.getId()); var retry = registry.retry("create-" + adapter.getId()); ServerResponse response = retry.executeSupplier(() -> { @@ -146,12 +256,20 @@ public = 400) { + LOGGER.infof("Create failed with %d for %s, attempting to map to existing resource", statusCode, adapter.getId()); + tryMapToExisting(aClass, kcModel); + } LOGGER.warn(response.getResponseBody()); - LOGGER.warn(response.getHttpStatus()); + LOGGER.debug(response.getHttpStatus()); } - adapter.apply(response.getResource()); - adapter.saveMapping(); + if (response.isSuccess()) { + adapter.apply(response.getResource()); + adapter.saveMapping(); + } + return response; }; public > void replace(Class aClass, @@ -165,10 +283,11 @@ public response = retry.executeSupplier(() -> { try { - LOGGER.info(adapter.getType()); + LOGGER.debug(adapter.getType()); if ((adapter.getType() == "Group" && this.model.get("group-patchOp", false)) || (adapter.getType() == "User" && this.model.get("user-patchOp", false))) { return adapter.toPatchBuilder(scimRequestBuilder, url) @@ -184,9 +303,71 @@ public createResponse = scimRequestBuilder + .create(adapter.getResourceClass(), ("/" + adapter.getSCIMEndpoint()).formatted()) + .setResource(adapter.toSCIM(false)) + .sendRequest(); + if (createResponse.isSuccess()) { + // Update the existing mapping with the new externalId + adapter.apply(createResponse.getResource()); + var existingMapping = adapter.getMapping(); + if (existingMapping != null) { + existingMapping.setExternalId(adapter.getExternalId()); + getEM().merge(existingMapping); + } else { + adapter.saveMapping(); + } + response = createResponse; // Use the successful create response + } else { + response = createResponse; // Return the failed create response for logging + } + } + } + } else if (statusCode == 404 || statusCode == 400) { + // Resource doesn't exist, create it + LOGGER.infof("Resource %s not found (%d), creating instead", adapter.getId(), statusCode); + ServerResponse createResponse = scimRequestBuilder + .create(adapter.getResourceClass(), ("/" + adapter.getSCIMEndpoint()).formatted()) + .setResource(adapter.toSCIM(false)) + .sendRequest(); + if (createResponse.isSuccess()) { + // Update the existing mapping with the new externalId + adapter.apply(createResponse.getResource()); + var existingMapping = adapter.getMapping(); + if (existingMapping != null) { + existingMapping.setExternalId(adapter.getExternalId()); + getEM().merge(existingMapping); + } else { + adapter.saveMapping(); + } + response = createResponse; // Use the successful create response + } else { + response = createResponse; // Return the failed create response for logging + } + } + } + if (!response.isSuccess()){ LOGGER.warn(response.getResponseBody()); - LOGGER.warn(response.getHttpStatus()); + LOGGER.debug(response.getHttpStatus()); } } catch (NoResultException e) { LOGGER.warnf("failed to replace resource %s, scim mapping not found", adapter.getId()); @@ -199,6 +380,7 @@ public > void refreshResources( Class aClass, SynchronizationResult syncRes) { - LOGGER.info("Refresh resources"); + LOGGER.debugf("Refreshing resources for %s", aClass.getSimpleName()); getAdapter(aClass).getResourceStream().forEach(resource -> { var adapter = getAdapter(aClass); adapter.apply(resource); - LOGGER.infof("Reconciling local resource %s", adapter.getId()); + String resourceInfo = getResourceInfo(adapter); + LOGGER.infof("Reconciling local resource %s: %s", adapter.getId(), resourceInfo); if (!adapter.skipRefresh()) { var mapping = adapter.getMapping(); if (mapping == null) { - LOGGER.info("Creating it"); - this.create(aClass, resource); + LOGGER.infof("Creating remote resource for %s", resourceInfo); + ServerResponse createResponse = this.create(aClass, resource); + if (createResponse != null && createResponse.isSuccess()) { + trackAdded(syncRes, adapter, resourceInfo); + } else if (adapter.getMapping() != null) { + // Mapped to existing + trackMapped(syncRes, adapter, resourceInfo); + } else { + trackFailed(syncRes, adapter, resourceInfo + " (create failed)"); + } } else { - LOGGER.info("Replacing it"); + LOGGER.infof("Updating remote resource for %s", resourceInfo); this.replace(aClass, resource); + trackUpdated(syncRes, adapter, resourceInfo); } - syncRes.increaseUpdated(); + } else { + LOGGER.infof("Skipping refresh for %s", resourceInfo); } }); @@ -254,9 +447,10 @@ public > void importResources( Class aClass, SynchronizationResult syncRes) { LOGGER.info("Import"); + LOGGER.debugf("Importing resources for %s", aClass.getSimpleName()); try { var adapter = getAdapter(aClass); - ServerResponse> response = scimRequestBuilder.list("url", adapter.getResourceClass()).get().sendRequest(); + ServerResponse> response = scimRequestBuilder.list(scimApplicationBaseUrl + "/" + adapter.getSCIMEndpoint(), adapter.getResourceClass()).get().sendRequest(); ListResponse resourceTypeListResponse = response.getResource(); for (var resource : resourceTypeListResponse.getListedResources()) { @@ -265,49 +459,59 @@ public > void sync(Class aClass, SynchronizationResult syncRes) { + LOGGER.debugf("Starting sync for %s", aClass.getSimpleName()); if (this.model.get("sync-import", false)) { this.importResources(aClass, syncRes); } if (this.model.get("sync-refresh", false)) { this.refreshResources(aClass, syncRes); } + LOGGER.debugf("Sync completed for %s", aClass.getSimpleName()); } public void close() { scimRequestBuilder.close(); } + + private > String getResourceInfo(A adapter) { + if (adapter instanceof UserAdapter userAdapter) { + String username = userAdapter.getUsername(); + String email = userAdapter.getEmail(); + return String.format("User(username=%s, email=%s)", username, email); + } else if (adapter instanceof GroupAdapter groupAdapter) { + String displayName = groupAdapter.getDisplayName(); + return String.format("Group(name=%s, id=%s)", displayName, adapter.getId()); + } + return String.format("Resource(id=%s)", adapter.getId()); + } + + private > void trackAdded(SynchronizationResult syncRes, A adapter, String resourceInfo) { + if (syncRes instanceof ScimSynchronizationResult scimResult) { + if (adapter instanceof UserAdapter) { + scimResult.addAddedUser(resourceInfo); + } else if (adapter instanceof GroupAdapter) { + scimResult.addAddedGroup(resourceInfo); + } else { + syncRes.increaseAdded(); + } + } else { + syncRes.increaseAdded(); + } + } + + private > void trackUpdated(SynchronizationResult syncRes, A adapter, String resourceInfo) { + if (syncRes instanceof ScimSynchronizationResult scimResult) { + if (adapter instanceof UserAdapter) { + scimResult.addUpdatedUser(resourceInfo); + } else if (adapter instanceof GroupAdapter) { + scimResult.addUpdatedGroup(resourceInfo); + } else { + syncRes.increaseUpdated(); + } + } else { + syncRes.increaseUpdated(); + } + } + + private > void trackRemoved(SynchronizationResult syncRes, A adapter, String resourceInfo) { + if (syncRes instanceof ScimSynchronizationResult scimResult) { + if (adapter instanceof UserAdapter) { + scimResult.addRemovedUser(resourceInfo); + } else if (adapter instanceof GroupAdapter) { + scimResult.addRemovedGroup(resourceInfo); + } else { + syncRes.increaseRemoved(); + } + } else { + syncRes.increaseRemoved(); + } + } + + private > void trackMapped(SynchronizationResult syncRes, A adapter, String resourceInfo) { + if (syncRes instanceof ScimSynchronizationResult scimResult) { + if (adapter instanceof UserAdapter) { + scimResult.addMappedUser(resourceInfo); + } else if (adapter instanceof GroupAdapter) { + scimResult.addMappedGroup(resourceInfo); + } else { + syncRes.increaseUpdated(); + } + } else { + syncRes.increaseUpdated(); + } + } + + private > void trackFailed(SynchronizationResult syncRes, A adapter, String resourceInfo) { + if (syncRes instanceof ScimSynchronizationResult scimResult) { + if (adapter instanceof UserAdapter) { + scimResult.addFailedUser(resourceInfo); + } else if (adapter instanceof GroupAdapter) { + scimResult.addFailedGroup(resourceInfo); + } else { + syncRes.increaseFailed(); + } + } else { + syncRes.increaseFailed(); + } + } + } diff --git a/src/main/java/sh/libre/scim/core/UserAdapter.java b/src/main/java/sh/libre/scim/core/UserAdapter.java index f13d6ee..4218c97 100644 --- a/src/main/java/sh/libre/scim/core/UserAdapter.java +++ b/src/main/java/sh/libre/scim/core/UserAdapter.java @@ -6,6 +6,8 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import java.util.stream.Stream; import de.captaingoldfish.scim.sdk.client.ScimRequestBuilder; @@ -154,7 +156,10 @@ public void apply(User user) { public User toSCIM(Boolean addMeta) { var user = new User(); user.setExternalId(id); - user.setUserName(username); + var model = getModel(); + String usernameSource = model.getFirst("username-source"); + String scimUsername = "email".equals(usernameSource) && email != null ? email : username; + user.setUserName(scimUsername); user.setId(externalId); user.setDisplayName(displayName); Name name = new Name(); @@ -238,7 +243,15 @@ public Boolean tryToMap() { @Override public Stream getResourceStream() { - return this.session.users().searchForUserStream(this.session.getContext().getRealm(), Map.of(UserModel.ENABLED, "true")); + var filteredGroups = getFilteredGroups().collect(Collectors.toSet()); + if (filteredGroups.isEmpty()) { + return this.session.users().searchForUserStream(this.session.getContext().getRealm(), Map.of(UserModel.ENABLED, "true")); + } + Set users = new HashSet<>(); + for (var group : filteredGroups) { + session.users().getGroupMembersStream(realm, group).forEach(users::add); + } + return users.stream().filter(u -> u.isEnabled()); } @Override diff --git a/src/main/java/sh/libre/scim/storage/ScimStorageProviderFactory.java b/src/main/java/sh/libre/scim/storage/ScimStorageProviderFactory.java index 867e963..01ac491 100644 --- a/src/main/java/sh/libre/scim/storage/ScimStorageProviderFactory.java +++ b/src/main/java/sh/libre/scim/storage/ScimStorageProviderFactory.java @@ -17,6 +17,8 @@ import org.keycloak.storage.UserStorageProviderModel; import org.keycloak.storage.user.ImportSynchronization; import org.keycloak.storage.user.SynchronizationResult; +import java.util.ArrayList; +import java.util.List; import sh.libre.scim.core.GroupAdapter; import sh.libre.scim.core.ScimDispatcher; @@ -72,18 +74,21 @@ public class ScimStorageProviderFactory .name("propagation-user") .type(ProviderConfigProperty.BOOLEAN_TYPE) .label("Enable user propagation") + .helpText("Enable syncing users between Keycloak and the SCIM server during sync operations.") .defaultValue("true") .add() .property() .name("propagation-group") .type(ProviderConfigProperty.BOOLEAN_TYPE) .label("Enable group propagation") + .helpText("Enable syncing groups between Keycloak and the SCIM server during sync operations.") .defaultValue("true") .add() .property() .name("sync-import") .type(ProviderConfigProperty.BOOLEAN_TYPE) .label("Enable import during sync") + .helpText("Enable importing users and groups from the SCIM server during sync operations. Disable this for one-way sync from Keycloak to SCIM.") .add() .property() .name("sync-import-action") @@ -97,19 +102,48 @@ public class ScimStorageProviderFactory .name("sync-refresh") .type(ProviderConfigProperty.BOOLEAN_TYPE) .label("Enable refresh during sync") + .helpText("Enable fetching current data from the SCIM server before performing sync operations to ensure consistency and avoid conflicts.") .add() .property() .name("group-patchOp") .type(ProviderConfigProperty.BOOLEAN_TYPE) - .label("Use patchOp for groups") - .helpText("Only used when endpoint doesn't support putGroup API operation (full replace)") + .label("Use PATCH for groups") + .helpText("When enabled, use PATCH operations for groups. When disabled, use PUT operations.") .defaultValue(false) .add() .property() .name("user-patchOp") .type(ProviderConfigProperty.BOOLEAN_TYPE) - .label("Use patchOp for users") - .helpText("Only used when endpoint doesn't support putUser API operation (full replace)") + .label("Use PATCH for users") + .helpText("When enabled, use PATCH operations for users. When disabled, use PUT operations.") + .defaultValue(false) + .add() + .property() + .name("group-filter") + .type(ProviderConfigProperty.STRING_TYPE) + .label("Group filter patterns") + .helpText("Comma-separated regex patterns for group names to sync (e.g., 'admin.*,.*test'). Leave empty to sync all groups.") + .add() + .property() + .name("username-source") + .type(ProviderConfigProperty.LIST_TYPE) + .label("Username source") + .helpText("The user attribute to use as SCIM userName.") + .options("username", "email") + .defaultValue("username") + .add() + .property() + .name("map-existing-users") + .type(ProviderConfigProperty.BOOLEAN_TYPE) + .label("Map to Existing Users on Email Match") + .helpText("If enabled, when creating a user fails due to email conflict, map to the existing remote user instead of failing.") + .defaultValue(false) + .add() + .property() + .name("map-existing-groups") + .type(ProviderConfigProperty.BOOLEAN_TYPE) + .label("Map to Existing Groups on Name Match") + .helpText("If enabled, when creating a group fails due to name conflict, map to the existing remote group instead of failing.") .defaultValue(false) .add() .build(); @@ -135,7 +169,7 @@ public List getConfigProperties() { public SynchronizationResult sync(KeycloakSessionFactory sessionFactory, String realmId, UserStorageProviderModel model) { LOGGER.info("sync"); - var result = new SynchronizationResult(); + var result = new ScimSynchronizationResult(); KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() { @Override diff --git a/src/main/java/sh/libre/scim/storage/ScimSynchronizationResult.java b/src/main/java/sh/libre/scim/storage/ScimSynchronizationResult.java new file mode 100644 index 0000000..a274c1e --- /dev/null +++ b/src/main/java/sh/libre/scim/storage/ScimSynchronizationResult.java @@ -0,0 +1,106 @@ +package sh.libre.scim.storage; + +import java.util.ArrayList; +import java.util.List; + +import org.keycloak.storage.user.SynchronizationResult; + +public class ScimSynchronizationResult extends SynchronizationResult { + private List addedUsers = new ArrayList<>(); + private List updatedUsers = new ArrayList<>(); + private List removedUsers = new ArrayList<>(); + private List failedUsers = new ArrayList<>(); + private List mappedUsers = new ArrayList<>(); + private List addedGroups = new ArrayList<>(); + private List updatedGroups = new ArrayList<>(); + private List removedGroups = new ArrayList<>(); + private List failedGroups = new ArrayList<>(); + private List mappedGroups = new ArrayList<>(); + + public void addAddedUser(String userInfo) { + addedUsers.add(userInfo); + super.increaseAdded(); + } + + public void addUpdatedUser(String userInfo) { + updatedUsers.add(userInfo); + super.increaseUpdated(); + } + + public void addRemovedUser(String userInfo) { + removedUsers.add(userInfo); + super.increaseRemoved(); + } + + public void addFailedUser(String userInfo) { + failedUsers.add(userInfo); + super.increaseFailed(); + } + + public void addAddedGroup(String groupInfo) { + addedGroups.add(groupInfo); + super.increaseAdded(); + } + + public void addUpdatedGroup(String groupInfo) { + updatedGroups.add(groupInfo); + super.increaseUpdated(); + } + + public void addRemovedGroup(String groupInfo) { + removedGroups.add(groupInfo); + super.increaseRemoved(); + } + + public void addFailedGroup(String groupInfo) { + failedGroups.add(groupInfo); + super.increaseFailed(); + } + + public void addMappedUser(String userInfo) { + mappedUsers.add(userInfo); + super.increaseUpdated(); // Treat as updated + } + + public void addMappedGroup(String groupInfo) { + mappedGroups.add(groupInfo); + super.increaseUpdated(); // Treat as updated + } + + // Getters for the lists + public List getAddedUsers() { return addedUsers; } + public List getUpdatedUsers() { return updatedUsers; } + public List getRemovedUsers() { return removedUsers; } + public List getFailedUsers() { return failedUsers; } + public List getMappedUsers() { return mappedUsers; } + public List getAddedGroups() { return addedGroups; } + public List getUpdatedGroups() { return updatedGroups; } + public List getRemovedGroups() { return removedGroups; } + public List getFailedGroups() { return failedGroups; } + public List getMappedGroups() { return mappedGroups; } + + @Override + public String getStatus() { + StringBuilder status = new StringBuilder(); + if (getAdded() > 0) status.append(getAdded()).append(" added"); + if (getUpdated() > 0) { + if (status.length() > 0) status.append(", "); + status.append(getUpdated()).append(" updated"); + } + if (getRemoved() > 0) { + if (status.length() > 0) status.append(", "); + status.append(getRemoved()).append(" removed"); + } + if (getFailed() > 0) { + if (status.length() > 0) status.append(", "); + status.append(getFailed()).append(" failed"); + } + int mapped = mappedUsers.size() + mappedGroups.size(); + if (mapped > 0) { + if (status.length() > 0) status.append(", "); + status.append(mapped).append(" mapped"); + } + if (status.length() == 0) status.append("No changes"); + return status.toString(); + } +} \ No newline at end of file diff --git a/src/main/resources/META-INF/scim-resource-changelog.xml b/src/main/resources/META-INF/scim-resource-changelog.xml index 45be732..680b4d2 100644 --- a/src/main/resources/META-INF/scim-resource-changelog.xml +++ b/src/main/resources/META-INF/scim-resource-changelog.xml @@ -1,6 +1,6 @@ - +