Skip to content

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

fix(invites): reject malformed emails and unknown teams when an invite is created (#7864)

Anthony Stirling7825214811d9
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/InviteLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/InviteLinkController.java
index 6f745b5550..d971c8fa30 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/InviteLinkController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/InviteLinkController.java
@@ -25,6 +25,7 @@ import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.InviteRedemptionService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
+import stirling.software.proprietary.security.util.EmailAddresses;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@InviteApi
@@ -73,8 +74,9 @@ public class InviteLinkController {
// If email is provided, validate and check for conflicts
if (email != null && !email.trim().isEmpty()) {
- // Validate email format
- if (!email.contains("@")) {
+ // The address becomes the account's username at redemption, so it has to be
+ // usable now: a link minted for "a@" only fails when someone tries to redeem it.
+ if (!EmailAddresses.isValidAccountAddress(email)) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Invalid email address"));
}
@@ -150,8 +152,11 @@ public class InviteLinkController {
}
} else {
Team selectedTeam = teamRepository.findById(effectiveTeamId).orElse(null);
- if (selectedTeam != null
- && TeamService.INTERNAL_TEAM_NAME.equals(selectedTeam.getName())) {
+ if (selectedTeam == null) {
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .body(Map.of("error", "Team not found"));
+ }
+ if (TeamService.INTERNAL_TEAM_NAME.equals(selectedTeam.getName())) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Cannot assign users to Internal team"));
}
@@ -435,21 +440,27 @@ public class InviteLinkController {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Email address is required"));
}
+ effectiveEmail = email;
+ }
- // Validate email format
- if (!email.contains("@")) {
- return ResponseEntity.status(HttpStatus.BAD_REQUEST)
- .body(Map.of("error", "Invalid email address"));
- }
-
- effectiveEmail = email.trim().toLowerCase();
+ // Preset addresses on older invites were never validated, so check both sources
+ if (!EmailAddresses.isValidAccountAddress(effectiveEmail)) {
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .body(Map.of("error", "Invalid email address"));
}
+ effectiveEmail = effectiveEmail.trim().toLowerCase(Locale.ROOT);
// Check if user already exists
if (userService.usernameExistsIgnoreCase(effectiveEmail)) {
return invalidInviteResponse();
}
+ // The team may have been deleted since the invite was issued
+ if (invite.getTeamId() != null && !teamRepository.existsById(invite.getTeamId())) {
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .body(Map.of("error", "Team not found"));
+ }
+
// Re-check the licence limit at redemption. The check when the link was generated
// counted the invites outstanding at that moment; users can have been added since, and
// a link issued while slots were free must not be able to create the user over the cap.
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/TeamController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/TeamController.java
index 7114c4b903..02c51dbefe 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/TeamController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/TeamController.java
@@ -41,6 +41,11 @@ public class TeamController {
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/create")
public ResponseEntity<?> createTeam(@RequestParam("name") String name) {
+ if (name == null || name.isBlank()) {
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .body(Map.of("error", "Team name is required."));
+ }
+ name = name.trim();
if (teamRepository.existsByNameIgnoreCase(name)) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(Map.of("error", "Team name already exists."));
@@ -56,6 +61,11 @@ public class TeamController {
@Transactional
public ResponseEntity<?> renameTeam(
@RequestParam("teamId") Long teamId, @RequestParam("newName") String newName) {
+ if (newName == null || newName.isBlank()) {
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .body(Map.of("error", "Team name is required."));
+ }
+ newName = newName.trim();
Optional<Team> existing = teamRepository.findById(teamId);
if (existing.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
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 c41a63da1c..5688cd8a85 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
@@ -58,6 +58,7 @@ import stirling.software.proprietary.security.service.TeamMembershipService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
+import stirling.software.proprietary.security.util.EmailAddresses;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@UserApi
@@ -926,8 +927,7 @@ public class UserController {
private InviteResult processEmailInvite(
String email, Long teamId, String role, String loginUrl) {
try {
- // Validate email format (basic check)
- if (!email.contains("@") || !email.contains(".")) {
+ if (!EmailAddresses.isValidAccountAddress(email)) {
return InviteResult.failure(email + ": Invalid email format");
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
index 5de3beef9e..08f6148be4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
@@ -6,7 +6,6 @@ import static stirling.software.proprietary.security.service.MfaService.MFA_REQU
import static stirling.software.proprietary.security.service.MfaService.MFA_SECRET_KEY;
import java.sql.SQLException;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
@@ -46,7 +45,6 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.exception.UnsupportedProviderException;
import stirling.software.common.service.UserServiceInterface;
-import stirling.software.common.util.RegexPatternUtils;
import stirling.software.proprietary.access.model.PrincipalType;
import stirling.software.proprietary.access.model.ResourceType;
import stirling.software.proprietary.access.repository.ResourceGrantRepository;
@@ -65,6 +63,7 @@ import stirling.software.proprietary.security.model.exception.UserLimitExceededE
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
+import stirling.software.proprietary.security.util.UsernameRules;
import stirling.software.proprietary.service.UserLicenseSettingsService;
import stirling.software.proprietary.storage.model.FileShare;
import stirling.software.proprietary.storage.model.StorageCleanupEntry;
@@ -696,28 +695,7 @@ public class UserService implements UserServiceInterface {
}
public boolean isUsernameValid(String username) {
- // Checks whether the simple username is formatted correctly
- // Regular expression for user name: Min. 3 characters, max. 50 characters
- boolean isValidSimpleUsername =
- RegexPatternUtils.getInstance()
- .getUsernameValidationPattern()
- .matcher(username)
- .matches();
-
- // Checks whether the email address is formatted correctly
- // Regular expression for email addresses: Max. 320 characters, with RFC-like validation
- boolean isValidEmail =
- RegexPatternUtils.getInstance()
- .getEmailValidationPattern()
- .matcher(username)
- .matches();
-
- List<String> notAllowedUserList = new ArrayList<>();
- notAllowedUserList.add("ALL_USERS".toLowerCase(Locale.ROOT));
- notAllowedUserList.add("anonymoususer");
- String normalizedUsername = username.toLowerCase(Locale.ROOT);
- boolean notAllowedUser = notAllowedUserList.contains(normalizedUsername);
- return (isValidSimpleUsername || isValidEmail) && !notAllowedUser;
+ return UsernameRules.isValid(username);
}
private String getInvalidUsernameMessage() {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/util/EmailAddresses.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/util/EmailAddresses.java
new file mode 100644
index 0000000000..eb6057a54f
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/util/EmailAddresses.java
@@ -0,0 +1,31 @@
+package stirling.software.proprietary.security.util;
+
+import java.util.regex.Pattern;
+
+/**
+ * The shape an address must have to be worth mailing, and the stricter shape it must have to also
+ * become an account. Deliberately structural, not deliverable: full RFC 5322 buys nothing here, and
+ * only a sent message proves an address exists.
+ */
+public final class EmailAddresses {
+
+ /** Requires a domain with a 2-character-or-longer TLD; rejects "a@" and "a@b". */
+ private static final Pattern PATTERN = Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$");
+
+ private EmailAddresses() {}
+
+ /** Whether the address is worth handing to a mail server. Says nothing about account rules. */
+ public static boolean hasDeliverableShape(String value) {
+ return value != null && PATTERN.matcher(value.trim()).matches();
+ }
+
+ /**
+ * Whether an account may be created for this address. Both halves are load-bearing: the shape
+ * keeps undeliverable invites from being minted, and {@link UsernameRules} is what {@code
+ * saveUserCore} enforces, so accepting an address it rejects turns into a failure at redemption
+ * rather than at the request that offered it.
+ */
+ public static boolean isValidAccountAddress(String value) {
+ return hasDeliverableShape(value) && UsernameRules.isValid(value.trim());
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/util/UsernameRules.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/util/UsernameRules.java
new file mode 100644
index 0000000000..748b56d4de
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/util/UsernameRules.java
@@ -0,0 +1,30 @@
+package stirling.software.proprietary.security.util;
+
+import java.util.Locale;
+import java.util.Set;
+
+import stirling.software.common.util.RegexPatternUtils;
+
+/**
+ * The names an account may be stored under: a plain username, or an email address. Authority for
+ * {@code UserService.saveUserCore}, which throws when it is not satisfied, so any gate that decides
+ * an account can be created later must agree with this or it promises an account the writer will
+ * refuse.
+ */
+public final class UsernameRules {
+
+ private static final Set<String> RESERVED = Set.of("all_users", "anonymoususer");
+
+ private UsernameRules() {}
+
+ public static boolean isValid(String username) {
+ if (username == null) {
+ return false;
+ }
+ RegexPatternUtils patterns = RegexPatternUtils.getInstance();
+ boolean matchesShape =
+ patterns.getUsernameValidationPattern().matcher(username).matches()
+ || patterns.getEmailValidationPattern().matcher(username).matches();
+ return matchesShape && !RESERVED.contains(username.toLowerCase(Locale.ROOT));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java
index 14af09c6e0..3a62787c37 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java
@@ -14,7 +14,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
-import java.util.regex.Pattern;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
@@ -33,6 +32,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.EmailService;
+import stirling.software.proprietary.security.util.EmailAddresses;
import stirling.software.proprietary.storage.crypto.StorageEncryptionErrors;
import stirling.software.proprietary.storage.crypto.StorageKeyRevokedException;
import stirling.software.proprietary.storage.model.FileShare;
@@ -60,10 +60,6 @@ import stirling.software.proprietary.storage.repository.StoredFileRepository;
@Slf4j
public class FileStorageService {
- // Requires at least 2-character TLD; rejects obvious non-addresses like [email protected]
- private static final Pattern EMAIL_PATTERN =
- Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$");
-
private final StoredFileRepository storedFileRepository;
private final FolderRepository folderRepository;
private final FileShareRepository fileShareRepository;
@@ -913,7 +909,7 @@ public class FileStorageService {
}
private boolean isEmailAddress(String value) {
- return value != null && EMAIL_PATTERN.matcher(value.trim()).matches();
+ return EmailAddresses.hasDeliverableShape(value);
}
private boolean isOwner(StoredFile file, User owner) {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerMoreTest.java
index 0f89367967..6b03b0f547 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerMoreTest.java
@@ -98,6 +98,51 @@ class InviteLinkControllerMoreTest {
.value("Cannot send email without an email address"));
}
+ @Test
+ @DisplayName("rejects an address that has no deliverable domain")
+ void rejectsMalformedEmail() throws Exception {
+ mockMvc.perform(
+ post("/api/v1/invite/generate")
+ .principal(adminPrincipal)
+ .param("email", "a@"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.error").value("Invalid email address"));
+
+ verify(inviteTokenRepository, never()).save(any());
+ }
+
+ @Test
+ @DisplayName("rejects an address that could not become an account")
+ void rejectsEmailThatCannotBecomeAUsername() throws Exception {
+ mockMvc.perform(
+ post("/api/v1/invite/generate")
+ .principal(adminPrincipal)
+ .param("email", "o'[email protected]"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.error").value("Invalid email address"));
+
+ verify(inviteTokenRepository, never()).save(any());
+ }
+
+ @Test
+ @DisplayName("rejects a team that does not exist")
+ void rejectsUnknownTeam() throws Exception {
+ when(userService.usernameExistsIgnoreCase("[email protected]")).thenReturn(false);
+ when(inviteTokenRepository.findByEmail("[email protected]")).thenReturn(Optional.empty());
+ when(userLicenseSettingsService.calculateMaxAllowedUsers()).thenReturn(5);
+ when(teamRepository.findById(999_999L)).thenReturn(Optional.empty());
+
+ mockMvc.perform(
+ post("/api/v1/invite/generate")
+ .principal(adminPrincipal)
+ .param("email", "[email protected]")
+ .param("teamId", "999999"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.error").value("Team not found"));
+
+ verify(inviteTokenRepository, never()).save(any());
+ }
+
@Test
@DisplayName("returns conflict when the user already exists")
void userAlreadyExists() throws Exception {
@@ -292,6 +337,23 @@ class InviteLinkControllerMoreTest {
.andExpect(jsonPath("$.error").value("Email address is required"));
}
+ @Test
+ @DisplayName("rejects a malformed email on a general link")
+ void rejectsMalformedEmailOnAccept() throws Exception {
+ InviteToken invite = validInvite("general");
+ invite.setEmail(null);
+ when(inviteTokenRepository.findByToken("general")).thenReturn(Optional.of(invite));
+
+ mockMvc.perform(
+ post("/api/v1/invite/accept/general")
+ .param("email", "a@")
+ .param("password", "secret123"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.error").value("Invalid email address"));
+
+ verify(userService, never()).saveUserCore(any());
+ }
+
@Test
@DisplayName("creates the account using the pre-set email")
void createsWithPresetEmail() throws Exception {
@@ -300,6 +362,7 @@ class InviteLinkControllerMoreTest {
invite.setTeamId(3L);
when(inviteTokenRepository.findByToken("preset")).thenReturn(Optional.of(invite));
when(userService.usernameExistsIgnoreCase("[email protected]")).thenReturn(false);
+ when(teamRepository.existsById(3L)).thenReturn(true);
when(inviteRedemptionService.redeem(invite, "[email protected]", "secret123"))
.thenReturn(true);
@@ -328,6 +391,38 @@ class InviteLinkControllerMoreTest {
.andExpect(jsonPath("$.error").value("Invalid invite link"));
}
+ @Test
+ @DisplayName("rejects a malformed pre-set email from an older invite")
+ void rejectsMalformedPresetEmail() throws Exception {
+ InviteToken invite = validInvite("legacy");
+ invite.setEmail("a@");
+ when(inviteTokenRepository.findByToken("legacy")).thenReturn(Optional.of(invite));
+
+ mockMvc.perform(post("/api/v1/invite/accept/legacy").param("password", "secret123"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.error").value("Invalid email address"));
+
+ verify(userService, never()).saveUserCore(any());
+ }
+
+ @Test
+ @DisplayName("rejects an invite whose team was deleted after it was issued")
+ void rejectsDeletedTeam() throws Exception {
+ InviteToken invite = validInvite("orphan");
+ invite.setEmail("[email protected]");
+ invite.setTeamId(42L);
+ when(inviteTokenRepository.findByToken("orphan")).thenReturn(Optional.of(invite));
+ when(userService.usernameExistsIgnoreCase("[email protected]")).thenReturn(false);
+ when(teamRepository.existsById(42L)).thenReturn(false);
+
+ mockMvc.perform(post("/api/v1/invite/accept/orphan").param("password", "secret123"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.error").value("Team not found"));
+
+ verify(userService, never()).saveUserCore(any());
+ verify(inviteTokenRepository, never()).save(invite);
+ }
+
@Test
@DisplayName("refuses redemption once the licence limit is reached")
void refusesAtLicenceLimit() throws Exception {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/TeamControllerNameTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/TeamControllerNameTest.java
new file mode 100644
index 0000000000..1a0a540121
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/TeamControllerNameTest.java
@@ -0,0 +1,104 @@
+package stirling.software.proprietary.security.controller.api;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import java.util.Optional;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import stirling.software.proprietary.access.repository.ResourceGrantRepository;
+import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.repository.TeamRepository;
+import stirling.software.proprietary.security.service.TeamMembershipService;
+
+@ExtendWith(MockitoExtension.class)
+@DisplayName("TeamController - team names")
+class TeamControllerNameTest {
+
+ @Mock private TeamRepository teamRepository;
+ @Mock private UserRepository userRepository;
+ @Mock private ResourceGrantRepository resourceGrantRepository;
+ @Mock private IntegrationConfigRepository integrationConfigRepository;
+ @Mock private TeamMembershipService teamMembershipService;
+
+ private MockMvc mockMvc;
+
+ @BeforeEach
+ void setUp() {
+ TeamController controller =
+ new TeamController(
+ teamRepository,
+ userRepository,
+ resourceGrantRepository,
+ integrationConfigRepository,
+ teamMembershipService);
+ mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+ }
+
+ @Test
+ @DisplayName("refuses to create a team whose name is only whitespace")
+ void createRejectsBlankName() throws Exception {
+ mockMvc.perform(post("/api/v1/team/create").param("name", " "))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.error").value("Team name is required."));
+
+ verify(teamRepository, never()).save(any());
+ }
+
+ @Test
+ @DisplayName("stores a created team's name trimmed")
+ void createTrimsName() throws Exception {
+ when(teamRepository.existsByNameIgnoreCase("Finance")).thenReturn(false);
+
+ mockMvc.perform(post("/api/v1/team/create").param("name", " Finance "))
+ .andExpect(status().isOk());
+
+ ArgumentCaptor<Team> saved = ArgumentCaptor.forClass(Team.class);
+ verify(teamRepository).save(saved.capture());
+ org.junit.jupiter.api.Assertions.assertEquals("Finance", saved.getValue().getName());
+ }
+
+ @Test
+ @DisplayName("refuses to rename a team to only whitespace")
+ void renameRejectsBlankName() throws Exception {
+ mockMvc.perform(post("/api/v1/team/rename").param("teamId", "1").param("newName", " "))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.error").value("Team name is required."));
+
+ verify(teamRepository, never()).findById(any());
+ }
+
+ @Test
+ @DisplayName("stores a renamed team's name trimmed")
+ void renameTrimsName() throws Exception {
+ Team team = new Team();
+ team.setId(1L);
+ team.setName("Old");
+ when(teamRepository.findById(1L)).thenReturn(Optional.of(team));
+ when(teamRepository.existsByNameIgnoreCase("Finance")).thenReturn(false);
+
+ mockMvc.perform(
+ post("/api/v1/team/rename")
+ .param("teamId", "1")
+ .param("newName", " Finance "))
+ .andExpect(status().isOk());
+
+ org.junit.jupiter.api.Assertions.assertEquals("Finance", team.getName());
+ }
+}
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 21916ed3f1..8f479260fb 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
@@ -479,5 +479,24 @@ class UserControllerMoreTest {
verify(userService).saveUserCore(any());
}
+
+ @Test
+ @DisplayName("refuses an address the account writer would reject")
+ void rejectsAddressThatCannotBecomeAUsername() throws Exception {
+ applicationProperties.getMail().setEnableInvites(true);
+
+ mockMvc.perform(
+ post("/api/v1/user/admin/inviteUsers")
+ .principal(auth("admin"))
+ .param("emails", "o'[email protected]"))
+ .andExpect(status().isBadRequest())
+ .andExpect(jsonPath("$.failureCount").value(1))
+ .andExpect(jsonPath("$.successCount").value(0))
+ .andExpect(
+ jsonPath("$.errors")
+ .value("o'[email protected]: Invalid email format; "));
+
+ verify(userService, never()).saveUserCore(any());
+ }
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
index 8d716f1c4f..98922b71e1 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
@@ -42,6 +42,7 @@ import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.model.exception.UserLimitExceededException;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
+import stirling.software.proprietary.security.util.EmailAddresses;
import stirling.software.proprietary.storage.model.FileShare;
import stirling.software.proprietary.storage.model.StoredFile;
import stirling.software.proprietary.storage.repository.FileShareAccessRepository;
@@ -331,6 +332,26 @@ class UserServiceTest {
assertTrue(userService.isUsernameValid("[email protected]"));
}
+ @Test
+ void saveUserCoreAcceptsEveryAddressTheInviteGateLetsThrough() {
+ for (String address :
+ List.of(
+ "admin@localhost",
+ "a@b")) {
+ if (EmailAddresses.isValidAccountAddress(address)) {
+ assertTrue(
+ userService.isUsernameValid(address.trim()),
+ address + " passes the invite gate but saveUserCore would reject it");
+ }
+ }
+ }
+
@Test
void deleteUser_withRelatedData_cleansUpInCorrectOrder() {
User user = new User();
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/util/EmailAddressesTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/util/EmailAddressesTest.java
new file mode 100644
index 0000000000..19ac3a37c0
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/util/EmailAddressesTest.java
@@ -0,0 +1,80 @@
+package stirling.software.proprietary.security.util;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class EmailAddressesTest {
+
+ @ParameterizedTest
+ @ValueSource(strings = {"a@", "@example.com", "a@b", "[email protected]", "no-at-sign", "a [email protected]", ""})
+ void rejectsAddressesThatCouldNotBeDelivered(String value) {
+ assertFalse(EmailAddresses.isValidAccountAddress(value));
+ assertFalse(EmailAddresses.hasDeliverableShape(value));
+ }
+
+ @Test
+ void rejectsNull() {
+ assertFalse(EmailAddresses.isValidAccountAddress(null));
+ assertFalse(EmailAddresses.hasDeliverableShape(null));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"[email protected]", "[email protected]", " [email protected] "})
+ void acceptsAddressesWithARealDomain(String value) {
+ assertTrue(EmailAddresses.isValidAccountAddress(value));
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "a<b>@ex.com",
+ "a@[192.168.0.1]",
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ })
+ void refusesWhatTheAccountWriterWouldRefuse(String value) {
+ assertTrue(EmailAddresses.hasDeliverableShape(value));
+ assertFalse(UsernameRules.isValid(value.trim()));
+ assertFalse(EmailAddresses.isValidAccountAddress(value));
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "admin@localhost",
+ "a@b",
+ "a@"
+ })
+ void everythingAcceptedCanBecomeAnAccount(String value) {
+ if (EmailAddresses.isValidAccountAddress(value)) {
+ assertTrue(UsernameRules.isValid(value.trim()));
+ }
+ }
+
+ @Test
+ void refusesSingleLabelMailDomainsEvenThoughAnAccountCouldHoldThem() {
+ assertTrue(UsernameRules.isValid("admin@localhost"));
+ assertFalse(EmailAddresses.isValidAccountAddress("admin@localhost"));
+ }
+}