aboutsummaryrefslogtreecommitdiffstats
path: root/server/sonar-db-dao/src
diff options
context:
space:
mode:
authorWojtek Wajerowicz <115081248+wojciech-wajerowicz-sonarsource@users.noreply.github.com>2022-11-24 19:45:16 +0100
committersonartech <sonartech@sonarsource.com>2022-12-08 20:02:58 +0000
commit77e8af2605811bf1d13532585ec18ecb602970a5 (patch)
tree042b538ba97036a4d1603cbbd2026b80a2a9f8dd /server/sonar-db-dao/src
parentbd23178bb85c8eca984ad63fda153567ee8b222e (diff)
downloadsonarqube-77e8af2605811bf1d13532585ec18ecb602970a5.tar.gz
sonarqube-77e8af2605811bf1d13532585ec18ecb602970a5.zip
SONAR-17645 Support user commissioning and decomissioning through SCIM for Okta
Diffstat (limited to 'server/sonar-db-dao/src')
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/DaoModule.java4
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/DbClient.java7
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/MyBatis.java2
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserDao.java69
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserDto.java41
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserMapper.java44
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserQuery.java89
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/scim/package-info.java24
-rw-r--r--server/sonar-db-dao/src/main/resources/org/sonar/db/scim/ScimUserMapper.xml68
-rw-r--r--server/sonar-db-dao/src/schema/schema-sq.ddl7
-rw-r--r--server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserDaoTest.java272
-rw-r--r--server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserQueryTest.java82
12 files changed, 708 insertions, 1 deletions
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/DaoModule.java b/server/sonar-db-dao/src/main/java/org/sonar/db/DaoModule.java
index 186b7ff51b4..9c4e55abcfe 100644
--- a/server/sonar-db-dao/src/main/java/org/sonar/db/DaoModule.java
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/DaoModule.java
@@ -81,6 +81,7 @@ import org.sonar.db.rule.RuleDao;
import org.sonar.db.rule.RuleRepositoryDao;
import org.sonar.db.scannercache.ScannerAnalysisCacheDao;
import org.sonar.db.schemamigration.SchemaMigrationDao;
+import org.sonar.db.scim.ScimUserDao;
import org.sonar.db.source.FileSourceDao;
import org.sonar.db.user.GroupDao;
import org.sonar.db.user.GroupMembershipDao;
@@ -161,8 +162,9 @@ public class DaoModule extends Module {
RuleRepositoryDao.class,
SamlMessageIdDao.class,
ScannerAnalysisCacheDao.class,
- SnapshotDao.class,
SchemaMigrationDao.class,
+ ScimUserDao.class,
+ SnapshotDao.class,
SessionTokensDao.class,
UserDao.class,
UserDismissedMessagesDao.class,
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/DbClient.java b/server/sonar-db-dao/src/main/java/org/sonar/db/DbClient.java
index f4238569bda..3b01f339f24 100644
--- a/server/sonar-db-dao/src/main/java/org/sonar/db/DbClient.java
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/DbClient.java
@@ -81,6 +81,7 @@ import org.sonar.db.rule.RuleDao;
import org.sonar.db.rule.RuleRepositoryDao;
import org.sonar.db.scannercache.ScannerAnalysisCacheDao;
import org.sonar.db.schemamigration.SchemaMigrationDao;
+import org.sonar.db.scim.ScimUserDao;
import org.sonar.db.source.FileSourceDao;
import org.sonar.db.user.GroupDao;
import org.sonar.db.user.GroupMembershipDao;
@@ -172,6 +173,7 @@ public class DbClient {
private final ApplicationProjectsDao applicationProjectsDao;
private final ProjectBadgeTokenDao projectBadgeTokenDao;
private final ScannerAnalysisCacheDao scannerAnalysisCacheDao;
+ private final ScimUserDao scimUserDao;
public DbClient(Database database, MyBatis myBatis, DBSessions dbSessions, Dao... daos) {
this.database = database;
@@ -254,6 +256,7 @@ public class DbClient {
userDismissedMessagesDao = getDao(map, UserDismissedMessagesDao.class);
applicationProjectsDao = getDao(map, ApplicationProjectsDao.class);
scannerAnalysisCacheDao = getDao(map, ScannerAnalysisCacheDao.class);
+ scimUserDao = getDao(map, ScimUserDao.class);
}
public DbSession openSession(boolean batch) {
@@ -561,4 +564,8 @@ public class DbClient {
public ScannerAnalysisCacheDao scannerAnalysisCacheDao() {
return scannerAnalysisCacheDao;
}
+
+ public ScimUserDao scimUserDao() {
+ return scimUserDao;
+ }
}
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/MyBatis.java b/server/sonar-db-dao/src/main/java/org/sonar/db/MyBatis.java
index 515fd70c61a..72f8c31e770 100644
--- a/server/sonar-db-dao/src/main/java/org/sonar/db/MyBatis.java
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/MyBatis.java
@@ -144,6 +144,7 @@ import org.sonar.db.rule.RuleRepositoryMapper;
import org.sonar.db.scannercache.ScannerAnalysisCacheMapper;
import org.sonar.db.schemamigration.SchemaMigrationDto;
import org.sonar.db.schemamigration.SchemaMigrationMapper;
+import org.sonar.db.scim.ScimUserMapper;
import org.sonar.db.source.FileSourceMapper;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.GroupMapper;
@@ -314,6 +315,7 @@ public class MyBatis {
SamlMessageIdMapper.class,
ScannerAnalysisCacheMapper.class,
SchemaMigrationMapper.class,
+ ScimUserMapper.class,
SessionTokenMapper.class,
SnapshotMapper.class,
UserDismissedMessagesMapper.class,
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserDao.java b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserDao.java
new file mode 100644
index 00000000000..7b270d79cd8
--- /dev/null
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserDao.java
@@ -0,0 +1,69 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.db.scim;
+
+import java.util.List;
+import java.util.Optional;
+import org.sonar.core.util.UuidFactory;
+import org.apache.ibatis.session.RowBounds;
+import org.sonar.db.Dao;
+import org.sonar.db.DbSession;
+
+public class ScimUserDao implements Dao {
+ private final UuidFactory uuidFactory;
+
+ public ScimUserDao(UuidFactory uuidFactory) {
+ this.uuidFactory = uuidFactory;
+ }
+
+ public List<ScimUserDto> findAll(DbSession dbSession) {
+ return mapper(dbSession).findAll();
+ }
+
+ public Optional<ScimUserDto> findByScimUuid(DbSession dbSession, String scimUserUuid) {
+ return Optional.ofNullable(mapper(dbSession).findByScimUuid(scimUserUuid));
+ }
+
+ public Optional<ScimUserDto> findByUserUuid(DbSession dbSession, String userUuid) {
+ return Optional.ofNullable(mapper(dbSession).findByUserUuid(userUuid));
+ }
+
+ public ScimUserDto enableScimForUser(DbSession dbSession, String userUuid) {
+ ScimUserDto scimUserDto = new ScimUserDto(uuidFactory.create(), userUuid);
+ mapper(dbSession).insert(scimUserDto);
+ return scimUserDto;
+ }
+
+ public List<ScimUserDto> findScimUsers(DbSession dbSession, ScimUserQuery scimUserQuery, int offset, int limit) {
+ return mapper(dbSession).findScimUsers(scimUserQuery, new RowBounds(offset, limit));
+ }
+
+ public int countScimUsers(DbSession dbSession, ScimUserQuery scimUserQuery) {
+ return mapper(dbSession).countScimUsers(scimUserQuery);
+ }
+
+ private static ScimUserMapper mapper(DbSession session) {
+ return session.getMapper(ScimUserMapper.class);
+ }
+
+ public void deleteByUserUuid(DbSession dbSession, String userUuid) {
+ mapper(dbSession).deleteByUserUuid(userUuid);
+ }
+}
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserDto.java b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserDto.java
new file mode 100644
index 00000000000..c92e4e5abe1
--- /dev/null
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserDto.java
@@ -0,0 +1,41 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.db.scim;
+
+public class ScimUserDto {
+
+ private final String scimUserUuid;
+ private final String userUuid;
+
+ public ScimUserDto(String scimUserUuid, String userUuid) {
+ this.scimUserUuid = scimUserUuid;
+ this.userUuid = userUuid;
+ }
+
+ public String getScimUserUuid() {
+ return scimUserUuid;
+ }
+
+
+ public String getUserUuid() {
+ return userUuid;
+ }
+
+}
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserMapper.java b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserMapper.java
new file mode 100644
index 00000000000..75e1c0f96bf
--- /dev/null
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserMapper.java
@@ -0,0 +1,44 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.db.scim;
+
+import java.util.List;
+import javax.annotation.CheckForNull;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.session.RowBounds;
+
+public interface ScimUserMapper {
+
+ List<ScimUserDto> findAll();
+
+ @CheckForNull
+ ScimUserDto findByScimUuid(@Param("scimUserUuid") String scimUserUuid);
+
+ @CheckForNull
+ ScimUserDto findByUserUuid(@Param("userUuid") String userUuid);
+
+ void insert(@Param("scimUserDto") ScimUserDto scimUserDto);
+
+ List<ScimUserDto> findScimUsers(@Param("query") ScimUserQuery scimUserQuery, RowBounds rowBounds);
+
+ int countScimUsers(@Param("query") ScimUserQuery scimUserQuery);
+
+ void deleteByUserUuid(@Param("userUuid") String userUuid);
+}
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserQuery.java b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserQuery.java
new file mode 100644
index 00000000000..34f4fcbd3d9
--- /dev/null
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/ScimUserQuery.java
@@ -0,0 +1,89 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.db.scim;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.annotation.CheckForNull;
+import javax.annotation.Nullable;
+
+import static java.util.regex.Pattern.CASE_INSENSITIVE;
+import static org.apache.commons.lang.StringUtils.isBlank;
+
+public class ScimUserQuery {
+ private static final Pattern USERNAME_FILTER_PATTERN = Pattern.compile("^userName\\s+eq\\s+\"([^\"]*?)\"$", CASE_INSENSITIVE);
+ private static final String UNSUPPORTED_FILTER = "Unsupported filter value: %s. Format should be 'userName eq \"username\"'";
+
+ private final String userName;
+
+ private ScimUserQuery(String userName) {
+ this.userName = userName;
+ }
+
+ @CheckForNull
+ public String getUserName() {
+ return userName;
+ }
+
+ public static ScimUserQuery empty() {
+ return builder().build();
+ }
+
+ public static ScimUserQuery fromScimFilter(@Nullable String filter) {
+ if (isBlank(filter)) {
+ return empty();
+ }
+
+ String userName = getUserNameFromFilter(filter)
+ .orElseThrow(() -> new IllegalStateException(String.format(UNSUPPORTED_FILTER, filter)));
+
+ return builder().userName(userName).build();
+ }
+
+ private static Optional<String> getUserNameFromFilter(String filter) {
+ Matcher matcher = USERNAME_FILTER_PATTERN.matcher(filter.trim());
+ return matcher.find()
+ ? Optional.of(matcher.group(1))
+ : Optional.empty();
+ }
+
+ public static ScimUserQueryBuilder builder() {
+ return new ScimUserQueryBuilder();
+ }
+
+ public static final class ScimUserQueryBuilder {
+
+ private String userName;
+
+ private ScimUserQueryBuilder() {
+ }
+
+ public ScimUserQueryBuilder userName(String userName) {
+ this.userName = userName;
+ return this;
+ }
+
+ public ScimUserQuery build() {
+ return new ScimUserQuery(userName);
+ }
+
+ }
+}
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/scim/package-info.java b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/package-info.java
new file mode 100644
index 00000000000..db44d63a454
--- /dev/null
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/scim/package-info.java
@@ -0,0 +1,24 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.db.scim;
+
+import javax.annotation.ParametersAreNonnullByDefault;
+
diff --git a/server/sonar-db-dao/src/main/resources/org/sonar/db/scim/ScimUserMapper.xml b/server/sonar-db-dao/src/main/resources/org/sonar/db/scim/ScimUserMapper.xml
new file mode 100644
index 00000000000..2c99a131fc0
--- /dev/null
+++ b/server/sonar-db-dao/src/main/resources/org/sonar/db/scim/ScimUserMapper.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd">
+
+<mapper namespace="org.sonar.db.scim.ScimUserMapper">
+
+ <sql id="scimUsersColumns">
+ scim_uuid as scimUserUuid,
+ user_uuid as userUuid
+ </sql>
+
+ <select id="findAll" resultType="org.sonar.db.scim.ScimUserDto">
+ select
+ <include refid="scimUsersColumns"/>
+ from scim_users
+ </select>
+
+ <select id="findByScimUuid" parameterType="String" resultType="org.sonar.db.scim.ScimUserDto">
+ select
+ <include refid="scimUsersColumns"/>
+ from scim_users
+ where
+ scim_uuid = #{scimUserUuid,jdbcType=VARCHAR}
+ </select>
+
+ <select id="findByUserUuid" parameterType="String" resultType="org.sonar.db.scim.ScimUserDto">
+ select
+ <include refid="scimUsersColumns"/>
+ from scim_users
+ where
+ user_uuid = #{userUuid,jdbcType=VARCHAR}
+ </select>
+
+ <insert id="insert" parameterType="map" useGeneratedKeys="false">
+ insert into scim_users (
+ scim_uuid,
+ user_uuid
+ ) values (
+ #{scimUserDto.scimUserUuid,jdbcType=VARCHAR},
+ #{scimUserDto.userUuid,jdbcType=VARCHAR}
+ )
+ </insert>
+
+ <select id="findScimUsers" resultType="org.sonar.db.scim.ScimUserDto">
+ select
+ <include refid="scimUsersColumns"/>
+ <include refid="sqlSelectByQuery"/>
+ order by s.scim_uuid asc
+ </select>
+
+ <select id="countScimUsers" resultType="int">
+ select count(1)
+ <include refid="sqlSelectByQuery"/>
+ </select>
+
+ <sql id="sqlSelectByQuery">
+ from scim_users s
+ <if test="query.userName != null">
+ inner join users u on u.uuid=s.user_uuid
+ where lower(u.external_id) like lower(#{query.userName,jdbcType=VARCHAR}) escape '/'
+ </if>
+ </sql>
+
+ <delete id="deleteByUserUuid" parameterType="String">
+ delete from scim_users where user_uuid = #{userUuid, jdbcType=VARCHAR}
+ </delete>
+
+</mapper>
+
diff --git a/server/sonar-db-dao/src/schema/schema-sq.ddl b/server/sonar-db-dao/src/schema/schema-sq.ddl
index 023646e06ff..eb1660e6ef6 100644
--- a/server/sonar-db-dao/src/schema/schema-sq.ddl
+++ b/server/sonar-db-dao/src/schema/schema-sq.ddl
@@ -920,6 +920,13 @@ CREATE TABLE "SCANNER_ANALYSIS_CACHE"(
);
ALTER TABLE "SCANNER_ANALYSIS_CACHE" ADD CONSTRAINT "PK_SCANNER_ANALYSIS_CACHE" PRIMARY KEY("BRANCH_UUID");
+CREATE TABLE "SCIM_USERS"(
+ "SCIM_UUID" CHARACTER VARYING(40) NOT NULL,
+ "USER_UUID" CHARACTER VARYING(40) NOT NULL
+);
+ALTER TABLE "SCIM_USERS" ADD CONSTRAINT "PK_SCIM_USERS" PRIMARY KEY("SCIM_UUID");
+CREATE UNIQUE INDEX "UNIQ_SCIM_USERS_USER_UUID" ON "SCIM_USERS"("USER_UUID" NULLS FIRST);
+
CREATE TABLE "SESSION_TOKENS"(
"UUID" CHARACTER VARYING(40) NOT NULL,
"USER_UUID" CHARACTER VARYING(255) NOT NULL,
diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserDaoTest.java
new file mode 100644
index 00000000000..588b9e6fc77
--- /dev/null
+++ b/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserDaoTest.java
@@ -0,0 +1,272 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.db.scim;
+
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+import com.tngtech.java.junit.dataprovider.UseDataProvider;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.sonar.db.DbSession;
+import org.sonar.db.DbTester;
+import org.sonar.db.user.UserDto;
+
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Fail.fail;
+
+@RunWith(DataProviderRunner.class)
+public class ScimUserDaoTest {
+
+ @Rule
+ public DbTester db = DbTester.create();
+ private final DbSession dbSession = db.getSession();
+ private final ScimUserDao scimUserDao = db.getDbClient().scimUserDao();
+
+ @Test
+ public void findAll_ifNoData_returnsEmptyList() {
+ assertThat(scimUserDao.findAll(dbSession)).isEmpty();
+ }
+
+ @Test
+ public void findAll_returnsAllEntries() {
+ ScimUserTestData scimUser1TestData = insertScimUser("scimUser1");
+ ScimUserTestData scimUser2TestData = insertScimUser("scimUser2");
+
+ List<ScimUserDto> scimUserDtos = scimUserDao.findAll(dbSession);
+
+ assertThat(scimUserDtos).hasSize(2)
+ .map(scimUserDto -> new ScimUserTestData(scimUserDto.getScimUserUuid(), scimUserDto.getUserUuid()))
+ .containsExactlyInAnyOrder(scimUser1TestData, scimUser2TestData);
+
+ }
+
+ @Test
+ public void findByScimUuid_whenScimUuidNotFound_shouldReturnEmptyOptional() {
+ assertThat(scimUserDao.findByScimUuid(dbSession, "unknownId")).isEmpty();
+ }
+
+ @Test
+ public void findByScimUuid_whenScimUuidFound_shouldReturnDto() {
+ ScimUserTestData scimUser1TestData = insertScimUser("scimUser1");
+ insertScimUser("scimUser2");
+
+ ScimUserDto scimUserDto = scimUserDao.findByScimUuid(dbSession, scimUser1TestData.getScimUserUuid())
+ .orElseGet(() -> fail("User not found"));
+
+ assertThat(scimUserDto.getScimUserUuid()).isEqualTo(scimUser1TestData.getScimUserUuid());
+ assertThat(scimUserDto.getUserUuid()).isEqualTo(scimUser1TestData.getUserUuid());
+ }
+
+ @Test
+ public void findByUserUuid_whenScimUuidNotFound_shouldReturnEmptyOptional() {
+ assertThat(scimUserDao.findByUserUuid(dbSession, "unknownId")).isEmpty();
+ }
+
+ @Test
+ public void findByUserUuid_whenScimUuidFound_shouldReturnDto() {
+ ScimUserTestData scimUser1TestData = insertScimUser("scimUser1");
+ insertScimUser("scimUser2");
+
+ ScimUserDto scimUserDto = scimUserDao.findByUserUuid(dbSession, scimUser1TestData.getUserUuid())
+ .orElseGet(() -> fail("User not found"));
+
+ assertThat(scimUserDto.getScimUserUuid()).isEqualTo(scimUser1TestData.getScimUserUuid());
+ assertThat(scimUserDto.getUserUuid()).isEqualTo(scimUser1TestData.getUserUuid());
+ }
+
+ @DataProvider
+ public static Object[][] paginationData() {
+ return new Object[][] {
+ {5, 0, 20, List.of("1", "2", "3", "4", "5")},
+ {9, 0, 5, List.of("1", "2", "3", "4", "5")},
+ {9, 3, 3, List.of("4", "5", "6")},
+ {9, 7, 3, List.of("8", "9")},
+ {5, 5, 20, List.of()},
+ {5, 0, 0, List.of()}
+ };
+ }
+
+ @Test
+ @UseDataProvider("paginationData")
+ public void findScimUsers_whenPaginationAndStartIndex_shouldReturnTheCorrectNumberOfScimUsers(int totalScimUsers, int offset, int pageSize, List<String> expectedScimUserUuids) {
+ generateScimUsers(totalScimUsers);
+
+ List<ScimUserDto> scimUserDtos = scimUserDao.findScimUsers(dbSession, ScimUserQuery.empty(), offset, pageSize);
+
+ List<String> scimUsersUuids = toScimUsersUuids(scimUserDtos);
+ assertThat(scimUsersUuids).containsExactlyElementsOf(expectedScimUserUuids);
+ }
+
+ private List<String> toScimUsersUuids(Collection<ScimUserDto> scimUserDtos) {
+ return scimUserDtos.stream()
+ .map(ScimUserDto::getScimUserUuid)
+ .collect(Collectors.toList());
+ }
+
+ @Test
+ public void countScimUsers_shouldReturnTheTotalNumberOfScimUsers() {
+ int totalScimUsers = 15;
+ generateScimUsers(totalScimUsers);
+
+ assertThat(scimUserDao.countScimUsers(dbSession, ScimUserQuery.empty())).isEqualTo(totalScimUsers);
+ }
+
+ @Test
+ public void countScimUsers_shouldReturnZero_whenNoScimUsers() {
+ assertThat(scimUserDao.countScimUsers(dbSession, ScimUserQuery.empty())).isZero();
+ }
+
+ @Test
+ public void countScimUsers_shoudReturnZero_whenNoScimUsersMatchesQuery() {
+ int totalScimUsers = 15;
+ generateScimUsers(totalScimUsers);
+ ScimUserQuery scimUserQuery = ScimUserQuery.builder().userName("jean.okta").build();
+
+ assertThat(scimUserDao.countScimUsers(dbSession, scimUserQuery)).isZero();
+ }
+
+ @Test
+ public void countScimUsers_shoudReturnCorrectNumberOfScimUser_whenFilteredByScimUserName() {
+ inserScimUsersWithUsers(List.of("TEST_A", "TEST_B", "TEST_B_BIS", "TEST_C", "TEST_D"));
+ ScimUserQuery scimUserQuery = ScimUserQuery.builder().userName("test_b").build();
+
+ assertThat(scimUserDao.countScimUsers(dbSession, scimUserQuery)).isEqualTo(1);
+ }
+
+ private void generateScimUsers(int totalScimUsers) {
+ List<ScimUserTestData> allScimUsers = Stream.iterate(1, i -> i + 1)
+ .map(i -> insertScimUser(i.toString()))
+ .limit(totalScimUsers)
+ .collect(Collectors.toList());
+ assertThat(allScimUsers).hasSize(totalScimUsers);
+ }
+
+ @Test
+ public void enableScimForUser_addsUserToScimUsers() {
+ ScimUserDto scimUserDto = scimUserDao.enableScimForUser(dbSession, "sqUser1");
+
+ assertThat(scimUserDto.getScimUserUuid()).isNotBlank();
+ ScimUserDto actualScimUserDto = scimUserDao.findByScimUuid(dbSession, scimUserDto.getScimUserUuid()).orElseThrow();
+ assertThat(scimUserDto.getScimUserUuid()).isEqualTo(actualScimUserDto.getScimUserUuid());
+ assertThat(scimUserDto.getUserUuid()).isEqualTo(actualScimUserDto.getUserUuid());
+ }
+
+ @DataProvider
+ public static Object[][] filterData() {
+ return new Object[][] {
+ {"test_user", List.of("test_user", "Test_USEr", "xxx.test_user.yyy", "test_xxx_user"), List.of("1", "2")},
+ {"TEST_USER", List.of("test_user", "Test_USEr", "xxx.test_user.yyy", "test_xxx_user"), List.of("1", "2")},
+ {"test_user_x", List.of("test_user"), List.of()},
+ {"test_x_user", List.of("test_user"), List.of()},
+ };
+ }
+
+ @Test
+ @UseDataProvider("filterData")
+ public void findScimUsers_whenFilteringByUserName_shouldReturnTheExpectedScimUsers(String search, List<String> userLogins, List<String> expectedScimUserUuids) {
+ inserScimUsersWithUsers(userLogins);
+ ScimUserQuery query = ScimUserQuery.builder().userName(search).build();
+
+ List<ScimUserDto> scimUsersByQuery = scimUserDao.findScimUsers(dbSession, query, 0, 100);
+
+ List<String> scimUsersUuids = toScimUsersUuids(scimUsersByQuery);
+ assertThat(scimUsersUuids).containsExactlyElementsOf(expectedScimUserUuids);
+ }
+
+ @Test
+ public void deleteFromUserUuid_shouldDeleteScimUser() {
+ ScimUserTestData scimUserTestData = insertScimUser("scimUser");
+
+ scimUserDao.deleteByUserUuid(dbSession, scimUserTestData.getUserUuid());
+
+ assertThat(scimUserDao.findAll(dbSession)).isEmpty();
+ }
+
+ @Test
+ public void deleteFromUserUuid_shouldNotFail_whenNoUser() {
+ assertThatCode(() -> scimUserDao.deleteByUserUuid(dbSession, randomAlphanumeric(6))).doesNotThrowAnyException();
+ }
+
+ private void inserScimUsersWithUsers(List<String> userLogins) {
+ IntStream.range(0, userLogins.size())
+ .forEachOrdered(i -> insertScimUserWithUser(userLogins.get(i), String.valueOf(i + 1)));
+ }
+
+ private void insertScimUserWithUser(String userLogin, String scimUuid) {
+ UserDto userDto = db.users().insertUser(u -> u.setExternalId(userLogin));
+ insertScimUser(scimUuid, userDto.getUuid());
+ }
+
+ private ScimUserTestData insertScimUser(String scimUserUuid) {
+ return insertScimUser(scimUserUuid, randomAlphanumeric(40));
+ }
+
+ private ScimUserTestData insertScimUser(String scimUserUuid, String userUuid) {
+ ScimUserTestData scimUserTestData = new ScimUserTestData(scimUserUuid, userUuid);
+ Map<String, Object> data = Map.of("scim_uuid", scimUserTestData.getScimUserUuid(), "user_uuid", scimUserTestData.getUserUuid());
+ db.executeInsert("scim_users", data);
+
+ return scimUserTestData;
+ }
+
+ private static class ScimUserTestData {
+
+ private final String scimUserUuid;
+ private final String userUuid;
+
+ private ScimUserTestData(String scimUserUuid, String userUuid) {
+ this.scimUserUuid = scimUserUuid;
+ this.userUuid = userUuid;
+ }
+
+ private String getScimUserUuid() {
+ return scimUserUuid;
+ }
+
+ private String getUserUuid() {
+ return userUuid;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+ ScimUserTestData that = (ScimUserTestData) o;
+ return getScimUserUuid().equals(that.getScimUserUuid()) && getUserUuid().equals(that.getUserUuid());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getScimUserUuid(), getUserUuid());
+ }
+ }
+}
diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserQueryTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserQueryTest.java
new file mode 100644
index 00000000000..175dd28a79a
--- /dev/null
+++ b/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserQueryTest.java
@@ -0,0 +1,82 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2022 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.db.scim;
+
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+import com.tngtech.java.junit.dataprovider.UseDataProvider;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+@RunWith(DataProviderRunner.class)
+public class ScimUserQueryTest {
+
+ @DataProvider
+ public static Object[][] filterData() {
+ ScimUserQuery queryWithUserName = ScimUserQuery.builder().userName("test.user@okta.local").build();
+ ScimUserQuery emptyQuery = ScimUserQuery.builder().build();
+ return new Object[][]{
+ {"userName eq \"test.user@okta.local\"", queryWithUserName},
+ {" userName eq \"test.user@okta.local\" ", queryWithUserName},
+ {"userName eq \"test.user@okta.local\"", queryWithUserName},
+ {"UsERnaMe eq \"test.user@okta.local\"", queryWithUserName},
+ {"userName EQ \"test.user@okta.local\"", queryWithUserName},
+ {null, emptyQuery},
+ {"", emptyQuery}
+ };
+ }
+
+ @Test
+ @UseDataProvider("filterData")
+ public void fromScimFilter_shouldCorrectlyResolveProperties(String filter, ScimUserQuery expected) {
+ ScimUserQuery scimUserQuery = ScimUserQuery.fromScimFilter(filter);
+
+ assertThat(scimUserQuery).usingRecursiveComparison().isEqualTo(expected);
+ }
+
+ @DataProvider
+ public static Object[][] unsupportedFilterData() {
+ return new Object[][]{
+ {"otherProp eq \"test.user@okta.local\""},
+ {"userName eq \"test.user@okta.local\" or userName eq \"test.user2@okta.local\""},
+ {"userName eq \"test.user@okta.local\" and email eq \"test.user2@okta.local\""},
+ {"userName eq \"test.user@okta.local\"xjdkfgldkjfhg"}
+ };
+ }
+
+ @Test
+ @UseDataProvider("unsupportedFilterData")
+ public void fromScimFilter_shouldThrowAnException(String filter) {
+ assertThatThrownBy(() -> ScimUserQuery.fromScimFilter(filter))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(String.format("Unsupported filter value: %s. Format should be 'userName eq \"username\"'", filter));
+ }
+
+ @Test
+ public void empty_shouldHaveNoProperties() {
+ ScimUserQuery scimUserQuery = ScimUserQuery.empty();
+
+ assertThat(scimUserQuery.getUserName()).isNull();
+ }
+
+}