Skip to content

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

Reuse the already-resolved User instead of re-querying it per request (#8061)

Anthony Stirlingfcc7c489ede7
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
index 2959a6e423..75b8429867 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
@@ -261,9 +261,10 @@ public class EntitlementGuard implements HandlerInterceptor {
if (auth instanceof LinkedInstanceAuthenticationToken instance) {
return instance.getTeamId();
}
- if (auth instanceof ApiKeyAuthenticationToken
- && auth.getPrincipal() instanceof User apiUser) {
- return apiUser.getTeam() == null ? null : apiUser.getTeam().getId();
+ // SupabaseAuthenticationFilter already resolved this User onto the token; team is EAGER so
+ // it is loaded on the detached instance. Guests carry a raw Jwt, hence the lookup below.
+ if (auth != null && auth.getPrincipal() instanceof User principalUser) {
+ return principalUser.getTeam() == null ? null : principalUser.getTeam().getId();
}
String supabaseId = AuthenticationUtils.extractSupabaseId(auth);
if (supabaseId == null) {
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java b/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
index 2ecc7baeb1..2ffff1c80a 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
@@ -508,7 +508,9 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
if (auth == null || !auth.isAuthenticated()) {
return null;
}
- if (auth instanceof ApiKeyAuthenticationToken && auth.getPrincipal() instanceof User u) {
+ // SupabaseAuthenticationFilter already resolved this User onto the token; reuse it rather
+ // than paying another lookup. Guests carry a raw Jwt, hence the lookup below.
+ if (auth.getPrincipal() instanceof User u) {
return u;
}
// InstanceAiUsageService meters linked instances; their instance-id principal would only
diff --git a/app/saas/src/main/java/stirling/software/saas/security/TeamSecurityExpressions.java b/app/saas/src/main/java/stirling/software/saas/security/TeamSecurityExpressions.java
index 39c6556b2c..f6922b4ce7 100644
--- a/app/saas/src/main/java/stirling/software/saas/security/TeamSecurityExpressions.java
+++ b/app/saas/src/main/java/stirling/software/saas/security/TeamSecurityExpressions.java
@@ -20,9 +20,9 @@ import stirling.software.proprietary.security.service.UserService;
* {@code @PreAuthorize("@teamSecurity.isTeamLeader(#teamId)")} annotations on {@code
* SaasTeamController} endpoints.
*
- * <p>The current-user resolution uses the saas-mode authentication primitives ({@link
- * EnhancedJwtAuthenticationToken} from a Supabase JWT, or our existing API-key path) and looks the
- * local {@link User} row up via {@link UserService#findBySupabaseId(UUID)}.
+ * <p>The current user is the {@link User} the authentication filters already attached as the
+ * principal. Only a principal that is not a {@link User} is looked up: a guest's raw Jwt via {@link
+ * UserService#findBySupabaseId(UUID)}, a bare username via {@link UserService#findByUsername}.
*/
@Component("teamSecurity")
@Profile("saas")
@@ -76,6 +76,12 @@ public class TeamSecurityExpressions {
if (authentication == null || !authentication.isAuthenticated()) {
return null;
}
+ // Both the JWT and API-key filters attach the resolved User to the token, so prefer it over
+ // another lookup. Guests carry a raw Jwt and fall through to the supabase-id path.
+ Object principal = authentication.getPrincipal();
+ if (principal instanceof User user) {
+ return user;
+ }
if (authentication instanceof EnhancedJwtAuthenticationToken jwt) {
try {
UUID supabaseId = UUID.fromString(jwt.getSupabaseId());
@@ -84,11 +90,6 @@ public class TeamSecurityExpressions {
return null;
}
}
- // API-key path: the principal is the User entity itself.
- Object principal = authentication.getPrincipal();
- if (principal instanceof User user) {
- return user;
- }
// Username fallback.
if (principal instanceof String username) {
Optional<User> byUsername = userService.findByUsername(username);
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
index 7e53f539e7..fffc4d3882 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
@@ -760,6 +760,59 @@ class EntitlementGuardTest {
Mockito.verifyNoInteractions(entitlementService);
}
+ @Test
+ void jwtCarryingResolvedUser_resolvesTeamWithoutARepositoryLookup() throws Exception {
+ // SupabaseAuthenticationFilter attaches the User it already loaded; re-querying it here
+ // cost a second transatlantic round trip on every gated request.
+ UUID supabaseId = UUID.randomUUID();
+ SecurityContextHolder.getContext()
+ .setAuthentication(jwtAuthWithUser(supabaseId, userWithTeam(7L, 42L)));
+ when(entitlementService.getSnapshot(42L)).thenReturn(degradedSnapshot());
+
+ MockHttpServletResponse res = new MockHttpServletResponse();
+ assertThat(guard.preHandle(new MockHttpServletRequest(), res, handlerFor("aiOnly")))
+ .isFalse();
+
+ assertThat(res.getStatus()).isEqualTo(402);
+ verify(entitlementService).getSnapshot(42L);
+ verify(userRepository, never()).findBySupabaseId(any());
+ }
+
+ @Test
+ void jwtWithoutResolvedUser_stillFallsBackToTheLookup() throws Exception {
+ // Guests carry a raw Jwt rather than a User, so the lookup path must survive.
+ UUID supabaseId = UUID.randomUUID();
+ SecurityContextHolder.getContext().setAuthentication(jwtAuth(supabaseId));
+ when(userRepository.findBySupabaseId(supabaseId))
+ .thenReturn(Optional.of(userWithTeam(7L, 42L)));
+ when(entitlementService.getSnapshot(42L)).thenReturn(degradedSnapshot());
+
+ MockHttpServletResponse res = new MockHttpServletResponse();
+ assertThat(guard.preHandle(new MockHttpServletRequest(), res, handlerFor("aiOnly")))
+ .isFalse();
+
+ verify(userRepository).findBySupabaseId(supabaseId);
+ }
+
+ private static EnhancedJwtAuthenticationToken jwtAuthWithUser(UUID supabaseId, User user) {
+ Map<String, Object> claims = new HashMap<>();
+ claims.put("sub", supabaseId.toString());
+ claims.put("email", "[email protected]");
+ Jwt jwt =
+ new Jwt(
+ "token",
+ Instant.now(),
+ Instant.now().plusSeconds(3600),
+ Map.of("alg", "RS256"),
+ claims);
+ return new EnhancedJwtAuthenticationToken(
+ jwt,
+ List.of(new SimpleGrantedAuthority("ROLE_USER")),
+ supabaseId.toString(),
+ user);
+ }
+
private static EnhancedJwtAuthenticationToken jwtAuth(UUID supabaseId) {
Map<String, Object> headers = new HashMap<>();
headers.put("alg", "RS256");