Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Add SCIM 2.0 user provisioning as an Enterprise feature (#8874)

Anthony Stirlingfbf45559a277
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index 7e3f7bcaba..2be7eeb342 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -23,6 +23,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
+import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
@@ -135,7 +136,12 @@ public class ApplicationProperties {
environment.getPropertySources().addFirst(propertySource);
}
- log.debug("Loaded properties: {}", propertySource.getSource());
+ // Names only: values include secrets such as security.scimToken.
+ log.debug(
+ "Loaded property keys: {}",
+ propertySource instanceof EnumerablePropertySource<?> keys
+ ? Arrays.toString(keys.getPropertyNames())
+ : propertySource.getName());
return propertySource;
}
@@ -975,6 +981,10 @@ public class ApplicationProperties {
private long loginResetTimeMinutes;
private String loginMethod = "all";
private String customGlobalAPIKey;
+ // Bearer token (32+ chars) for SCIM 2.0 provisioning at /api/v1/scim/v2; blank disables it.
+ @ToString.Exclude private String scimToken;
+ // SCIM DELETE erases the user and their files; when false it only deactivates them.
+ private boolean scimDeleteRemovesUser = false;
private Jwt jwt = new Jwt();
private Validation validation = new Validation();
private Timestamp timestamp = new Timestamp();
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index 483876b5cf..4579c464ea 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -16,6 +16,8 @@ security:
ssoAutoLogin: false
loginAttemptCount: 5 # lock user account after 5 tries; when using e.g. Fail2Ban you can deactivate the function with -1
loginResetTimeMinutes: 120 # lock account for 2 hours after x attempts
+ scimToken: "" # Bearer token (at least 32 characters) for SCIM 2.0 user provisioning at /api/v1/scim/v2 (Okta, Entra ID). Leave empty to disable
+ scimDeleteRemovesUser: false # When true, a SCIM DELETE permanently erases the user and their files; when false it only deactivates them
loginMethod: all # Accepts values like 'all' and 'normal'(only Login with Username/Password), 'oauth2'(only Login with OAuth2) or 'saml2'(only Login with SAML2)
initialLogin:
username: "" # initial username for the first login
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java
index 58514de424..2aed27202c 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java
@@ -56,6 +56,7 @@ import stirling.software.proprietary.security.oauth2.TauriAuthorizationRequestRe
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticationFailureHandler;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticationSuccessHandler;
import stirling.software.proprietary.security.saml2.CustomSaml2ResponseAuthenticationConverter;
+import stirling.software.proprietary.security.scim.ScimTokenFilter;
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
import stirling.software.proprietary.security.service.CustomOAuth2UserService;
import stirling.software.proprietary.security.service.CustomUserDetailsService;
@@ -301,6 +302,9 @@ public class SecurityConfiguration {
// OncePerRequestFilter with proper config-driven limits.
// .addFilterBefore(rateLimitingFilter,
// UsernamePasswordAuthenticationFilter.class)
+ // Same order as the JWT filter; registered first so SCIM's bearer token wins.
+ .addFilterBefore(
+ new ScimTokenFilter(securityProperties), UserAuthenticationFilter.class)
.addFilterBefore(jwtAuthenticationFilter, UserAuthenticationFilter.class);
http.sessionManagement(
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/scim/ScimTokenFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/scim/ScimTokenFilter.java
new file mode 100644
index 0000000000..4531bbea22
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/scim/ScimTokenFilter.java
@@ -0,0 +1,85 @@
+package stirling.software.proprietary.security.scim;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.List;
+import java.util.Locale;
+
+import org.springframework.http.HttpHeaders;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+
+/** Authenticates SCIM requests with the configured bearer token and nothing else. */
+@Slf4j
+public class ScimTokenFilter extends OncePerRequestFilter {
+
+ public static final String AUTHORITY = "ROLE_SCIM";
+ static final int MIN_TOKEN_LENGTH = 32;
+
+ // Not a String or UserDetails, so later filters don't look it up as a user account.
+ public enum ScimClient {
+ SCIM;
+
+ @Override
+ public String toString() {
+ return "scim-provisioning";
+ }
+ }
+
+ private final ApplicationProperties.Security security;
+
+ public ScimTokenFilter(ApplicationProperties.Security security) {
+ this.security = security;
+ String token = security.getScimToken();
+ if (token != null && !token.isBlank() && token.length() < MIN_TOKEN_LENGTH) {
+ log.warn("security.scimToken is under {} characters; SCIM stays off", MIN_TOKEN_LENGTH);
+ }
+ }
+
+ @Override
+ protected boolean shouldNotFilter(HttpServletRequest request) {
+ // Servlet path is already decoded and normalised by the container.
+ return !request.getServletPath().toLowerCase(Locale.ROOT).startsWith("/api/v1/scim/");
+ }
+
+ @Override
+ protected void doFilterInternal(
+ HttpServletRequest request, HttpServletResponse response, FilterChain chain)
+ throws ServletException, IOException {
+ String token = security.getScimToken();
+ String header = request.getHeader(HttpHeaders.AUTHORIZATION);
+ if (token == null
+ || token.length() < MIN_TOKEN_LENGTH
+ || header == null
+ || !MessageDigest.isEqual(
+ ("Bearer " + token).getBytes(StandardCharsets.UTF_8),
+ header.getBytes(StandardCharsets.UTF_8))) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ response.setContentType("application/scim+json");
+ response.getWriter()
+ .write(
+ "{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:Error\"],"
+ + "\"status\":\"401\",\"detail\":\"Invalid SCIM token\"}");
+ return;
+ }
+ SecurityContextHolder.getContext()
+ .setAuthentication(
+ new PreAuthenticatedAuthenticationToken(
+ ScimClient.SCIM,
+ null,
+ List.of(new SimpleGrantedAuthority(AUTHORITY))));
+ chain.doFilter(request, response);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/scim/ScimUserController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/scim/ScimUserController.java
new file mode 100644
index 0000000000..7f56d9fd17
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/scim/ScimUserController.java
@@ -0,0 +1,265 @@
+package stirling.software.proprietary.security.scim;
+
+import java.net.URI;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.server.ResponseStatusException;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+
+import io.swagger.v3.oas.annotations.Hidden;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.enumeration.Role;
+import stirling.software.proprietary.security.config.EnterpriseEndpoint;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.AuthenticationType;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.model.exception.UserLimitExceededException;
+import stirling.software.proprietary.security.service.SaveUserRequest;
+import stirling.software.proprietary.security.service.UserService;
+
+/** SCIM 2.0 user provisioning (RFC 7644) for identity providers such as Okta and Entra ID. */
+@Hidden
+@EnterpriseEndpoint
+@Profile("!saas")
+@RestController
+@RequestMapping("/api/v1/scim/v2/Users")
+@PreAuthorize("hasAuthority('" + ScimTokenFilter.AUTHORITY + "')")
+@Slf4j
+@RequiredArgsConstructor
+public class ScimUserController {
+
+ private static final String USER = "urn:ietf:params:scim:schemas:core:2.0:User";
+ private static final String LIST = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
+ private static final String ERROR = "urn:ietf:params:scim:api:messages:2.0:Error";
+ private static final Pattern FILTER =
+ Pattern.compile("userName eq \"([^\"]*)\"", Pattern.CASE_INSENSITIVE);
+
+ private final UserService userService;
+ private final UserRepository userRepository;
+ private final ApplicationProperties.Security security;
+
+ @GetMapping
+ public Map<String, Object> list(
+ @RequestParam(required = false) String filter,
+ @RequestParam(defaultValue = "1") int startIndex,
+ @RequestParam(defaultValue = "100") int count) {
+ List<User> users;
+ if (filter == null) {
+ users = userRepository.findAll();
+ } else {
+ Matcher match = FILTER.matcher(filter.trim());
+ if (!match.matches()) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported filter");
+ }
+ users = userService.findByUsernameIgnoreCase(match.group(1)).stream().toList();
+ }
+ List<User> visible =
+ users.stream().filter(u -> !hasRole(u, Role.INTERNAL_API_USER)).toList();
+ List<Map<String, Object>> page =
+ visible.stream()
+ .skip(Math.max(startIndex, 1) - 1L)
+ .limit(Math.max(count, 0))
+ .map(this::toScim)
+ .toList();
+ return Map.of(
+ "schemas", List.of(LIST),
+ "totalResults", visible.size(),
+ "startIndex", Math.max(startIndex, 1),
+ "itemsPerPage", page.size(),
+ "Resources", page);
+ }
+
+ @GetMapping("/{id}")
+ public Map<String, Object> get(@PathVariable long id) {
+ return toScim(find(id));
+ }
+
+ @PostMapping
+ public ResponseEntity<Map<String, Object>> create(@RequestBody Map<String, Object> body)
+ throws Exception {
+ if (!(attr(body, "userName") instanceof String userName) || userName.isBlank()) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "userName is required");
+ }
+ if (userService.usernameExistsIgnoreCase(userName)) {
+ throw new ResponseStatusException(HttpStatus.CONFLICT, "userName already exists");
+ }
+ if (!userService.isUsernameValid(userName)) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid userName");
+ }
+ User user =
+ userService.saveUserCore(
+ SaveUserRequest.builder()
+ .username(userName)
+ .authenticationType(
+ Boolean.TRUE.equals(security.getSaml2().getEnabled())
+ ? AuthenticationType.SAML2
+ : AuthenticationType.OAUTH2)
+ .enabled(
+ !"false"
+ .equalsIgnoreCase(
+ String.valueOf(attr(body, "active"))))
+ .build());
+ log.info("SCIM created user {}", userName);
+ return ResponseEntity.created(location(user)).body(toScim(user));
+ }
+
+ @PutMapping("/{id}")
+ @Transactional(rollbackFor = Exception.class)
+ public Map<String, Object> replace(@PathVariable long id, @RequestBody Map<String, Object> body)
+ throws Exception {
+ return toScim(apply(findModifiable(id), body));
+ }
+
+ // One transaction so a failing operation rolls back the ones before it.
+ @PatchMapping("/{id}")
+ @Transactional(rollbackFor = Exception.class)
+ public Map<String, Object> patch(@PathVariable long id, @RequestBody Map<String, Object> body)
+ throws Exception {
+ User user = findModifiable(id);
+ if (!(attr(body, "Operations") instanceof List<?> operations) || operations.isEmpty()) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Operations is required");
+ }
+ for (Object item : operations) {
+ Map<?, ?> op = (Map<?, ?>) item;
+ Object path = op.get("path");
+ String kind = String.valueOf(op.get("op")).toLowerCase(Locale.ROOT);
+ if (!Set.of("add", "replace", "remove").contains(kind)) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported op");
+ }
+ if (kind.equals("remove")) {
+ if (path == null || Set.of("username", "active").contains(lower(path))) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "userName and active cannot be removed");
+ }
+ continue;
+ }
+ // Okta omits the path and sends an attribute map; Entra names the attribute in path.
+ user =
+ apply(
+ user,
+ path == null
+ ? (Map<?, ?>) op.get("value")
+ : Collections.singletonMap(path, op.get("value")));
+ }
+ return toScim(user);
+ }
+
+ @DeleteMapping("/{id}")
+ public ResponseEntity<Void> delete(@PathVariable long id) throws Exception {
+ User user = findModifiable(id);
+ if (security.isScimDeleteRemovesUser()) {
+ userService.deleteUser(user.getUsername());
+ log.info("SCIM deleted user {}", user.getUsername());
+ } else {
+ apply(user, Map.of("active", false));
+ }
+ return ResponseEntity.noContent().build();
+ }
+
+ @ExceptionHandler(ResponseStatusException.class)
+ public ResponseEntity<Map<String, Object>> error(ResponseStatusException e) {
+ return ResponseEntity.status(e.getStatusCode())
+ .body(
+ Map.of(
+ "schemas", List.of(ERROR),
+ "status", String.valueOf(e.getStatusCode().value()),
+ "detail", String.valueOf(e.getReason())));
+ }
+
+ @ExceptionHandler({UserLimitExceededException.class, IllegalArgumentException.class})
+ public ResponseEntity<Map<String, Object>> rejected(RuntimeException e) {
+ HttpStatus status =
+ e instanceof UserLimitExceededException
+ ? HttpStatus.FORBIDDEN
+ : HttpStatus.BAD_REQUEST;
+ return error(new ResponseStatusException(status, e.getMessage()));
+ }
+
+ private User apply(User user, Map<?, ?> attrs) throws Exception {
+ if (attrs == null) return user;
+ Object userName = attr(attrs, "userName");
+ if (userName != null && !userName.toString().equals(user.getUsername())) {
+ if (userService.isUsernameTakenByOtherUser(userName.toString(), user.getId())) {
+ throw new ResponseStatusException(HttpStatus.CONFLICT, "userName already exists");
+ }
+ log.info("SCIM renamed user {} to {}", user.getUsername(), userName);
+ userService.changeUsername(user, userName.toString());
+ }
+ Object active = attr(attrs, "active");
+ boolean enable =
+ active == null ? user.isEnabled() : Boolean.parseBoolean(active.toString());
+ if (enable != user.isEnabled()) {
+ userService.changeUserEnabled(user, enable);
+ if (!enable) userService.invalidateUserSessions(user.getUsername());
+ log.info("SCIM set user {} active={}", user.getUsername(), enable);
+ }
+ return user;
+ }
+
+ private User find(long id) {
+ return userRepository
+ .findById(id)
+ .filter(u -> !hasRole(u, Role.INTERNAL_API_USER))
+ .orElseThrow(
+ () -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
+ }
+
+ // A leaked SCIM token must not be able to take over or lock out admin accounts.
+ private User findModifiable(long id) {
+ User user = find(id);
+ if (hasRole(user, Role.ADMIN)) {
+ throw new ResponseStatusException(HttpStatus.FORBIDDEN, "SCIM cannot modify admins");
+ }
+ return user;
+ }
+
+ // SCIM attribute names are case-insensitive (RFC 7643).
+ private static Object attr(Map<?, ?> attrs, String name) {
+ return attrs.entrySet().stream()
+ .filter(e -> name.equalsIgnoreCase(String.valueOf(e.getKey())))
+ .findFirst()
+ .map(Map.Entry::getValue)
+ .orElse(null);
+ }
+
+ private static String lower(Object value) {
+ return String.valueOf(value).toLowerCase(Locale.ROOT);
+ }
+
+ private static URI location(User user) {
+ return ServletUriComponentsBuilder.fromCurrentContextPath()
+ .path("/api/v1/scim/v2/Users/{id}")
+ .buildAndExpand(user.getId())
+ .toUri();
+ }
+
+ private static boolean hasRole(User user, Role role) {
+ return user.getAuthorities().stream()
+ .anyMatch(a -> role.getRoleId().equals(a.getAuthority()));
+ }
+
+ private Map<String, Object> toScim(User user) {
+ return Map.of(
+ "schemas", List.of(USER),
+ "id", String.valueOf(user.getId()),
+ "userName", user.getUsername(),
+ "active", user.isEnabled(),
+ "meta", Map.of("resourceType", "User", "location", location(user).toString()));
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/scim/ScimTokenFilterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/scim/ScimTokenFilterTest.java
new file mode 100644
index 0000000000..ff8fb8bfb2
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/scim/ScimTokenFilterTest.java
@@ -0,0 +1,70 @@
+package stirling.software.proprietary.security.scim;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.mock.web.MockFilterChain;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import stirling.software.common.model.ApplicationProperties;
+
+class ScimTokenFilterTest {
+
+ private static final String TOKEN = "x".repeat(ScimTokenFilter.MIN_TOKEN_LENGTH);
+
+ @AfterEach
+ void clear() {
+ SecurityContextHolder.clearContext();
+ }
+
+ private MockHttpServletResponse run(String token, String header, String path) throws Exception {
+ ApplicationProperties.Security security = new ApplicationProperties.Security();
+ security.setScimToken(token);
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", path);
+ request.setServletPath(path);
+ if (header != null) request.addHeader("Authorization", header);
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ new ScimTokenFilter(security).doFilter(request, response, new MockFilterChain());
+ return response;
+ }
+
+ @Test
+ void validTokenAuthenticatesAsScimClient() throws Exception {
+ assertEquals(200, run(TOKEN, "Bearer " + TOKEN, "/api/v1/scim/v2/Users").getStatus());
+ Authentication auth = SecurityContextHolder.getContext().getAuthentication();
+ assertEquals(ScimTokenFilter.ScimClient.SCIM, auth.getPrincipal());
+ assertTrue(auth.isAuthenticated());
+ }
+
+ @Test
+ void wrongOrMissingTokenIsRejected() throws Exception {
+ assertEquals(401, run(TOKEN, "Bearer wrong", "/api/v1/scim/v2/Users").getStatus());
+ assertEquals(401, run(TOKEN, null, "/api/v1/scim/v2/Users").getStatus());
+ assertNull(SecurityContextHolder.getContext().getAuthentication());
+ }
+
+ @Test
+ void blankConfiguredTokenDisablesScim() throws Exception {
+ MockHttpServletResponse response = run("", "Bearer ", "/api/v1/scim/v2/Users");
+ assertEquals(401, response.getStatus());
+ assertTrue(response.getContentAsString().contains("Invalid SCIM token"));
+ }
+
+ @Test
+ void tokenShorterThan32CharactersIsRefused() throws Exception {
+ assertEquals(
+ 401, run("short-token", "Bearer short-token", "/api/v1/scim/v2/Users").getStatus());
+ }
+
+ @Test
+ void otherPathsAreUntouched() throws Exception {
+ assertEquals(200, run(TOKEN, "Bearer " + TOKEN, "/api/v1/user/me").getStatus());
+ assertNull(SecurityContextHolder.getContext().getAuthentication());
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/scim/ScimUserControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/scim/ScimUserControllerTest.java
new file mode 100644
index 0000000000..16d1a2fb25
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/scim/ScimUserControllerTest.java
@@ -0,0 +1,227 @@
+package stirling.software.proprietary.security.scim;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.enumeration.Role;
+import stirling.software.proprietary.security.config.EnterpriseEndpoint;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.Authority;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.service.SaveUserRequest;
+import stirling.software.proprietary.security.service.UserService;
+
+class ScimUserControllerTest {
+
+ private final UserService userService = mock(UserService.class);
+ private final UserRepository userRepository = mock(UserRepository.class);
+ private final ApplicationProperties.Security security = new ApplicationProperties.Security();
+ private ScimUserController controller;
+ private User alice;
+
+ @BeforeEach
+ void setUp() {
+ controller = new ScimUserController(userService, userRepository, security);
+ alice = user(7L, "[email protected]", Role.USER);
+ when(userRepository.findById(7L)).thenReturn(Optional.of(alice));
+ when(userService.isUsernameValid(any())).thenReturn(true);
+ RequestContextHolder.setRequestAttributes(
+ new ServletRequestAttributes(new MockHttpServletRequest()));
+ }
+
+ @AfterEach
+ void tearDown() {
+ RequestContextHolder.resetRequestAttributes();
+ }
+
+ private static User user(long id, String name, Role role) {
+ User user = new User();
+ user.setId(id);
+ user.setUsername(name);
+ user.setEnabled(true);
+ user.addAuthority(new Authority(role.getRoleId(), user));
+ return user;
+ }
+
+ @Test
+ void requiresEnterpriseLicence() {
+ assertTrue(ScimUserController.class.isAnnotationPresent(EnterpriseEndpoint.class));
+ }
+
+ @Test
+ void createsSsoUser() throws Exception {
+ when(userService.saveUserCore(any())).thenReturn(alice);
+ var response = controller.create(Map.of("userName", "[email protected]", "active", true));
+ assertEquals(201, response.getStatusCode().value());
+ assertEquals(
+ "http://localhost/api/v1/scim/v2/Users/7",
+ response.getHeaders().getLocation().toString());
+ assertEquals("7", response.getBody().get("id"));
+ ArgumentCaptor<SaveUserRequest> request = ArgumentCaptor.forClass(SaveUserRequest.class);
+ verify(userService).saveUserCore(request.capture());
+ assertEquals("[email protected]", request.getValue().getUsername());
+ assertEquals(null, request.getValue().getPassword());
+ }
+
+ @Test
+ void missingUserNameIsRejected() {
+ var e = assertThrows(ResponseStatusException.class, () -> controller.create(Map.of()));
+ assertEquals(400, e.getStatusCode().value());
+ }
+
+ @Test
+ void attributeNamesAreCaseInsensitive() throws Exception {
+ controller.patch(
+ 7L,
+ Map.of(
+ "operations",
+ List.of(Map.of("op", "replace", "path", "Active", "value", false))));
+ verify(userService).changeUserEnabled(alice, false);
+ }
+
+ @Test
+ void unsupportedOrRequiredAttributeRemovalIsRejected() {
+ assertThrows(ResponseStatusException.class, () -> controller.patch(7L, Map.of()));
+ for (Map<String, Object> op :
+ List.<Map<String, Object>>of(
+ Map.of("op", "remove", "path", "userName"),
+ Map.of("op", "move", "path", "active"))) {
+ var e =
+ assertThrows(
+ ResponseStatusException.class,
+ () -> controller.patch(7L, Map.of("Operations", List.of(op))));
+ assertEquals(400, e.getStatusCode().value());
+ }
+ }
+
+ @Test
+ void duplicateUserNameIsConflict() {
+ when(userService.usernameExistsIgnoreCase("[email protected]")).thenReturn(true);
+ var e =
+ assertThrows(
+ ResponseStatusException.class,
+ () -> controller.create(Map.of("userName", "[email protected]")));
+ assertEquals(409, e.getStatusCode().value());
+ }
+
+ @Test
+ void filterByUserNameReturnsMatchOrEmptyList() {
+ when(userService.findByUsernameIgnoreCase("[email protected]"))
+ .thenReturn(Optional.of(alice));
+ Map<String, Object> hit = controller.list("userName eq \"[email protected]\"", 1, 100);
+ assertEquals(1, hit.get("totalResults"));
+ Map<String, Object> miss = controller.list("userName eq \"[email protected]\"", 1, 100);
+ assertEquals(0, miss.get("totalResults"));
+ assertThrows(ResponseStatusException.class, () -> controller.list("title pr", 1, 100));
+ }
+
+ @Test
+ void listHidesInternalApiUser() {
+ when(userRepository.findAll())
+ .thenReturn(
+ List.of(
+ alice,
+ user(1L, "STIRLING-PDF-BACKEND-API-USER", Role.INTERNAL_API_USER)));
+ assertEquals(1, controller.list(null, 1, 100).get("totalResults"));
+ }
+
+ @Test
+ void oktaStylePatchDeactivates() throws Exception {
+ controller.patch(
+ 7L,
+ Map.of(
+ "Operations",
+ List.of(Map.of("op", "replace", "value", Map.of("active", false)))));
+ verify(userService).changeUserEnabled(alice, false);
+ verify(userService).invalidateUserSessions("[email protected]");
+ }
+
+ @Test
+ void entraStylePatchDeactivates() throws Exception {
+ controller.patch(
+ 7L,
+ Map.of(
+ "Operations",
+ List.of(Map.of("op", "Replace", "path", "active", "value", "False"))));
+ verify(userService).changeUserEnabled(alice, false);
+ }
+
+ @Test
+ void renameLeavesActiveAlone() throws Exception {
+ alice.setEnabled(false);
+ controller.patch(
+ 7L,
+ Map.of(
+ "Operations",
+ List.of(
+ Map.of(
+ "op",
+ "replace",
+ "path",
+ "userName",
+ "value",
+ verify(userService).changeUsername(alice, "[email protected]");
+ verify(userService, never()).changeUserEnabled(any(), any());
+ }
+
+ @Test
+ void deleteDeactivatesByDefault() throws Exception {
+ assertEquals(204, controller.delete(7L).getStatusCode().value());
+ verify(userService).changeUserEnabled(alice, false);
+ verify(userService, never()).deleteUser(any());
+ }
+
+ @Test
+ void deleteErasesWhenToggledOn() throws Exception {
+ security.setScimDeleteRemovesUser(true);
+ assertEquals(204, controller.delete(7L).getStatusCode().value());
+ verify(userService).deleteUser("[email protected]");
+ }
+
+ @Test
+ void adminsCannotBeModified() throws Exception {
+ when(userRepository.findById(2L)).thenReturn(Optional.of(user(2L, "admin", Role.ADMIN)));
+ Map<String, Object> rename = Map.of("userName", "[email protected]");
+ for (var call :
+ List.<org.junit.jupiter.api.function.Executable>of(
+ () -> controller.delete(2L),
+ () -> controller.replace(2L, rename),
+ () ->
+ controller.patch(
+ 2L,
+ Map.of("Operations", List.of(Map.of("value", rename)))))) {
+ var e = assertThrows(ResponseStatusException.class, call);
+ assertEquals(403, e.getStatusCode().value());
+ }
+ verify(userService, never()).changeUsername(any(), any());
+ }
+
+ @Test
+ void internalUserIsNotFound() {
+ when(userRepository.findById(1L))
+ .thenReturn(Optional.of(user(1L, "internal", Role.INTERNAL_API_USER)));
+ var e = assertThrows(ResponseStatusException.class, () -> controller.delete(1L));
+ assertEquals(404, e.getStatusCode().value());
+ }
+}