Skip to content

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

Fix SaaS signing participant lookup and remove scope configuration (#8374)

ConnorYoh22cfe42a0ad1
diff --git a/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java b/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java
index 837d6e7714..642932edb3 100644
--- a/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java
+++ b/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java
@@ -82,13 +82,10 @@ public class ConfigInitializer {
migrateProFeaturesKeyCasing(settingsFile, settingsTemplateFile);
boolean ssoAutoLoginMigrated =
migrateSsoAutoLoginToSecurity(settingsFile, settingsTemplateFile);
- boolean signingScopeMigrated =
- migrateSigningUserListScope(settingsFile, settingsTemplateFile);
boolean changesMade =
settingsTemplateFile.updateValuesFromYaml(settingsFile, settingsTemplateFile)
- || ssoAutoLoginMigrated
- || signingScopeMigrated;
+ || ssoAutoLoginMigrated;
if (changesMade) {
settingsTemplateFile.save(destPath);
log.info("Settings file updated based on template changes.");
@@ -157,16 +154,6 @@ public class ConfigInitializer {
}
}
- private boolean migrateSigningUserListScope(YamlHelper yaml, YamlHelper template) {
- if (yaml.getValueByExactKeyPath("storage", "signing", "userListScope") != null) {
- return false;
- }
- Object legacyScope = yaml.getValueByExactKeyPath("storage", "encryption", "userListScope");
- return legacyScope != null
- && template.updateValue(
- List.of("storage", "signing", "userListScope"), legacyScope);
- }
-
boolean migrateSsoAutoLoginToSecurity(YamlHelper yaml, YamlHelper template) {
if (yaml.getValueByExactKeyPath("security", "ssoAutoLogin") != null) {
return false;
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 296ce99b27..f53afbde3a 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
@@ -1498,10 +1498,6 @@ public class ApplicationProperties {
@Data
public static class Signing {
private boolean enabled = true;
-
- // Signing user-picker scope: 'org' (default) = whole instance, anything else =
- // caller's team only (fail-closed). The saas profile pins 'team'.
- private String userListScope = "org";
}
}
diff --git a/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java b/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java
index d596c1b334..3e9eea0dbf 100644
--- a/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java
+++ b/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java
@@ -31,22 +31,6 @@ class ApplicationPropertiesLogicTest {
assertTrue(sys.isAnalyticsEnabled());
}
- @Test
- void storageSigning_userListScope_defaultsToOrg_andIsSettable() {
- // Self-host backward-compat: scope must default to "org" (saas profile pins "team").
- ApplicationProperties.Storage.Signing signing = new ApplicationProperties.Storage.Signing();
-
- assertTrue(signing.isEnabled());
- assertEquals("org", signing.getUserListScope());
-
- signing.setUserListScope("team");
- assertEquals("team", signing.getUserListScope());
-
- // Reachable from the full tree as storage.signing.userListScope.
- assertEquals(
- "org", new ApplicationProperties().getStorage().getSigning().getUserListScope());
- }
-
@Test
void storageDefaultsEnableLocalStorageAndSigningWithoutSharingOrEncryption() {
ApplicationProperties.Storage storage = new ApplicationProperties().getStorage();
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index f8296a767b..6e6c72943e 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -295,7 +295,6 @@ storage:
linkExpirationDays: 3 # Number of days before share links expire
signing:
enabled: true # set to 'false' to disable shared signing (requires storage.enabled and security.enableLogin) [ALPHA]
- userListScope: org # 'org' lists the whole instance; any other value limits the picker to the caller's team.
# Encryption at rest for stored files (AES-256, per-team keys). Requires a Pro or
# Enterprise licence. Key setup, cluster requirements, the encrypt-existing migration,
# the revocation kill switch and master-key rotation are documented in
diff --git a/app/core/src/test/java/stirling/software/common/configuration/SigningScopeMigrationTest.java b/app/core/src/test/java/stirling/software/common/configuration/SigningScopeMigrationTest.java
deleted file mode 100644
index d30eed0b37..0000000000
--- a/app/core/src/test/java/stirling/software/common/configuration/SigningScopeMigrationTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package stirling.software.common.configuration;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.mockito.Mockito.mockStatic;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-
-import org.junit.jupiter.api.io.TempDir;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.CsvSource;
-import org.mockito.MockedStatic;
-
-import stirling.software.common.util.YamlHelper;
-
-class SigningScopeMigrationTest {
- @ParameterizedTest
- @CsvSource(
- value = {
- "team,-,team",
- "org,-,org",
- "team,org,org",
- "org,team,team",
- "-,team,team",
- "-,-,org"
- },
- nullValues = "-")
- void preservesScopeAndExplicitOverridesAcrossRestarts(
- String legacyScope, String signingScope, String expectedScope, @TempDir Path tmp)
- throws Exception {
- Path settings = tmp.resolve("settings.yml");
- Path custom = tmp.resolve("custom_settings.yml");
- String legacy =
- legacyScope == null
- ? ""
- : " encryption:\n userListScope: " + legacyScope + "\n";
- String current =
- signingScope == null ? "" : " signing:\n userListScope: " + signingScope + "\n";
- // Startup replaces files shorter than 31 lines instead of merging their settings.
- Files.writeString(
- settings,
- "# Existing installation\n".repeat(32)
- + "storage:\n enabled: true\n"
- + legacy
- + current);
-
- try (MockedStatic<InstallationPathConfig> paths =
- mockStatic(InstallationPathConfig.class)) {
- paths.when(InstallationPathConfig::getSettingsPath).thenReturn(settings.toString());
- paths.when(InstallationPathConfig::getCustomSettingsPath).thenReturn(custom.toString());
- ConfigInitializer initializer = new ConfigInitializer();
- initializer.ensureConfigExists();
- YamlHelper migrated = new YamlHelper(settings);
- assertEquals(
- expectedScope,
- migrated.getValueByExactKeyPath("storage", "signing", "userListScope"));
- assertNull(migrated.getValueByExactKeyPath("storage", "encryption", "userListScope"));
-
- initializer.ensureConfigExists();
- YamlHelper restarted = new YamlHelper(settings);
- assertEquals(
- expectedScope,
- restarted.getValueByExactKeyPath("storage", "signing", "userListScope"));
- assertEquals(migrated.getAllKeys(), restarted.getAllKeys());
- }
- }
-}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java
index 10dde83245..cf4d3f24f3 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java
@@ -10,6 +10,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.UUID;
+import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -76,6 +77,7 @@ public class UserController {
private final TeamMembershipService teamMembershipService;
private final stirling.software.proprietary.service.OrgOwnerService orgOwnerService;
private final LoginLandingService loginLandingService;
+ private final Environment environment;
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@PostMapping("/register")
@@ -1016,7 +1018,7 @@ public class UserController {
}
}
- // Lists enabled users for the signing picker; 'org' scope = instance-wide, else caller's team.
+ /** Lists enabled signing recipients; SaaS always restricts discovery to the caller's team. */
@PreAuthorize("@principalPolicy.isHumanUser(authentication)")
@GetMapping("/users")
public ResponseEntity<List<UserSummaryDTO>> listUsers(Principal principal) {
@@ -1025,34 +1027,24 @@ public class UserController {
}
Optional<User> callerOpt = userService.findByUsernameIgnoreCase(principal.getName());
+ if (callerOpt.isEmpty() || !callerOpt.get().isEnabled()) {
+ return ResponseEntity.ok(List.of());
+ }
// Anonymous (SaaS) accounts must never enumerate users, in any scope or team.
if (callerOpt.map(UserController::isAnonymousUser).orElse(false)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
- // Fail-closed: only literal "org" opens the whole instance; anything else scopes to team.
- String scope = applicationProperties.getStorage().getSigning().getUserListScope();
- boolean teamScoped = !"org".equalsIgnoreCase(scope == null ? "" : scope.trim());
-
- List<User> source;
- if (teamScoped) {
+ if (environment.matchesProfiles("saas")) {
Team callerTeam = callerOpt.map(User::getTeam).orElse(null);
if (callerTeam == null || isSystemTeam(callerTeam)) {
- // No team or a shared system team: return only the caller, not the team's members.
- source = callerOpt.map(List::of).orElse(List.of());
- } else {
- // Scopes via the single User.team FK; revisit if multi-team membership is added.
- source = userRepository.findAllByTeamId(callerTeam.getId());
+ return ResponseEntity.ok(List.of(toUserSummaryDTO(callerOpt.get())));
}
- } else {
- source = userRepository.findAll();
+ return ResponseEntity.ok(
+ userRepository.findEnabledSigningUsersByTeamId(callerTeam.getId()));
}
-
- List<UserSummaryDTO> users =
- source.stream().filter(User::isEnabled).map(this::toUserSummaryDTO).toList();
-
- return ResponseEntity.ok(users);
+ return ResponseEntity.ok(userRepository.findEnabledSigningUsers());
}
// SaaS anonymous accounts, which must not enumerate users.
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java
index 32d6e9bbdb..b30cd73359 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java
@@ -14,6 +14,7 @@ import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
+import stirling.software.common.model.api.security.UserSummaryDTO;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.model.User;
@@ -61,6 +62,32 @@ public interface UserRepository extends JpaRepository<User, Long> {
"SELECT u FROM User u JOIN FETCH u.authorities JOIN FETCH u.team WHERE u.team.id = :teamId")
List<User> findAllByTeamId(@Param("teamId") Long teamId);
+ /** Picker summaries without loading each user's eager authorities and team entities. */
+ @Query(
+ """
+ SELECT new stirling.software.common.model.api.security.UserSummaryDTO(
+ u.id, u.username, u.username, t.name, true)
+ FROM User u LEFT JOIN u.team t
+ WHERE (u.enabled IS NULL OR u.enabled = true)
+ AND u.username IS NOT NULL
+ AND (u.authenticationType IS NULL OR LOWER(u.authenticationType) <> 'anonymous')
+ ORDER BY u.username, u.id
+ """)
+ List<UserSummaryDTO> findEnabledSigningUsers();
+
+ /** Team-scoped picker summaries; disabled and anonymous accounts cannot be recipients. */
+ @Query(
+ """
+ SELECT new stirling.software.common.model.api.security.UserSummaryDTO(
+ u.id, u.username, u.username, t.name, true)
+ FROM User u JOIN u.team t
+ WHERE t.id = :teamId AND (u.enabled IS NULL OR u.enabled = true)
+ AND u.username IS NOT NULL
+ AND (u.authenticationType IS NULL OR LOWER(u.authenticationType) <> 'anonymous')
+ ORDER BY u.username, u.id
+ """)
+ List<UserSummaryDTO> findEnabledSigningUsersByTeamId(@Param("teamId") Long teamId);
+
/** Usernames alone, ordered and limited by the database, for callers that need no entities. */
@Query(
"SELECT u.username FROM User u WHERE u.team.id IN :teamIds AND u.username IS NOT NULL"
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerMoreTest.java
index 1857e4e865..21916ed3f1 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerMoreTest.java
@@ -18,6 +18,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.mock.env.MockEnvironment;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.test.web.servlet.MockMvc;
@@ -72,7 +73,8 @@ class UserControllerMoreTest {
teamMembershipService,
org.mockito.Mockito.mock(
stirling.software.proprietary.service.OrgOwnerService.class),
- loginLandingService);
+ loginLandingService,
+ new MockEnvironment());
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java
index 476fc9a9eb..b56de2388d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java
@@ -1,6 +1,5 @@
package stirling.software.proprietary.security.controller.api;
-import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -16,15 +15,20 @@ import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
+import org.springframework.mock.env.MockEnvironment;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.api.security.UserSummaryDTO;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.AuthenticationType;
@@ -61,11 +65,13 @@ class UserControllerTest {
@Mock private LoginLandingService loginLandingService;
private ApplicationProperties applicationProperties;
+ private MockEnvironment environment;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
applicationProperties = new ApplicationProperties();
+ environment = new MockEnvironment();
applicationProperties.getPremium().setMaxUsers(10);
applicationProperties.getMail().setEnabled(true);
@@ -82,7 +88,8 @@ class UserControllerTest {
teamMembershipService,
org.mockito.Mockito.mock(
stirling.software.proprietary.service.OrgOwnerService.class),
- loginLandingService);
+ loginLandingService,
+ environment);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@@ -198,10 +205,6 @@ class UserControllerTest {
verify(loginAttemptService).resetAttempts("lockeduser");
}
- // ---------------------------------------------------------------------
- // GET /api/v1/user/users - storage.signing.userListScope scoping
- // ---------------------------------------------------------------------
-
private static User user(long id, String username, boolean enabled, Team team) {
User u = new User();
u.setId(id);
@@ -222,24 +225,32 @@ class UserControllerTest {
return new UsernamePasswordAuthenticationToken(username, "pw");
}
- @Test
- void listUsersDefaultScopeIsOrgWide() throws Exception {
- // Default "org" scope returns every enabled user via findAll(), no team lookup.
+ private static UserSummaryDTO summary(long id, String username, String teamName) {
+ return new UserSummaryDTO(id, username, username, teamName, true);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"org", "team", "invalid"})
+ void listUsersSelfHostedIsInstanceWideRegardlessOfLegacySetting(String legacyScope)
+ throws Exception {
+ environment.setActiveProfiles("security");
+ environment.withProperty("storage.signing.userListScope", legacyScope);
Team alpha = team(1L, "alpha");
- when(userRepository.findAll())
+ when(userService.findByUsernameIgnoreCase("[email protected]"))
+ .thenReturn(Optional.of(user(1L, "[email protected]", true, alpha)));
+ when(userRepository.findEnabledSigningUsers())
.thenReturn(
List.of(
- user(1L, "[email protected]", true, alpha),
- user(2L, "[email protected]", true, alpha)));
+ summary(1L, "[email protected]", "alpha"),
+ summary(2L, "[email protected]", "beta")));
mockMvc.perform(get("/api/v1/user/users").principal(auth("[email protected]")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(2))
.andExpect(jsonPath("$[0].username").value("[email protected]"))
- .andExpect(jsonPath("$[1].username").value("[email protected]"));
+ .andExpect(jsonPath("$[1].username").value("[email protected]"));
- // Caller is resolved (for the anonymous-gate) but org scope still uses findAll, not team.
- verify(userRepository, never()).findAllByTeamId(any());
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
}
@Test
@@ -252,60 +263,93 @@ class UserControllerTest {
mockMvc.perform(get("/api/v1/user/users").principal(auth("anon_abc")))
.andExpect(status().isForbidden());
- verify(userRepository, never()).findAll();
- verify(userRepository, never()).findAllByTeamId(any());
+ verify(userRepository, never()).findEnabledSigningUsers();
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
}
- @Test
- void listUsersOrgScopeFiltersDisabledUsers() throws Exception {
+ @ParameterizedTest
+ @NullAndEmptySource
+ @ValueSource(strings = {"org", "ORG", " org ", "team", "invalid"})
+ void listUsersSaasAlwaysUsesTeamScope(String configuredScope) throws Exception {
+ environment.setActiveProfiles("saas");
+ if (configuredScope != null) {
+ environment.withProperty("storage.signing.userListScope", configuredScope);
+ }
Team alpha = team(1L, "alpha");
- when(userRepository.findAll())
- .thenReturn(
- List.of(
- user(1L, "[email protected]", true, alpha),
- user(2L, "[email protected]", false, alpha)));
+ when(userService.findByUsernameIgnoreCase("[email protected]"))
+ .thenReturn(Optional.of(user(1L, "[email protected]", true, alpha)));
+ when(userRepository.findEnabledSigningUsersByTeamId(1L))
+ .thenReturn(List.of(summary(1L, "[email protected]", "alpha")));
mockMvc.perform(get("/api/v1/user/users").principal(auth("[email protected]")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(1))
.andExpect(jsonPath("$[0].username").value("[email protected]"));
+
+ verify(userRepository, never()).findEnabledSigningUsers();
}
@Test
void listUsersTeamScopeReturnsOnlyCallerTeam() throws Exception {
- applicationProperties.getStorage().getSigning().setUserListScope("team");
+ environment.setActiveProfiles("saas");
Team alpha = team(7L, "alpha");
User caller = user(1L, "[email protected]", true, alpha);
when(userService.findByUsernameIgnoreCase("[email protected]"))
.thenReturn(Optional.of(caller));
- when(userRepository.findAllByTeamId(7L))
- .thenReturn(List.of(caller, user(2L, "[email protected]", true, alpha)));
+ when(userRepository.findEnabledSigningUsersByTeamId(7L))
+ .thenReturn(
+ List.of(
+ summary(1L, "[email protected]", "alpha"),
+ summary(2L, "[email protected]", "alpha")));
mockMvc.perform(get("/api/v1/user/users").principal(auth("[email protected]")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(2))
.andExpect(jsonPath("$[0].teamName").value("alpha"));
- verify(userRepository).findAllByTeamId(7L);
- verify(userRepository, never()).findAll();
+ verify(userRepository).findEnabledSigningUsersByTeamId(7L);
+ verify(userRepository, never()).findEnabledSigningUsers();
}
@Test
void listUsersTeamScopeWithMissingCallerReturnsEmpty() throws Exception {
- applicationProperties.getStorage().getSigning().setUserListScope("team");
+ environment.setActiveProfiles("saas");
when(userService.findByUsernameIgnoreCase("[email protected]")).thenReturn(Optional.empty());
mockMvc.perform(get("/api/v1/user/users").principal(auth("[email protected]")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(0));
- verify(userRepository, never()).findAllByTeamId(any());
- verify(userRepository, never()).findAll();
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
+ verify(userRepository, never()).findEnabledSigningUsers();
+ }
+
+ @Test
+ void listUsersOrgScopeWithMissingCallerReturnsEmpty() throws Exception {
+ mockMvc.perform(get("/api/v1/user/users").principal(auth("missing")))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.length()").value(0));
+
+ verify(userRepository, never()).findEnabledSigningUsers();
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
+ }
+
+ @Test
+ void listUsersDisabledCallerCannotEnumerateUsers() throws Exception {
+ when(userService.findByUsernameIgnoreCase("disabled"))
+ .thenReturn(Optional.of(user(1L, "disabled", false, null)));
+
+ mockMvc.perform(get("/api/v1/user/users").principal(auth("disabled")))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.length()").value(0));
+
+ verify(userRepository, never()).findEnabledSigningUsers();
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
}
@Test
void listUsersTeamScopeWithNullTeamReturnsSelfOnly() throws Exception {
- applicationProperties.getStorage().getSigning().setUserListScope("team");
+ environment.setActiveProfiles("saas");
User caller = user(1L, "[email protected]", true, null);
when(userService.findByUsernameIgnoreCase("[email protected]"))
.thenReturn(Optional.of(caller));
@@ -315,14 +359,14 @@ class UserControllerTest {
.andExpect(jsonPath("$.length()").value(1))
.andExpect(jsonPath("$[0].username").value("[email protected]"));
- verify(userRepository, never()).findAllByTeamId(any());
- verify(userRepository, never()).findAll();
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
+ verify(userRepository, never()).findEnabledSigningUsers();
}
@Test
void listUsersTeamScopeOnDefaultTeamReturnsSelfOnly() throws Exception {
// A caller on a shared system team must not enumerate its members.
- applicationProperties.getStorage().getSigning().setUserListScope("team");
+ environment.setActiveProfiles("saas");
Team defaultTeam = team(1L, TeamService.DEFAULT_TEAM_NAME);
User caller = user(1L, "[email protected]", true, defaultTeam);
when(userService.findByUsernameIgnoreCase("[email protected]")).thenReturn(Optional.of(caller));
@@ -332,13 +376,13 @@ class UserControllerTest {
.andExpect(jsonPath("$.length()").value(1))
.andExpect(jsonPath("$[0].username").value("[email protected]"));
- verify(userRepository, never()).findAllByTeamId(any());
- verify(userRepository, never()).findAll();
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
+ verify(userRepository, never()).findEnabledSigningUsers();
}
@Test
void listUsersTeamScopeOnInternalTeamReturnsSelfOnly() throws Exception {
- applicationProperties.getStorage().getSigning().setUserListScope("team");
+ environment.setActiveProfiles("saas");
Team internalTeam = team(2L, TeamService.INTERNAL_TEAM_NAME);
User caller = user(1L, "[email protected]", true, internalTeam);
when(userService.findByUsernameIgnoreCase("[email protected]")).thenReturn(Optional.of(caller));
@@ -348,82 +392,15 @@ class UserControllerTest {
.andExpect(jsonPath("$.length()").value(1))
.andExpect(jsonPath("$[0].username").value("[email protected]"));
- verify(userRepository, never()).findAllByTeamId(any());
- verify(userRepository, never()).findAll();
- }
-
- @Test
- void listUsersFailsClosedOnUnrecognisedScope() throws Exception {
- // Any non-"org" value must restrict to the caller's team, not leak the instance.
- applicationProperties.getStorage().getSigning().setUserListScope("tewm");
- Team alpha = team(3L, "alpha");
- when(userService.findByUsernameIgnoreCase("[email protected]"))
- .thenReturn(Optional.of(user(1L, "[email protected]", true, alpha)));
- when(userRepository.findAllByTeamId(3L))
- .thenReturn(List.of(user(1L, "[email protected]", true, alpha)));
-
- mockMvc.perform(get("/api/v1/user/users").principal(auth("[email protected]")))
- .andExpect(status().isOk());
-
- verify(userRepository).findAllByTeamId(3L);
- verify(userRepository, never()).findAll();
- }
-
- @Test
- void listUsersFailsClosedOnBlankScope() throws Exception {
- applicationProperties.getStorage().getSigning().setUserListScope(" ");
- Team alpha = team(4L, "alpha");
- when(userService.findByUsernameIgnoreCase("[email protected]"))
- .thenReturn(Optional.of(user(1L, "[email protected]", true, alpha)));
- when(userRepository.findAllByTeamId(4L)).thenReturn(List.of());
-
- mockMvc.perform(get("/api/v1/user/users").principal(auth("[email protected]")))
- .andExpect(status().isOk());
-
- verify(userRepository).findAllByTeamId(4L);
- verify(userRepository, never()).findAll();
- }
-
- @Test
- void listUsersFailsClosedOnNullScope() throws Exception {
- // A null value must also fail closed to the caller's team.
- applicationProperties.getStorage().getSigning().setUserListScope(null);
- Team alpha = team(9L, "alpha");
- when(userService.findByUsernameIgnoreCase("[email protected]"))
- .thenReturn(Optional.of(user(1L, "[email protected]", true, alpha)));
- when(userRepository.findAllByTeamId(9L)).thenReturn(List.of());
-
- mockMvc.perform(get("/api/v1/user/users").principal(auth("[email protected]")))
- .andExpect(status().isOk());
-
- verify(userRepository).findAllByTeamId(9L);
- verify(userRepository, never()).findAll();
- }
-
- @Test
- void listUsersOrgScopeIsCaseInsensitive() throws Exception {
- applicationProperties.getStorage().getSigning().setUserListScope("ORG");
- when(userRepository.findAll()).thenReturn(List.of(user(1L, "[email protected]", true, null)));
-
- mockMvc.perform(get("/api/v1/user/users").principal(auth("[email protected]")))
- .andExpect(status().isOk());
-
- verify(userRepository).findAll();
- verify(userRepository, never()).findAllByTeamId(any());
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
+ verify(userRepository, never()).findEnabledSigningUsers();
}
@Test
void listUsersRequiresAuthentication() throws Exception {
mockMvc.perform(get("/api/v1/user/users")).andExpect(status().isUnauthorized());
- verify(userRepository, never()).findAll();
- verify(userRepository, never()).findAllByTeamId(any());
- }
-
- @Test
- void signingUserListScopeDefaultsToOrg() {
- // Self-host backward-compat: default must stay "org" (saas profile flips it to "team").
- assertEquals(
- "org", new ApplicationProperties().getStorage().getSigning().getUserListScope());
+ verify(userRepository, never()).findEnabledSigningUsers();
+ verify(userRepository, never()).findEnabledSigningUsersByTeamId(any());
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/repository/SigningUserQueryDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/repository/SigningUserQueryDbTest.java
new file mode 100644
index 0000000000..ecf109327b
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/repository/SigningUserQueryDbTest.java
@@ -0,0 +1,133 @@
+package stirling.software.proprietary.security.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.stat.Statistics;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.boot.persistence.autoconfigure.EntityScan;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.PersistenceContext;
+
+import stirling.software.common.model.api.security.UserSummaryDTO;
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.AuthenticationType;
+import stirling.software.proprietary.security.model.Authority;
+import stirling.software.proprietary.security.model.User;
+
+@DataJpaTest(
+ showSql = false,
+ properties = "spring.jpa.properties.hibernate.generate_statistics=true")
+class SigningUserQueryDbTest {
+
+ @Autowired private UserRepository userRepository;
+ @Autowired private EntityManagerFactory entityManagerFactory;
+ @PersistenceContext private EntityManager entityManager;
+
+ @Test
+ void filtersRecipientsInDatabaseAndPreservesSummaryContract() {
+ Team alpha = team("alpha");
+ Team beta = team("beta");
+ User alice = user("alice", true, alpha);
+ user("bob", null, alpha);
+ user("disabled", false, alpha);
+ User anonymous = user("anonymous", true, alpha);
+ anonymous.setAuthenticationType(AuthenticationType.ANONYMOUS);
+ user("other-team", true, beta);
+ user("no-team", true, null);
+ user(null, null, alpha);
+ user(null, true, alpha).setAuthenticationType(AuthenticationType.WEB);
+ user(null, true, null);
+ flushAndClear();
+
+ List<UserSummaryDTO> members =
+ userRepository.findEnabledSigningUsersByTeamId(alpha.getId());
+ assertThat(members).extracting(UserSummaryDTO::getUsername).containsExactly("alice", "bob");
+ assertThat(members.getFirst())
+ .isEqualTo(new UserSummaryDTO(alice.getId(), "alice", "alice", "alpha", true));
+ assertThat(members).allMatch(UserSummaryDTO::isEnabled);
+ assertThat(userRepository.findEnabledSigningUsers())
+ .extracting(UserSummaryDTO::getUsername)
+ .containsExactly("alice", "bob", "no-team", "other-team");
+ assertThat(userRepository.findEnabledSigningUsersByTeamId(-1L)).isEmpty();
+ }
+
+ @Test
+ void pickerUsesOneStatementAndNoEntitiesAsUserCountGrows() {
+ Team alpha = team("alpha");
+ Team beta = team("beta");
+ for (int i = 0; i < 100; i++) {
+ User user = user("member-" + i, true, alpha);
+ entityManager.persist(new Authority("ROLE_USER", user));
+ }
+ user("unrelated", true, beta);
+ flushAndClear();
+
+ assertSingleSummaryQuery(alpha.getId(), 100, 101);
+ for (int i = 100; i < 400; i++) {
+ User user =
+ user(
+ "member-" + i,
+ true,
+ entityManager.getReference(Team.class, alpha.getId()));
+ entityManager.persist(new Authority("ROLE_USER", user));
+ }
+ flushAndClear();
+ assertSingleSummaryQuery(alpha.getId(), 400, 401);
+ }
+
+ private void assertSingleSummaryQuery(Long teamId, int teamCount, int totalCount) {
+ Statistics statistics = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
+ statistics.clear();
+ assertThat(userRepository.findEnabledSigningUsersByTeamId(teamId)).hasSize(teamCount);
+ assertThat(statistics.getPrepareStatementCount()).isEqualTo(1);
+ assertThat(statistics.getEntityLoadCount()).isZero();
+ statistics.clear();
+ assertThat(userRepository.findEnabledSigningUsers()).hasSize(totalCount);
+ assertThat(statistics.getPrepareStatementCount()).isEqualTo(1);
+ assertThat(statistics.getEntityLoadCount()).isZero();
+ }
+
+ private Team team(String name) {
+ Team team = new Team();
+ team.setName(name);
+ entityManager.persist(team);
+ return team;
+ }
+
+ private User user(String username, Boolean enabled, Team team) {
+ User user = new User();
+ user.setUsername(username);
+ user.setEnabled(enabled);
+ user.setTeam(team);
+ entityManager.persist(user);
+ return user;
+ }
+
+ private void flushAndClear() {
+ entityManager.flush();
+ entityManager.clear();
+ }
+
+ @SpringBootConfiguration
+ @EntityScan(
+ basePackages = {
+ "stirling.software.proprietary.security.model",
+ "stirling.software.proprietary.model"
+ })
+ @EnableJpaRepositories(
+ basePackages = {
+ "stirling.software.proprietary.security.database.repository",
+ "stirling.software.proprietary.security.repository"
+ })
+ static class TestApp {}
+}
diff --git a/app/saas/src/main/resources/application-saas.properties b/app/saas/src/main/resources/application-saas.properties
index 85745ff2e3..7234e19d6a 100644
--- a/app/saas/src/main/resources/application-saas.properties
+++ b/app/saas/src/main/resources/application-saas.properties
@@ -85,8 +85,3 @@ supabase.url=https://${app.supabase.project-ref}.supabase.co
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://${app.supabase.project-ref}.supabase.co/auth/v1/.well-known/jwks.json
spring.security.oauth2.resourceserver.jwt.audiences=${app.supabase.expected-aud}
-
-# ---------- Multi-tenant scoping ----------
-# Restrict the signing user picker to the caller's team; SaaS must be 'team'
-# or unrelated tenants leak emails to each other.
-storage.signing.userListScope=team