Skip to content

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

Fix deleted/disabled-user token handling, error stack traces, and admin-change pool starvation (#8579)

Anthony Stirlingfd1d716e12ed
diff --git a/app/core/src/main/resources/application.properties b/app/core/src/main/resources/application.properties
index 2b464633c7..87d0779d84 100644
--- a/app/core/src/main/resources/application.properties
+++ b/app/core/src/main/resources/application.properties
@@ -36,9 +36,9 @@ server.compression.mime-types=application/json,application/xml,text/html,text/pl
spring.web.error.path=/error
spring.web.error.whitelabel.enabled=false
-spring.web.error.include-stacktrace=always
-spring.web.error.include-exception=true
-spring.web.error.include-message=always
+spring.web.error.include-stacktrace=never
+spring.web.error.include-exception=false
+spring.web.error.include-message=never
# Disable Spring's built-in ProblemDetailsExceptionHandler (@Order(0)) so that
# GlobalExceptionHandler runs first and provides detailed, logged error responses.
diff --git a/app/core/src/test/java/stirling/software/SPDF/config/FallbackErrorResponseTest.java b/app/core/src/test/java/stirling/software/SPDF/config/FallbackErrorResponseTest.java
new file mode 100644
index 0000000000..88f082af58
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/config/FallbackErrorResponseTest.java
@@ -0,0 +1,65 @@
+package stirling.software.SPDF.config;
+
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import java.io.InputStream;
+import java.sql.SQLException;
+import java.util.Objects;
+import java.util.Properties;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.autoconfigure.web.ErrorProperties;
+import org.springframework.boot.context.properties.bind.Bindable;
+import org.springframework.boot.context.properties.bind.Binder;
+import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
+import org.springframework.boot.webmvc.autoconfigure.error.BasicErrorController;
+import org.springframework.boot.webmvc.error.DefaultErrorAttributes;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import jakarta.servlet.RequestDispatcher;
+
+class FallbackErrorResponseTest {
+
+ @Test
+ void fallbackErrorHidesInternalMessagesEvenWhenRequested() throws Exception {
+ Properties properties = new Properties();
+ try (InputStream input =
+ Objects.requireNonNull(getClass().getResourceAsStream("/application.properties"))) {
+ properties.load(input);
+ }
+ ErrorProperties errorProperties =
+ new Binder(new MapConfigurationPropertySource(properties))
+ .bind("spring.web.error", Bindable.of(ErrorProperties.class))
+ .get();
+ MockMvc mvc =
+ MockMvcBuilders.standaloneSetup(
+ new BasicErrorController(
+ new DefaultErrorAttributes(), errorProperties))
+ .build();
+ String internalMessage = "Could not connect to jdbc:postgresql://private-db/internal";
+
+ mvc.perform(
+ get("/error")
+ .accept(MediaType.APPLICATION_JSON)
+ .param("message", "true")
+ .param("trace", "true")
+ .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 500)
+ .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, "/api/v1/auth/me")
+ .requestAttr(RequestDispatcher.ERROR_MESSAGE, internalMessage)
+ .requestAttr(
+ RequestDispatcher.ERROR_EXCEPTION,
+ new SQLException(internalMessage)))
+ .andExpect(status().isInternalServerError())
+ .andExpect(jsonPath("$.message").doesNotExist())
+ .andExpect(jsonPath("$.trace").doesNotExist())
+ .andExpect(jsonPath("$.exception").doesNotExist())
+ .andExpect(content().string(not(containsString(internalMessage))));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AuthController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AuthController.java
index 686e4f7dea..2f464a23e5 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AuthController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AuthController.java
@@ -37,7 +37,6 @@ import stirling.software.proprietary.security.model.AuthenticationType;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.model.api.user.MfaCodeRequest;
import stirling.software.proprietary.security.model.api.user.UsernameAndPassMfa;
-import stirling.software.proprietary.security.model.exception.AuthenticationFailureException;
import stirling.software.proprietary.security.service.CustomUserDetailsService;
import stirling.software.proprietary.security.service.JwtServiceInterface;
import stirling.software.proprietary.security.service.LoginAttemptService;
@@ -369,6 +368,11 @@ public class AuthController {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
User user = (User) userDetails;
+ if (!user.isEnabled()) {
+ log.warn("Token refresh rejected: user {} is disabled", username);
+ return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
+ .body(Map.of("error", "Token refresh failed"));
+ }
Map<String, Object> newClaims = new HashMap<>();
newClaims.put("authType", user.getAuthenticationType());
@@ -412,7 +416,7 @@ public class AuthController {
"expires_in",
getTokenExpirySeconds(isDesktopClient))));
- } catch (AuthenticationFailureException e) {
+ } catch (AuthenticationException e) {
log.warn("Token refresh failed: {}", e.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Map.of("error", "Token refresh failed"));
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java
index df98cc2f53..22b8b8bc4d 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java
@@ -115,6 +115,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
try {
authenticate(request, claims);
+ } catch (AuthenticationException e) {
+ log.debug("JWT user rejected for {}: {}", tokenUsername, e.getMessage());
+ SecurityContextHolder.clearContext();
+ handleAuthenticationFailure(
+ request, response, new AuthenticationFailureException("Invalid token", e));
+ return;
} catch (SQLException | UnsupportedProviderException e) {
log.error("Error processing user authentication for user: {}", tokenUsername, e);
handleAuthenticationFailure(
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/UserAuthenticationFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/UserAuthenticationFilter.java
index 54bea98c2b..4bdd2a66fd 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/UserAuthenticationFilter.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/UserAuthenticationFilter.java
@@ -303,7 +303,6 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
"/api/v1/info/status",
"/api/v1/auth/login",
"/api/v1/auth/refresh",
- "/api/v1/auth/me",
"/api/v1/invite/validate",
"/api/v1/invite/accept",
"/api/v1/ui-data/footer-info"
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/DatabaseService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/DatabaseService.java
index 1220b04686..581fa40d9f 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/DatabaseService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/DatabaseService.java
@@ -1,6 +1,7 @@
package stirling.software.proprietary.security.service;
import java.io.IOException;
+import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -27,6 +28,8 @@ import javax.sql.DataSource;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.context.annotation.Profile;
+import org.springframework.jdbc.CannotGetJdbcConnectionException;
+import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.init.CannotReadScriptException;
import org.springframework.jdbc.datasource.init.ScriptException;
import org.springframework.stereotype.Service;
@@ -109,6 +112,7 @@ public class DatabaseService implements DatabaseServiceInterface {
private final ApplicationProperties.Datasource datasourceProps;
private final DataSource dataSource;
+ private volatile Boolean h2Database;
private final org.springframework.context.ApplicationEventPublisher events;
private final DatabaseNotificationServiceInterface backupNotificationService;
@@ -276,19 +280,6 @@ public class DatabaseService implements DatabaseServiceInterface {
@Override
public void exportDatabase() {
- List<FileInfo> filteredBackupList =
- new ArrayList<>(
- this.getBackupList().stream()
- .filter(
- backup ->
- !backup.getFileName()
- .startsWith(BACKUP_PREFIX + "user_"))
- .toList());
-
- if (filteredBackupList.size() > 5) {
- deleteOldestBackup(filteredBackupList);
- }
-
LocalDateTime dateNow = LocalDateTime.now();
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
Path insertOutputFilePath =
@@ -296,34 +287,99 @@ public class DatabaseService implements DatabaseServiceInterface {
if (isH2Database()) {
String query = "SCRIPT SIMPLE COLUMNS DROP to ?;";
+ Path pendingBackup;
+ try {
+ pendingBackup = Files.createTempFile(BACKUP_DIR, ".backup-", SQL_SUFFIX);
+ } catch (IOException e) {
+ log.error("Could not create database export file", e);
+ backupNotificationService.notifyBackupsFailure(
+ "Database backup export failed", "Could not create a backup file");
+ return;
+ }
+
+ try {
+ Connection conn = null;
+ try {
+ conn = DataSourceUtils.getConnection(dataSource);
+ try (PreparedStatement stmt = conn.prepareStatement(query)) {
+ stmt.setString(1, pendingBackup.toString());
+ stmt.execute();
+ }
+ } catch (SQLException | CannotGetJdbcConnectionException e) {
+ log.error("Error during database export: {}", e.getMessage(), e);
+ backupNotificationService.notifyBackupsFailure(
+ "Database backup export failed",
+ "Backup file: "
+ + insertOutputFilePath.getFileName()
+ + " Message: "
+ + e.getMessage());
+ return;
+ } catch (CannotReadScriptException e) {
+ log.error("Error during database export: File {} not found", pendingBackup);
+ backupNotificationService.notifyBackupsFailure(
+ "Database backup export failed",
+ "Error during database export: File "
+ + insertOutputFilePath.getFileName()
+ + " not found. Message: "
+ + e.getMessage());
+ return;
+ } finally {
+ DataSourceUtils.releaseConnection(conn, dataSource);
+ }
+
+ if (!verifyBackup(pendingBackup)) {
+ backupNotificationService.notifyBackupsFailure(
+ "Database backup verification failed",
+ "Backup file: " + insertOutputFilePath.getFileName());
+ return;
+ }
+
+ try {
+ Files.move(
+ pendingBackup,
+ insertOutputFilePath,
+ StandardCopyOption.ATOMIC_MOVE,
+ StandardCopyOption.REPLACE_EXISTING);
+ } catch (AtomicMoveNotSupportedException e) {
+ Files.move(
+ pendingBackup,
+ insertOutputFilePath,
+ StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ List<FileInfo> filteredBackupList =
+ new ArrayList<>(
+ this.getBackupList().stream()
+ .filter(
+ backup ->
+ !backup.getFileName()
+ .startsWith(
+ BACKUP_PREFIX
+ + "user_")
+ && !backup.getFilePathAsPath()
+ .equals(
+ insertOutputFilePath))
+ .toList());
+ if (filteredBackupList.size() > 5) {
+ deleteOldestBackup(filteredBackupList);
+ }
- try (Connection conn = dataSource.getConnection();
- PreparedStatement stmt = conn.prepareStatement(query)) {
- stmt.setString(1, insertOutputFilePath.toString());
- stmt.execute();
backupNotificationService.notifyBackupsSuccess(
"Database backup export completed",
"Backup file: " + insertOutputFilePath.getFileName());
- } catch (SQLException e) {
- log.error("Error during database export: {}", e.getMessage(), e);
- backupNotificationService.notifyBackupsFailure(
- "Database backup export failed",
- "Backup file: "
- + insertOutputFilePath.getFileName()
- + " Message: "
- + e.getMessage());
- } catch (CannotReadScriptException e) {
- log.error("Error during database export: File {} not found", insertOutputFilePath);
+ log.debug("Database export completed: {}", insertOutputFilePath);
+ } catch (IOException e) {
+ log.error("Could not publish database backup {}", insertOutputFilePath, e);
backupNotificationService.notifyBackupsFailure(
"Database backup export failed",
- "Error during database export: File "
- + insertOutputFilePath.getFileName()
- + " not found. Message: "
- + e.getMessage());
+ "Could not publish backup file: " + insertOutputFilePath.getFileName());
+ } finally {
+ try {
+ Files.deleteIfExists(pendingBackup);
+ } catch (IOException e) {
+ log.warn("Could not remove incomplete database backup {}", pendingBackup, e);
+ }
}
-
- log.debug("Database export completed: {}", insertOutputFilePath);
- verifyBackup(insertOutputFilePath);
}
}
@@ -441,15 +497,25 @@ public class DatabaseService implements DatabaseServiceInterface {
/** Returns {@code true} when the active runtime DataSource is genuinely H2. */
private boolean isH2Database() {
- try (Connection conn = dataSource.getConnection()) {
+ Boolean known = h2Database;
+ if (known != null) {
+ return known;
+ }
+ Connection conn = null;
+ try {
+ conn = DataSourceUtils.getConnection(dataSource);
String product = conn.getMetaData().getDatabaseProductName();
- return product != null && product.toLowerCase().contains("h2");
- } catch (SQLException e) {
+ boolean h2 = product != null && product.toLowerCase().contains("h2");
+ h2Database = h2;
+ return h2;
+ } catch (SQLException | CannotGetJdbcConnectionException e) {
log.warn(
"Could not read DatabaseMetaData to determine driver; assuming non-H2 to avoid"
+ " issuing H2-only SQL against another database: {}",
e.getMessage());
return false;
+ } finally {
+ DataSourceUtils.releaseConnection(conn, dataSource);
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerMoreTest.java
index c26030deb3..43cb93d536 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerMoreTest.java
@@ -285,6 +285,41 @@ class AuthControllerMoreTest {
verify(userDetailsService, never()).loadUserByUsername(any());
}
+
+ @Test
+ @DisplayName("refuses a disabled user instead of issuing a new token")
+ void disabledUser() throws Exception {
+ User user = webUser();
+ user.setEnabled(false);
+ stubLiveToken();
+ when(userDetailsService.loadUserByUsername("[email protected]")).thenReturn(user);
+
+ mockMvc.perform(post("/api/v1/auth/refresh"))
+ .andExpect(status().isUnauthorized())
+ .andExpect(jsonPath("$.error").value("Token refresh failed"));
+
+ verify(jwtService, never()).generateToken(any(String.class), any());
+ }
+
+ @Test
+ @DisplayName("returns 401, not 500, for a deleted user")
+ void deletedUser() throws Exception {
+ stubLiveToken();
+ when(userDetailsService.loadUserByUsername("[email protected]"))
+ .thenThrow(new UsernameNotFoundException("gone"));
+
+ mockMvc.perform(post("/api/v1/auth/refresh"))
+ .andExpect(status().isUnauthorized())
+ .andExpect(jsonPath("$.error").value("Token refresh failed"));
+ }
+
+ private void stubLiveToken() {
+ when(jwtService.extractToken(any())).thenReturn("old");
+ Map<String, Object> claims = new HashMap<>();
+ claims.put("sub", "[email protected]");
+ claims.put("exp", new Date(System.currentTimeMillis() + 60_000));
+ when(jwtService.extractClaimsAllowExpired("old")).thenReturn(claims);
+ }
}
@Nested
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilterTest.java
index 7e2bab1308..97aea324e4 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilterTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilterTest.java
@@ -1,7 +1,5 @@
package stirling.software.proprietary.security.filter;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -27,7 +25,6 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import jakarta.servlet.FilterChain;
@@ -186,7 +183,7 @@ class JwtAuthenticationFilterTest {
}
@Test
- void exceptionThrown_WhenUserNotFound() throws ServletException, IOException {
+ void entryPointCalled_WhenUserNotFound() throws ServletException, IOException {
String token = "valid-jwt-token";
String username = "nonexistentuser";
Map<String, Object> claims = Map.of("sub", username, "authType", "WEB");
@@ -206,15 +203,11 @@ class JwtAuthenticationFilterTest {
.when(SecurityContextHolder::getContext)
.thenReturn(securityContext);
- UsernameNotFoundException result =
- assertThrows(
- UsernameNotFoundException.class,
- () ->
- jwtAuthenticationFilter.doFilterInternal(
- request, response, filterChain));
+ jwtAuthenticationFilter.doFilterInternal(request, response, filterChain);
- assertEquals("User not found: " + username, result.getMessage());
verify(userDetailsService).loadUserByUsername(username);
+ verify(authenticationEntryPoint)
+ .commence(eq(request), eq(response), any(AuthenticationFailureException.class));
verify(filterChain, never()).doFilter(request, response);
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilterUserLookupTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilterUserLookupTest.java
new file mode 100644
index 0000000000..af2544079b
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilterUserLookupTest.java
@@ -0,0 +1,92 @@
+package stirling.software.proprietary.security.filter;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+import java.util.Map;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+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.web.MockFilterChain;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.security.authentication.LockedException;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.security.JwtAuthenticationEntryPoint;
+import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
+import stirling.software.proprietary.security.service.CustomUserDetailsService;
+import stirling.software.proprietary.security.service.JwtServiceInterface;
+import stirling.software.proprietary.security.service.UserService;
+
+@ExtendWith(MockitoExtension.class)
+class JwtAuthenticationFilterUserLookupTest {
+
+ private static final String TOKEN = "valid-jwt";
+
+ @Mock private JwtServiceInterface jwtService;
+ @Mock private UserService userService;
+ @Mock private CustomUserDetailsService userDetailsService;
+ @Mock private ApiKeyAuthenticationService apiKeyAuthenticationService;
+
+ private JwtAuthenticationFilter filter;
+ private MockHttpServletRequest request;
+ private MockHttpServletResponse response;
+ private MockFilterChain chain;
+
+ @BeforeEach
+ void setUp() {
+ SecurityContextHolder.clearContext();
+ filter =
+ new JwtAuthenticationFilter(
+ jwtService,
+ userService,
+ userDetailsService,
+ new JwtAuthenticationEntryPoint(),
+ new ApplicationProperties.Security(),
+ apiKeyAuthenticationService);
+ request = new MockHttpServletRequest("GET", "/api/v1/proprietary/ui-data/account");
+ response = new MockHttpServletResponse();
+ chain = new MockFilterChain();
+ when(jwtService.isJwtEnabled()).thenReturn(true);
+ when(jwtService.extractToken(request)).thenReturn(TOKEN);
+ when(jwtService.extractClaims(TOKEN)).thenReturn(Map.of("sub", "gone", "authType", "WEB"));
+ }
+
+ @AfterEach
+ void tearDown() {
+ SecurityContextHolder.clearContext();
+ }
+
+ @Test
+ void deletedUserTokenIsUnauthorizedNotServerError() throws Exception {
+ when(userDetailsService.loadUserByUsername("gone"))
+ .thenThrow(new UsernameNotFoundException("No user found with username: gone"));
+
+ filter.doFilter(request, response, chain);
+
+ assertThat(response.getStatus()).isEqualTo(401);
+ assertThat(response.getContentAsString())
+ .doesNotContain("UsernameNotFoundException")
+ .doesNotContain("gone");
+ assertThat(chain.getRequest()).isNull();
+ assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
+ }
+
+ @Test
+ void lockedUserTokenIsUnauthorized() throws Exception {
+ when(userDetailsService.loadUserByUsername("gone"))
+ .thenThrow(new LockedException("locked"));
+
+ filter.doFilter(request, response, chain);
+
+ assertThat(response.getStatus()).isEqualTo(401);
+ assertThat(chain.getRequest()).isNull();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java
index 6a6a5aa77f..d968e1bd0d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java
@@ -227,6 +227,42 @@ class UserAuthenticationFilterTest {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
+ @Test
+ @DisplayName("refuses a disabled user's session bootstrap on /auth/me")
+ void disabledUserRefusedOnAuthMe() throws Exception {
+ request.setMethod("GET");
+ request.setRequestURI("/api/v1/auth/me");
+ User user = enabledUser("blocked");
+ setAuthentication(user, "blocked");
+ when(userService.usernameExistsIgnoreCase("blocked")).thenReturn(true);
+ when(userService.isUserDisabled("blocked")).thenReturn(true);
+ when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean()))
+ .thenReturn(List.of());
+
+ filter(true).doFilter(request, response, filterChain);
+
+ assertThat(response.getStatus()).isEqualTo(403);
+ assertThat(filterChain.getRequest()).isNull();
+ }
+
+ @Test
+ @DisplayName("refuses a deleted user's session bootstrap on /auth/me")
+ void deletedUserRefusedOnAuthMe() throws Exception {
+ request.setMethod("GET");
+ request.setRequestURI("/api/v1/auth/me");
+ User user = enabledUser("ghost");
+ setAuthentication(user, "ghost");
+ when(userService.usernameExistsIgnoreCase("ghost")).thenReturn(false);
+ when(userService.isUserDisabled("ghost")).thenReturn(false);
+ when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean()))
+ .thenReturn(List.of());
+
+ filter(true).doFilter(request, response, filterChain);
+
+ assertThat(response.getStatus()).isEqualTo(401);
+ assertThat(filterChain.getRequest()).isNull();
+ }
+
private void setAuthentication(User principal, String name) {
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(
@@ -257,6 +293,15 @@ class UserAuthenticationFilterTest {
assertThat(filter(true).shouldNotFilter(request)).isTrue();
}
+ @Test
+ @DisplayName("does not skip /auth/me, so account status is checked there")
+ void doesNotSkipAuthMe() {
+ request.setMethod("GET");
+ request.setRequestURI("/api/v1/auth/me");
+
+ assertThat(filter(true).shouldNotFilter(request)).isFalse();
+ }
+
@Test
@DisplayName("does not skip an arbitrary protected API endpoint")
void doesNotSkipProtectedEndpoint() {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/DatabaseServiceBackupRetentionTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/DatabaseServiceBackupRetentionTest.java
new file mode 100644
index 0000000000..cb48d7f332
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/DatabaseServiceBackupRetentionTest.java
@@ -0,0 +1,187 @@
+package stirling.software.proprietary.security.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.sql.DataSource;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.security.database.DatabaseNotificationServiceInterface;
+
+class DatabaseServiceBackupRetentionTest {
+
+ @TempDir Path backupDir;
+
+ private final DataSource dataSource = mock(DataSource.class);
+ private final Connection connection = mock(Connection.class);
+ private final DatabaseNotificationServiceInterface notifications =
+ mock(DatabaseNotificationServiceInterface.class);
+
+ private DatabaseService service;
+ private List<Path> existingBackups;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ DatabaseMetaData metadata = mock(DatabaseMetaData.class);
+ when(dataSource.getConnection()).thenReturn(connection);
+ when(connection.getMetaData()).thenReturn(metadata);
+ when(metadata.getDatabaseProductName()).thenReturn("H2");
+ service =
+ new DatabaseService(
+ new ApplicationProperties.Datasource(),
+ dataSource,
+ notifications,
+ mock(ApplicationEventPublisher.class));
+ ReflectionTestUtils.setField(service, "BACKUP_DIR", backupDir);
+
+ existingBackups = new ArrayList<>();
+ for (int i = 0; i < 6; i++) {
+ Path backup = backupDir.resolve("backup_20260101010" + i + ".sql");
+ Files.writeString(backup, "CREATE TABLE OLD_BACKUP_" + i + "(ID INT);");
+ existingBackups.add(backup);
+ }
+ // Populate H2 detection before the connection becomes unavailable.
+ assertThat(service.getBackupList()).hasSize(6);
+ }
+
+ @Test
+ void connectionFailureRetainsExistingBackups() throws Exception {
+ when(dataSource.getConnection()).thenThrow(new SQLException("Database unavailable"));
+
+ service.exportDatabase();
+
+ assertExistingBackupsUnchanged();
+ verify(notifications).notifyBackupsFailure(anyString(), anyString());
+ verify(notifications, never()).notifyBackupsSuccess(anyString(), anyString());
+ }
+
+ @Test
+ void exportFailureRetainsExistingBackups() throws Exception {
+ PreparedStatement statement = mock(PreparedStatement.class);
+ when(connection.prepareStatement(anyString())).thenReturn(statement);
+ AtomicReference<Path> output = new AtomicReference<>();
+ doAnswer(
+ invocation -> {
+ output.set(Path.of(invocation.getArgument(1, String.class)));
+ return null;
+ })
+ .when(statement)
+ .setString(org.mockito.ArgumentMatchers.eq(1), anyString());
+ when(statement.execute())
+ .thenAnswer(
+ invocation -> {
+ Files.writeString(output.get(), "PARTIAL EXPORT;");
+ throw new SQLException("Export failed");
+ });
+
+ service.exportDatabase();
+
+ assertExistingBackupsUnchanged();
+ verify(notifications).notifyBackupsFailure(anyString(), anyString());
+ verify(notifications, never()).notifyBackupsSuccess(anyString(), anyString());
+ }
+
+ @Test
+ void verificationFailureRetainsExistingBackups() throws Exception {
+ Path sameMinuteBackup =
+ backupDir.resolve(
+ "backup_"
+ + LocalDateTime.now()
+ .format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))
+ + ".sql");
+ String previousScript = "CREATE TABLE PREVIOUS_VERIFIED_BACKUP(ID INT);";
+ Files.writeString(sameMinuteBackup, previousScript);
+ PreparedStatement statement = mock(PreparedStatement.class);
+ when(connection.prepareStatement(anyString())).thenReturn(statement);
+ AtomicReference<Path> output = new AtomicReference<>();
+ doAnswer(
+ invocation -> {
+ output.set(Path.of(invocation.getArgument(1, String.class)));
+ return null;
+ })
+ .when(statement)
+ .setString(org.mockito.ArgumentMatchers.eq(1), anyString());
+ when(statement.execute())
+ .thenAnswer(
+ invocation -> {
+ Files.writeString(output.get(), "INVALID BACKUP SQL;");
+ return false;
+ });
+
+ service.exportDatabase();
+
+ assertExistingBackupsUnchanged(sameMinuteBackup);
+ assertThat(sameMinuteBackup).hasContent(previousScript);
+ assertThat(output.get()).doesNotExist();
+ verify(notifications).notifyBackupsFailure(anyString(), anyString());
+ verify(notifications, never()).notifyBackupsSuccess(anyString(), anyString());
+ }
+
+ @Test
+ void verifiedExportPrunesOldestAutomaticBackupAndKeepsUserBackup() throws Exception {
+ DataSource working =
+ new DriverManagerDataSource("jdbc:h2:mem:" + UUID.randomUUID(), "sa", "");
+ when(dataSource.getConnection()).thenAnswer(invocation -> working.getConnection());
+ Path userBackup = backupDir.resolve("backup_user_202501010101.sql");
+ Files.writeString(userBackup, "CREATE TABLE USER_BACKUP(ID INT);");
+
+ service.exportDatabase();
+
+ assertThat(existingBackups.getFirst()).doesNotExist();
+ for (Path backup : existingBackups.subList(1, existingBackups.size())) {
+ assertThat(backup).exists();
+ }
+ assertThat(userBackup).hasContent("CREATE TABLE USER_BACKUP(ID INT);");
+ assertThat(service.getBackupList()).hasSize(7);
+ try (var paths = Files.list(backupDir)) {
+ assertThat(paths.toList())
+ .allSatisfy(
+ path ->
+ assertThat(path.getFileName().toString())
+ .matches("backup_(user_)?\\d{12}\\.sql"));
+ }
+ service.exportDatabase();
+ assertThat(service.getBackupList()).hasSize(7);
+ verify(notifications, times(2)).notifyBackupsSuccess(anyString(), anyString());
+ verify(notifications, never()).notifyBackupsFailure(anyString(), anyString());
+ }
+
+ private void assertExistingBackupsUnchanged(Path... otherBackups) throws IOException {
+ for (int i = 0; i < existingBackups.size(); i++) {
+ assertThat(existingBackups.get(i))
+ .hasContent("CREATE TABLE OLD_BACKUP_" + i + "(ID INT);");
+ }
+ List<Path> expected = new ArrayList<>(existingBackups);
+ expected.addAll(List.of(otherBackups));
+ try (var paths = Files.list(backupDir)) {
+ assertThat(paths.toList()).containsExactlyInAnyOrderElementsOf(expected);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/DatabaseServiceExportAfterCommitTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/DatabaseServiceExportAfterCommitTest.java
new file mode 100644
index 0000000000..9a2e1d844d
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/DatabaseServiceExportAfterCommitTest.java
@@ -0,0 +1,89 @@
+package stirling.software.proprietary.security.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.security.database.DatabaseNotificationServiceInterface;
+
+class DatabaseServiceExportAfterCommitTest {
+
+ @TempDir Path backupDir;
+
+ private HikariDataSource dataSource;
+ private DatabaseNotificationServiceInterface notifications;
+ private DatabaseService databaseService;
+
+ @BeforeEach
+ void setUp() {
+ HikariConfig config = new HikariConfig();
+ config.setJdbcUrl("jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1");
+ config.setUsername("sa");
+ config.setMaximumPoolSize(1);
+ config.setConnectionTimeout(1_000);
+ dataSource = new HikariDataSource(config);
+
+ notifications = mock(DatabaseNotificationServiceInterface.class);
+ databaseService =
+ new DatabaseService(
+ new ApplicationProperties.Datasource(),
+ dataSource,
+ notifications,
+ mock(ApplicationEventPublisher.class));
+ ReflectionTestUtils.setField(databaseService, "BACKUP_DIR", backupDir);
+ }
+
+ @AfterEach
+ void tearDown() {
+ dataSource.close();
+ }
+
+ @Test
+ void exportAfterCommitReusesTheTransactionConnectionInsteadOfWaitingForAnother()
+ throws Exception {
+ TransactionTemplate tx =
+ new TransactionTemplate(new DataSourceTransactionManager(dataSource));
+ AtomicLong exportMillis = new AtomicLong();
+
+ tx.executeWithoutResult(
+ status ->
+ TransactionSynchronizationManager.registerSynchronization(
+ new TransactionSynchronization() {
+ @Override
+ public void afterCommit() {
+ long start = System.nanoTime();
+ databaseService.exportDatabase();
+ exportMillis.set((System.nanoTime() - start) / 1_000_000);
+ }
+ }));
+
+ assertThat(exportMillis.get()).isLessThan(1_000);
+ try (var backups = Files.list(backupDir)) {
+ assertThat(backups.map(p -> p.getFileName().toString()))
+ .anyMatch(n -> n.startsWith(DatabaseService.BACKUP_PREFIX));
+ }
+ verify(notifications, never()).notifyBackupsFailure(anyString(), anyString());
+ }
+}