Skip to content

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

fix(licensing): stop concurrent signups exceeding the licensed user limit (#7806)

ConnorYohec1df15b0515
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/UserLicenseSettingsRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/UserLicenseSettingsRepository.java
index 15b35e1bf4..0ee44f7be0 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/UserLicenseSettingsRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/UserLicenseSettingsRepository.java
@@ -3,8 +3,13 @@ package stirling.software.proprietary.security.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Lock;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
+import jakarta.persistence.LockModeType;
+
import stirling.software.proprietary.model.UserLicenseSettings;
@Repository
@@ -18,4 +23,18 @@ public interface UserLicenseSettingsRepository extends JpaRepository<UserLicense
default Optional<UserLicenseSettings> findSettings() {
return findById(UserLicenseSettings.SINGLETON_ID);
}
+
+ /**
+ * Reads the singleton row under a write lock, so that concurrent callers serialise behind
+ * whoever holds it until that transaction commits. Used to admit users against the licensed
+ * limit: the seat count is only trustworthy if nobody else can insert a user between the count
+ * and our own insert.
+ */
+ @Lock(LockModeType.PESSIMISTIC_WRITE)
+ @Query("select s from UserLicenseSettings s where s.id = :id")
+ Optional<UserLicenseSettings> findSettingsForUpdate(@Param("id") Long id);
+
+ default Optional<UserLicenseSettings> lockSettings() {
+ return findSettingsForUpdate(UserLicenseSettings.SINGLETON_ID);
+ }
}
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 b35397c646..f5f9301ad3 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
@@ -31,6 +31,8 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -501,6 +503,7 @@ public class UserService implements UserServiceInterface {
* @throws SQLException If a database error occurs
* @throws UnsupportedProviderException If an unsupported provider is specified
*/
+ @Transactional(rollbackFor = Exception.class)
public User saveUserCore(SaveUserRequest request)
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
@@ -566,12 +569,53 @@ public class UserService implements UserServiceInterface {
userRepository.save(user);
teamMembershipService.syncMembership(user);
- // Export database
- databaseService.exportDatabase();
+ exportAfterCommit();
return user;
}
+ /**
+ * Exports the database once this transaction commits, rather than inside it.
+ *
+ * <p>Two reasons it cannot run inline. The export opens its own connection, so our insert is
+ * still invisible to it and the backup it writes would omit the user we just created. And on EE
+ * it ends in a synchronous notification mail with no configured timeout, which would hold the
+ * admission lock taken in {@link #enforceUserLimit} for as long as the mail server takes to
+ * answer -- long enough for concurrent signups to give up on the lock rather than queue behind
+ * it.
+ *
+ * <p>Registered as a synchronization rather than moved below the call site because {@link
+ * #processSSOPostLogin} calls this method from inside its own transaction, where returning from
+ * {@code saveUserCore} does not commit anything.
+ */
+ private void exportAfterCommit() throws SQLException, UnsupportedProviderException {
+ if (!TransactionSynchronizationManager.isSynchronizationActive()) {
+ // No surrounding transaction to defer to, so nothing is uncommitted and no lock is
+ // held: lockForUserAdmission is MANDATORY and would have refused. Export inline, as
+ // callers that expect a backup on return always have.
+ databaseService.exportDatabase();
+ return;
+ }
+ TransactionSynchronizationManager.registerSynchronization(
+ new TransactionSynchronization() {
+ @Override
+ public void afterCommit() {
+ try {
+ databaseService.exportDatabase();
+ } catch (SQLException | UnsupportedProviderException | RuntimeException e) {
+ // The user is committed, so a failed backup must not surface as a
+ // failed signup. afterCommit cannot propagate the checked exceptions
+ // exportDatabase declares, and an exception thrown here would escape
+ // the synchronization boundary into the caller regardless.
+ log.error(
+ "Database export after user creation failed: {}",
+ e.getMessage(),
+ e);
+ }
+ }
+ });
+ }
+
/**
* Last line of defence on the licence user limit. Callers that can render a useful message
* check {@code wouldExceedLimit} first and fail with their own response; this only fires when a
@@ -582,11 +626,23 @@ public class UserService implements UserServiceInterface {
return;
}
UserLicenseSettingsService settings = licenseSettingsService.getIfAvailable();
- if (settings == null || !settings.wouldExceedLimit(1)) {
+ if (settings == null) {
return;
}
- long current = getTotalUsersCount();
+ // Resolve the cap before taking the lock. Only the count and the insert need serialising,
+ // and once a linked instance takes its capacity from SaaS this call can refresh that over
+ // the network -- a row lock must not be held across a round trip that may time out.
int max = settings.calculateMaxAllowedUsers();
+
+ // Serialise admission. The lock is held until saveUserCore's transaction commits, by which
+ // point our own insert is part of the count everyone else sees, so two concurrent creations
+ // at the last free seat cannot both be admitted.
+ settings.lockForUserAdmission();
+
+ long current = getTotalUsersCount();
+ if (current + 1 <= max) {
+ return;
+ }
log.warn(
"Refusing to create user {}: would exceed the licence limit of {} ({} in use). If"
+ " this is a legitimate path it should check wouldExceedLimit() first and"
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java
index a299384f03..3a3118eed4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java
@@ -12,6 +12,7 @@ import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
@@ -444,6 +445,21 @@ public class UserLicenseSettingsService {
return false;
}
+ /**
+ * Serialises user admission against the licensed limit.
+ *
+ * <p>Takes a write lock on the licence row, held until the caller's transaction commits. The
+ * count in {@link #wouldExceedLimit(int)} is only meaningful while nobody else can insert a
+ * user, so a caller must take this lock first and perform its insert in the same transaction.
+ * Declared {@code MANDATORY} because joining the caller's transaction is the whole point: in a
+ * transaction of its own the lock would be released immediately and admission would silently go
+ * back to being racy.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public void lockForUserAdmission() {
+ settingsRepository.lockSettings();
+ }
+
/**
* Checks if adding new users would exceed the limit.
*
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/repository/UserAdmissionLockDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/repository/UserAdmissionLockDbTest.java
new file mode 100644
index 0000000000..fdd9c7396a
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/repository/UserAdmissionLockDbTest.java
@@ -0,0 +1,115 @@
+package stirling.software.proprietary.security.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.BeforeEach;
+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 org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import stirling.software.proprietary.model.UserLicenseSettings;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.User;
+
+/**
+ * Admission against the licensed user limit is a count followed by an insert. Unless the two are
+ * serialised, two requests arriving at the last free seat both see room and both insert, leaving
+ * the instance over the limit its licence was bought for.
+ *
+ * <p>This drives that race against a real (H2) database: two transactions on separate threads, each
+ * taking the licence lock, counting, and inserting only if there is room. The lock is what makes
+ * the loser observe the winner's insert, so the seat count settles on the cap rather than one past
+ * it.
+ */
+@DataJpaTest
+@Transactional(propagation = Propagation.NOT_SUPPORTED) // each thread runs its own transaction
+class UserAdmissionLockDbTest {
+
+ private static final int CAP = 2;
+
+ @Autowired private UserLicenseSettingsRepository settingsRepository;
+ @Autowired private UserRepository userRepository;
+ @Autowired private PlatformTransactionManager txManager;
+
+ @BeforeEach
+ void seedLicenceRowAndFillToOneFreeSeat() {
+ UserLicenseSettings settings = new UserLicenseSettings();
+ settings.setId(UserLicenseSettings.SINGLETON_ID);
+ settings.setGrandfatheredUserCount(CAP);
+ settings.setLicenseMaxUsers(0);
+ settings.setGrandfatheringLocked(false);
+ settings.setIntegritySalt(UUID.randomUUID().toString());
+ settings.setGrandfatheredUserSignature("");
+ settingsRepository.save(settings);
+
+ userRepository.save(user("seat-1"));
+ }
+
+ @Test
+ void twoConcurrentAdmissionsCannotBothTakeTheLastSeat() throws Exception {
+ CountDownLatch bothReady = new CountDownLatch(2);
+ AtomicInteger admitted = new AtomicInteger();
+ ExecutorService pool = Executors.newFixedThreadPool(2);
+ try {
+ for (int i = 0; i < 2; i++) {
+ String username = "racer-" + i;
+ pool.submit(
+ () -> {
+ // Line both threads up so they contend for the lock, not for the clock.
+ bothReady.countDown();
+ bothReady.await(5, TimeUnit.SECONDS);
+ new TransactionTemplate(txManager)
+ .executeWithoutResult(
+ status -> {
+ settingsRepository.lockSettings();
+ if (userRepository.count() < CAP) {
+ userRepository.save(user(username));
+ admitted.incrementAndGet();
+ }
+ });
+ return null;
+ });
+ }
+ pool.shutdown();
+ assertThat(pool.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ } finally {
+ pool.shutdownNow();
+ }
+
+ assertThat(admitted.get()).isEqualTo(1);
+ assertThat(userRepository.count()).isEqualTo(CAP);
+ }
+
+ private static User user(String username) {
+ User u = new User();
+ u.setUsername(username);
+ return u;
+ }
+
+ @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/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 4d5ed65f78..d751c6e087 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
@@ -20,6 +20,8 @@ import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.MessageSource;
import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionSynchronizationUtils;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
@@ -170,7 +172,6 @@ class UserServiceTest {
stirling.software.proprietary.service.UserLicenseSettingsService settings =
mock(stirling.software.proprietary.service.UserLicenseSettingsService.class);
when(licenseSettingsService.getIfAvailable()).thenReturn(settings);
- when(settings.wouldExceedLimit(1)).thenReturn(true);
when(settings.calculateMaxAllowedUsers()).thenReturn(100);
when(userRepository.count()).thenReturn(100L);
when(userRepository.findByUsernameIgnoreCase(Role.INTERNAL_API_USER.getRoleId()))
@@ -372,4 +373,37 @@ class UserServiceTest {
verify(userRepository, never()).delete(any());
verify(workflowSessionRepository, never()).findByOwnerOrderByCreatedAtDesc(any());
}
+
+ @Test
+ void saveUserCore_holdsTheDatabaseExportUntilAfterCommit()
+ throws SQLException, UnsupportedProviderException {
+ Team team = new Team();
+ team.setId(7L);
+ when(userRepository.save(any(User.class)))
+ .thenAnswer(invocation -> invocation.getArgument(0));
+
+ SaveUserRequest request =
+ SaveUserRequest.builder()
+ .username("deferredExport")
+ .team(team)
+ .role(Role.USER.getRoleId())
+ .authenticationType(AuthenticationType.WEB)
+ .build();
+
+ TransactionSynchronizationManager.initSynchronization();
+ try {
+ userService.saveUserCore(request);
+
+ // The insert has happened but nothing has committed. Exporting here would write a
+ // backup missing this user (the export uses its own connection) and would hold the
+ // admission lock across an EE notification mail that has no timeout.
+ verify(userRepository).save(any(User.class));
+ verify(databaseService, never()).exportDatabase();
+
+ TransactionSynchronizationUtils.triggerAfterCommit();
+ verify(databaseService).exportDatabase();
+ } finally {
+ TransactionSynchronizationManager.clearSynchronization();
+ }
+ }
}