#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Cut repeated database reads from the authenticated request path (#8066)
Anthony Stirlingf9b92898bca6
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.javaindex fb156d92e4..1dfadd850e 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java@@ -12,6 +12,7 @@ import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.github.benmanes.caffeine.cache.Caffeine;+import com.github.benmanes.caffeine.cache.Scheduler;import lombok.extern.slf4j.Slf4j;@@ -31,14 +32,31 @@ public class CacheConfig {/** Short-TTL cache of recent audit rows, shared by every audit-derived portal view. */private static final String PORTAL_AUDIT_EVENTS_CACHE = "portalAuditEvents";+ /** kid to KeyPair. Key material is immutable, so the bound is about exposure, not staleness. */+ public static final String SIGNING_KEYS_CACHE = "signingKeys";++ /** Single node: eviction is authoritative, so the TTL is only a backstop. */+ private static final Duration SINGLE_NODE_FALLBACK = Duration.ofMinutes(10);++ /** Clustered: one node's eviction never reaches another, so the TTL is the whole guarantee. */+ private static final Duration CLUSTERED_FALLBACK = Duration.ofSeconds(30);++ /**+ * The fallback spec is what an unregistered cache name silently inherits, so it is sized to be+ * safe rather than useful: short enough that a revoked user or role cannot outlive it on a node+ * that never saw the eviction. Register a named cache with its own spec rather than widening+ * it.+ */@Beanpublic CacheManager cacheManager() {- int keyRetentionDays = applicationProperties.getSecurity().getJwt().getKeyRetentionDays();CaffeineCacheManager cacheManager = new CaffeineCacheManager();cacheManager.setCaffeine(Caffeine.newBuilder()- .maximumSize(1000) // Make configurable?- .expireAfterWrite(Duration.ofDays(keyRetentionDays))+ .maximumSize(1000)+ .expireAfterWrite(+ applicationProperties.getCluster().isEnabled()+ ? CLUSTERED_FALLBACK+ : SINGLE_NODE_FALLBACK).recordStats());// 30s TTL keeps audit views near-live without re-scanning the DB; one entry per scope.cacheManager.registerCustomCache(@@ -48,6 +66,18 @@ public class CacheConfig {.expireAfterWrite(Duration.ofSeconds(30)).recordStats().build());+ // Bounded and idle-expiring so a token signed by a long-retired kid cannot pin its+ // decrypted private half in memory for the life of the process. The scheduler evicts on+ // time: Caffeine otherwise only expires during later cache activity, which an idle node+ // may never have.+ cacheManager.registerCustomCache(+ SIGNING_KEYS_CACHE,+ Caffeine.newBuilder()+ .maximumSize(50)+ .expireAfterAccess(Duration.ofHours(1))+ .scheduler(Scheduler.systemScheduler())+ .recordStats()+ .build());return cacheManager;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyChecker.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyChecker.javaindex e4e59e5d37..1e015c229d 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyChecker.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyChecker.java@@ -3,6 +3,7 @@ package stirling.software.proprietary.security.configuration.ee;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;+import java.time.Duration;import org.springframework.boot.context.event.ApplicationReadyEvent;import org.springframework.context.annotation.Lazy;@@ -38,6 +39,16 @@ public class LicenseKeyChecker {/** The licence key's own tier, before any Team-plan promotion. Same volatile contract. */private volatile License licenseKeyResult = License.NORMAL;+ /**+ * premiumTier() is asked several times per page load and each miss costs a DB read, so the+ * resolved tier is memoised briefly. Deliberately short: a link, unlink or key change is picked+ * up within this window without any of the callers having to invalidate anything.+ */+ private static final long TIER_MEMO_NANOS = Duration.ofSeconds(5).toNanos();++ /** nanoTime of the last successful promotion; 0 means "never resolved", so never memoised. */+ private volatile long tierResolvedAtNanos = 0L;+public LicenseKeyChecker(KeygenLicenseVerifier licenseService,ApplicationProperties applicationProperties,@@ -111,14 +122,17 @@ public class LicenseKeyChecker {private void applyTeamPlanPromotion() {if (licenseKeyResult != License.NORMAL) {premiumEnabledResult = licenseKeyResult;+ tierResolvedAtNanos = System.nanoTime();return;}Integer users;try {users = purchasedTeamUsers();} catch (RuntimeException e) {- // A failed read must not revoke a known entitlement.+ // A failed read must not revoke a known entitlement, but it must not leave an earlier+ // stamp fresh either, or the next premiumTier() skips the retry.log.debug("Linked team allowance unreadable; keeping the current tier", e);+ tierResolvedAtNanos = 0L;return;}boolean entitled = users != null && users > 0;@@ -126,6 +140,7 @@ public class LicenseKeyChecker {log.info("Linked cloud team holds a Team plan for {} users; running as Server.", users);}premiumEnabledResult = entitled ? License.SERVER : License.NORMAL;+ tierResolvedAtNanos = System.nanoTime();}/** Throws when entitlement cannot be read; null means no purchased Team capacity. */@@ -180,10 +195,18 @@ public class LicenseKeyChecker {/** Resolves the effective tier after the datasource is available. */public License premiumTier() {- applyTeamPlanPromotion();+ if (!isTierMemoFresh()) {+ applyTeamPlanPromotion();+ }return premiumEnabledResult;}+ // A failed promotion never stamps, so an unreadable entitlement is retried, not frozen.+ private boolean isTierMemoFresh() {+ long resolvedAt = tierResolvedAtNanos;+ return resolvedAt != 0L && System.nanoTime() - resolvedAt < TIER_MEMO_NANOS;+ }+public License getPremiumLicenseEnabledResult() {return premiumEnabledResult;}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.javaindex 4bdd2a66fd..941750446b 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@@ -186,15 +186,14 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {loginMethod = UserLoginType.STRINGUSER;}- // Retrieve all active sessions for the user- List<SessionInformation> sessionsInformations =- sessionPersistentRegistry.getAllSessions(principal, false);-// Check if the user exists, is disabled, or needs session invalidationif (username != null) {log.debug("Validating user: {}", username);- boolean isUserExists = userService.usernameExistsIgnoreCase(username);- boolean isUserDisabled = userService.isUserDisabled(username);+ // One read for both answers: the two helpers each loaded the same row, with its+ // EAGER authorities and team, on every request.+ Optional<User> existingUser = userService.findByUsernameIgnoreCase(username);+ boolean isUserExists = existingUser.isPresent();+ boolean isUserDisabled = existingUser.map(user -> !user.isEnabled()).orElse(false);boolean notSsoLogin =!UserLoginType.OAUTH2USER.equals(loginMethod)@@ -222,6 +221,9 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {if (!isUserExists || isUserDisabled) {log.info("Invalidating session for disabled or non-existent user: {}", username);+ // Only this branch reads the sessions, so the query stays off the happy path.+ List<SessionInformation> sessionsInformations =+ sessionPersistentRegistry.getAllSessions(principal, false);for (SessionInformation sessionsInformation : sessionsInformations) {sessionsInformation.expireNow();sessionPersistentRegistry.expireSession(sessionsInformation.getSessionId());diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/CustomUserDetailsService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/CustomUserDetailsService.javaindex e5abb22685..f747419449 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/CustomUserDetailsService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/CustomUserDetailsService.java@@ -40,25 +40,16 @@ public class CustomUserDetailsService implements UserDetailsService {"Your account has been locked due to too many failed login attempts.");}- // TODO: Remove for SaaS - Handle legacy users without authenticationType (from versions <- // 1.3.0)+ // Pre-1.3.0 users have no authenticationType. Back-fill it once rather than deriving it+ // per read: MFA and SSO detection read the stored value, so a derived one leaves them+ // broken for these users. A password means web auth; its absence means SSO.String authTypeStr = user.getAuthenticationType();if (authTypeStr == null || authTypeStr.isEmpty()) {- // Migrate legacy users by detecting authentication type based on password presence- AuthenticationType detectedType;- if (user.hasPassword()) {- // Users with passwords are likely traditional web authentication users- detectedType = AuthenticationType.WEB;- } else {- // Users without passwords are SSO users (OAuth2/SAML2/etc)- // Choose the appropriate SSO type based on what's enabled- detectedType = determinePreferredSSOType();- }-- authTypeStr = detectedType.name();- // Update the user record to set the detected authentication type+ AuthenticationType detectedType =+ user.hasPassword() ? AuthenticationType.WEB : determinePreferredSSOType();user.setAuthenticationType(detectedType);userRepository.save(user);+ authTypeStr = detectedType.name();}AuthenticationType userAuthenticationType =diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/KeyPersistenceService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/KeyPersistenceService.javaindex 7222a1b49f..f5eea7215d 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/KeyPersistenceService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/KeyPersistenceService.java@@ -18,10 +18,8 @@ import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.Base64;import java.util.List;-import java.util.Map;import java.util.Optional;import java.util.UUID;-import java.util.concurrent.ConcurrentHashMap;import org.springframework.beans.factory.annotation.Value;import org.springframework.cache.Cache;@@ -36,6 +34,7 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.configuration.InstallationPathConfig;import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.configuration.CacheConfig;import stirling.software.proprietary.security.model.JwtSigningKeyEntity;import stirling.software.proprietary.security.model.JwtVerificationKey;import stirling.software.proprietary.security.repository.JwtSigningKeyRepository;@@ -51,12 +50,13 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {public static final String PUB_KEY_SUFFIX = ".pub";private final ApplicationProperties.Security.Jwt jwtProperties;- private final Cache verifyingKeyCache;private final JwtSigningKeyRepository keyRepository;private final boolean clusterEnabled;- // kid -> KeyPair; safe to cache since key material is immutable.- private final Map<String, KeyPair> keyPairCache = new ConcurrentHashMap<>();+ // kid -> KeyPair. Immutable once minted, so this is bounded for exposure, not for staleness:+ // an unbounded map kept every historic key's decrypted private half for the life of the+ // process.+ private final Cache keyPairCache;private volatile JwtVerificationKey activeKey;@@ -66,7 +66,7 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {JwtSigningKeyRepository keyRepository,@Value("${cluster.enabled:false}") boolean clusterEnabled) {this.jwtProperties = applicationProperties.getSecurity().getJwt();- this.verifyingKeyCache = cacheManager.getCache("verifyingKeys");+ this.keyPairCache = cacheManager.getCache(CacheConfig.SIGNING_KEYS_CACHE);this.keyRepository = keyRepository;this.clusterEnabled = clusterEnabled;}@@ -110,7 +110,6 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {}JwtVerificationKey adopted =new JwtVerificationKey(newest.getKeyId(), newest.getVerifyingKey());- verifyingKeyCache.put(newest.getKeyId(), adopted);activeKey = adopted;log.info("Adopted newest JWT signing key {} from the shared DB as active",@@ -128,10 +127,6 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {generateAndStoreKeypair();return;}- for (JwtSigningKeyEntity key : keys) {- verifyingKeyCache.put(- key.getKeyId(), new JwtVerificationKey(key.getKeyId(), key.getVerifyingKey()));- }activeKey =new JwtVerificationKey(keys.getFirst().getKeyId(), keys.getFirst().getVerifyingKey());@@ -151,7 +146,6 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {keyPairCache.put(keyId, keyPair);JwtVerificationKey verificationKey = new JwtVerificationKey(keyId, verifyingKey);- verifyingKeyCache.put(keyId, verificationKey);activeKey = verificationKey;log.info("Generated and stored new JWT keypair: {}", keyId);return verificationKey;@@ -174,7 +168,7 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {if (!isKeystoreEnabled() || keyId == null) {return Optional.empty();}- KeyPair cached = keyPairCache.get(keyId);+ KeyPair cached = keyPairCache.get(keyId, KeyPair.class);if (cached != null) {return Optional.of(cached);}@@ -190,7 +184,6 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {decodePublicKey(entity.getVerifyingKey()),decodePrivateKey(entity.getSigningKey()));keyPairCache.put(keyId, keyPair);- verifyingKeyCache.put(keyId, new JwtVerificationKey(keyId, entity.getVerifyingKey()));return Optional.of(keyPair);} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {log.error("Failed to decode keypair for keyId: {}", keyId, e);@@ -211,8 +204,7 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {@Overridepublic void removeKey(String keyId) {keyRepository.deleteById(keyId);- verifyingKeyCache.evict(keyId);- keyPairCache.remove(keyId);+ keyPairCache.evict(keyId);}@Overridediff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyCheckerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyCheckerTest.javaindex 2085f43d99..6026351e64 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyCheckerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyCheckerTest.java@@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.mockito.Mockito.never;import static org.mockito.Mockito.reset;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;@@ -45,6 +46,72 @@ class LicenseKeyCheckerTest {verifyNoInteractions(verifier);}+ @Test+ void repeatedTierQueriesCollapseIntoOneEntitlementRead() {+ // /app-config asks the tier several times per page load; each miss was its own DB read.+ ApplicationProperties properties = new ApplicationProperties();+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(300);+ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, properties, userLicenseSettingsService);++ assertEquals(License.SERVER, checker.premiumTier());+ assertEquals(License.SERVER, checker.premiumTier());+ assertEquals(License.SERVER, checker.premiumTier());++ verify(userLicenseSettingsService, times(1)).refreshLinkedTeamUsers();+ }++ @Test+ void aFailedExplicitRefreshDoesNotLeaveAnEarlierTierFresh() {+ ApplicationProperties properties = new ApplicationProperties();+ when(userLicenseSettingsService.refreshLinkedTeamUsers())+ .thenReturn(300)+ .thenThrow(new IllegalStateException("Supabase unreachable"))+ .thenReturn(300);+ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, properties, userLicenseSettingsService);++ assertEquals(License.SERVER, checker.premiumTier());+ checker.onEntitlementRefreshed();+ assertEquals(License.SERVER, checker.premiumTier());++ verify(userLicenseSettingsService, times(3)).refreshLinkedTeamUsers();+ }++ @Test+ void anUnreadableEntitlementIsRetried_notMemoised() {+ // The failure path must not stamp the memo, or a transient DB error would freeze the tier+ // for the whole window instead of being retried on the next question.+ ApplicationProperties properties = new ApplicationProperties();+ when(userLicenseSettingsService.refreshLinkedTeamUsers())+ .thenThrow(new IllegalStateException("Database not initialized"))+ .thenReturn(300);+ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, properties, userLicenseSettingsService);++ assertEquals(License.NORMAL, checker.premiumTier());+ assertEquals(License.SERVER, checker.premiumTier());++ verify(userLicenseSettingsService, times(2)).refreshLinkedTeamUsers();+ }++ @Test+ void anInstalledKeyNeedsNoEntitlementRead() {+ // A paid key short-circuits the promotion, so the linked-team lookup never runs at all.+ ApplicationProperties properties = new ApplicationProperties();+ properties.getPremium().setEnabled(true);+ properties.getPremium().setKey("a-key");+ when(verifier.verifyLicense("a-key")).thenReturn(License.ENTERPRISE);+ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, properties, userLicenseSettingsService);+ checker.init();++ assertEquals(License.ENTERPRISE, checker.premiumTier());+ assertEquals(License.ENTERPRISE, checker.premiumTier());++ verify(userLicenseSettingsService, never()).refreshLinkedTeamUsers();+ }+@Testvoid premiumDisabled_skipsVerification() {ApplicationProperties props = new ApplicationProperties();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.javaindex d968e1bd0d..71486947f5 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@@ -3,6 +3,7 @@ package stirling.software.proprietary.security.filter;import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyBoolean;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;@@ -111,10 +112,7 @@ class UserAuthenticationFilterTest {Optional.of(new ApiKeyAuthentication(user, "Prod (sk_demo0000)", user.getAuthorities())));- when(userService.usernameExistsIgnoreCase("api-user")).thenReturn(true);- when(userService.isUserDisabled("api-user")).thenReturn(false);- when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean()))- .thenReturn(List.of());+ when(userService.findByUsernameIgnoreCase("api-user")).thenReturn(Optional.of(user));filter(true).doFilter(request, response, filterChain);@@ -177,15 +175,16 @@ class UserAuthenticationFilterTest {request.setRequestURI("/api/v1/some/protected");User user = enabledUser("alice");setAuthentication(user, "alice");- when(userService.usernameExistsIgnoreCase("alice")).thenReturn(true);- when(userService.isUserDisabled("alice")).thenReturn(false);- when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean()))- .thenReturn(List.of());+ when(userService.findByUsernameIgnoreCase("alice")).thenReturn(Optional.of(user));filter(true).doFilter(request, response, filterChain);assertThat(filterChain.getRequest()).isSameAs(request);assertThat(response.getStatus()).isEqualTo(200);+ // Sessions are only needed to expire a rejected user, so the happy path must not read+ // them, and one lookup must answer both existence and enablement.+ verify(sessionPersistentRegistry, never()).getAllSessions(any(), anyBoolean());+ verify(userService).findByUsernameIgnoreCase("alice");}@Test@@ -194,8 +193,7 @@ class UserAuthenticationFilterTest {request.setRequestURI("/api/v1/some/protected");User user = enabledUser("ghost");setAuthentication(user, "ghost");- when(userService.usernameExistsIgnoreCase("ghost")).thenReturn(false);- when(userService.isUserDisabled("ghost")).thenReturn(false);+ when(userService.findByUsernameIgnoreCase("ghost")).thenReturn(Optional.empty());SessionInformation sessionInfo =new SessionInformation(user, "sess-1", new java.util.Date());when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean()))@@ -215,8 +213,8 @@ class UserAuthenticationFilterTest {request.setRequestURI("/api/v1/some/protected");User user = enabledUser("blocked");setAuthentication(user, "blocked");- when(userService.usernameExistsIgnoreCase("blocked")).thenReturn(true);- when(userService.isUserDisabled("blocked")).thenReturn(true);+ user.setEnabled(false);+ when(userService.findByUsernameIgnoreCase("blocked")).thenReturn(Optional.of(user));when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean())).thenReturn(List.of());diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/CustomUserDetailsServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/CustomUserDetailsServiceTest.javanew file mode 100644index 0000000000..b763b204d4--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/CustomUserDetailsServiceTest.java@@ -0,0 +1,85 @@+package stirling.software.proprietary.security.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.RETURNS_DEFAULTS;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;++import java.util.Optional;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.model.AuthenticationType;+import stirling.software.proprietary.security.model.User;++@ExtendWith(MockitoExtension.class)+class CustomUserDetailsServiceTest {++ @Mock private LoginAttemptService loginAttemptService;++ private UserRepository userRepository;++ /**+ * Answers every {@code findByUsername*} lookup with {@code user}, so these tests pin the+ * back-fill rather than which repository method resolves the user.+ */+ private CustomUserDetailsService serviceFor(User user) {+ userRepository =+ mock(+ UserRepository.class,+ invocation ->+ invocation.getMethod().getName().startsWith("findByUsername")+ && invocation.getMethod().getReturnType()+ == Optional.class+ ? Optional.of(user)+ : RETURNS_DEFAULTS.answer(invocation));+ return new CustomUserDetailsService(+ userRepository, loginAttemptService, new ApplicationProperties.Security());+ }++ private User legacyUser(String password) {+ User user = new User();+ user.setUsername("legacy");+ user.setPassword(password);+ return user;+ }++ @Test+ void legacyUserWithPasswordIsBackFilledAsWebAndSaved() {+ User user = legacyUser("hash");++ serviceFor(user).loadUserByUsername("legacy");++ assertThat(user.getAuthenticationType()).isEqualTo("web");+ verify(userRepository).save(user);+ }++ @Test+ void legacyUserWithoutPasswordIsBackFilledAsSso() {+ User user = legacyUser(null);++ serviceFor(user).loadUserByUsername("legacy");++ assertThat(user.getAuthenticationType()).isEqualTo("oauth2");+ verify(userRepository).save(user);+ }++ @Test+ void userWithStoredTypeIsNotWritten() {+ User user = new User();+ user.setUsername("current");+ user.setPassword("hash");+ user.setAuthenticationType(AuthenticationType.WEB);++ serviceFor(user).loadUserByUsername("current");++ verify(userRepository, never()).save(any());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/KeyPersistenceServiceInterfaceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/KeyPersistenceServiceInterfaceTest.javaindex f16117fdb9..96c0625abc 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/KeyPersistenceServiceInterfaceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/KeyPersistenceServiceInterfaceTest.java@@ -27,6 +27,7 @@ import org.springframework.cache.CacheManager;import org.springframework.cache.concurrent.ConcurrentMapCacheManager;import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.configuration.CacheConfig;import stirling.software.proprietary.security.model.JwtSigningKeyEntity;import stirling.software.proprietary.security.model.JwtVerificationKey;import stirling.software.proprietary.security.repository.JwtSigningKeyRepository;@@ -40,17 +41,17 @@ class KeyPersistenceServiceInterfaceTest {@Mock private ApplicationProperties.Security.Jwt jwtConfig;@Mock private JwtSigningKeyRepository keyRepository;+ private CacheManager cacheManager;+private KeyPersistenceService keyPersistenceService;private KeyPair testKeyPair;- private CacheManager cacheManager;@BeforeEachvoid setUp() throws NoSuchAlgorithmException {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(2048);testKeyPair = keyPairGenerator.generateKeyPair();-- cacheManager = new ConcurrentMapCacheManager("verifyingKeys");+ cacheManager = new ConcurrentMapCacheManager(CacheConfig.SIGNING_KEYS_CACHE);lenient().when(applicationProperties.getSecurity()).thenReturn(security);lenient().when(security.getJwt()).thenReturn(jwtConfig);