Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: P4ADEV-1906 caching #143

Merged
merged 3 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ val jjwtVersion = "0.12.6"
val wiremockVersion = "3.10.0"
val bouncycastleVersion = "1.79"
val micrometerVersion = "1.4.1"
val caffeineVersion = "3.2.0"

dependencies {
implementation("org.springframework.boot:spring-boot-starter")
Expand All @@ -50,6 +51,8 @@ dependencies {
implementation("io.micrometer:micrometer-registry-prometheus")
implementation("org.springframework.boot:spring-boot-starter-data-redis")
implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
implementation("org.springframework.boot:spring-boot-starter-cache")
implementation("com.github.ben-manes.caffeine:caffeine:$caffeineVersion")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:$springDocOpenApiVersion")
implementation("org.codehaus.janino:janino:$janinoVersion")
Expand Down
3 changes: 3 additions & 0 deletions gradle.lockfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.2=compileClasspath
com.fasterxml.jackson.module:jackson-module-parameter-names:2.18.2=compileClasspath
com.fasterxml.jackson:jackson-bom:2.18.2=compileClasspath
com.fasterxml:classmate:1.7.0=compileClasspath
com.github.ben-manes.caffeine:caffeine:3.2.0=compileClasspath
com.google.errorprone:error_prone_annotations:2.36.0=compileClasspath
com.nimbusds:nimbus-jose-jwt:9.48=compileClasspath
io.jsonwebtoken:jjwt-api:0.12.6=compileClasspath
io.jsonwebtoken:jjwt:0.12.6=compileClasspath
Expand Down Expand Up @@ -84,6 +86,7 @@ org.springframework.boot:spring-boot-actuator-autoconfigure:3.4.1=compileClasspa
org.springframework.boot:spring-boot-actuator:3.4.1=compileClasspath
org.springframework.boot:spring-boot-autoconfigure:3.4.1=compileClasspath
org.springframework.boot:spring-boot-starter-actuator:3.4.1=compileClasspath
org.springframework.boot:spring-boot-starter-cache:3.4.1=compileClasspath
org.springframework.boot:spring-boot-starter-data-mongodb:3.4.1=compileClasspath
org.springframework.boot:spring-boot-starter-data-redis:3.4.1=compileClasspath
org.springframework.boot:spring-boot-starter-json:3.4.1=compileClasspath
Expand Down
1 change: 1 addition & 0 deletions openapi/p4pa-auth.openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,7 @@ components:
type: string
enum:
- AUTH_GENERIC_ERROR
- AUTH_NOT_FOUND
- AUTH_USER_UNAUTHORIZED
- invalid_request
- invalid_client
Expand Down
57 changes: 57 additions & 0 deletions src/main/java/it/gov/pagopa/payhub/auth/config/CacheConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package it.gov.pagopa.payhub.auth.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldNameConstants;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.TimeUnit;

@Configuration
@ConfigurationProperties(prefix = "cache")
@EnableCaching
@Data
@FieldNameConstants
public class CacheConfig {

@NestedConfigurationProperty
private CacheConfigurationProperties jwks;
@NestedConfigurationProperty
private CacheConfigurationProperties organization;
@NestedConfigurationProperty
private CacheConfigurationProperties broker;

@Data
@NoArgsConstructor
@AllArgsConstructor
public static class CacheConfigurationProperties {
private long size;
private long expireIn;
}

@Bean
@Primary
public CacheManager localCacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.registerCustomCache(Fields.organization, buildCache(organization));
cacheManager.registerCustomCache(Fields.broker, buildCache(broker));
return cacheManager;
}

private Cache<Object, Object> buildCache(CacheConfigurationProperties cacheConfig) {
return Caffeine.newBuilder()
.maximumSize(cacheConfig.size)
.expireAfterAccess(cacheConfig.expireIn, TimeUnit.MINUTES)
.build();
}
}
13 changes: 13 additions & 0 deletions src/main/java/it/gov/pagopa/payhub/auth/config/RedisConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import it.gov.pagopa.payhub.auth.dto.IamUserInfoDTO;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

Expand All @@ -19,6 +22,16 @@ public class RedisConfig {

public static final String CACHE_NAME_ACCESS_TOKEN = "ACCESS_TOKEN";

@Bean
public RedisCacheManager redisCacheManager(
ObjectProvider<RedisCacheManagerBuilderCustomizer> redisCacheManagerBuilderCustomizers,
RedisConnectionFactory redisConnectionFactory) {
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory);
builder.enableStatistics();
redisCacheManagerBuilderCustomizers.orderedStream().forEach(customizer -> customizer.customize(builder));
return builder.build();
}

@Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer(
ObjectMapper objectMapper,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package it.gov.pagopa.payhub.auth.connector.organization;

import it.gov.pagopa.pu.p4pa_organization.dto.generated.Broker;

public interface BrokerService {
Broker getBrokerById(Long id, String accessToken);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package it.gov.pagopa.payhub.auth.connector.organization;

import it.gov.pagopa.payhub.auth.connector.organization.client.BrokerClient;
import it.gov.pagopa.pu.p4pa_organization.dto.generated.Broker;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = it.gov.pagopa.payhub.auth.config.CacheConfig.Fields.broker)
public class BrokerServiceImpl implements BrokerService {

private final BrokerClient entityClient;

public BrokerServiceImpl(BrokerClient entityClient) {
this.entityClient = entityClient;
}

@Override
@Cacheable(key = "#id", unless="#result == null")
public Broker getBrokerById(Long id, String accessToken) {
return entityClient.getBrokerById(id, accessToken);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package it.gov.pagopa.payhub.auth.connector.organization;

import it.gov.pagopa.pu.p4pa_organization.dto.generated.Organization;

public interface OrganizationService {
Organization getOrganizationByIpaCode(String ipaCode, String accessToken);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package it.gov.pagopa.payhub.auth.connector.organization;

import it.gov.pagopa.payhub.auth.connector.organization.client.OrganizationSearchClient;
import it.gov.pagopa.pu.p4pa_organization.dto.generated.Organization;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = it.gov.pagopa.payhub.auth.config.CacheConfig.Fields.organization)
public class OrganizationServiceImpl implements OrganizationService {
private final OrganizationSearchClient searchClient;

public OrganizationServiceImpl(OrganizationSearchClient searchClient) {
this.searchClient = searchClient;
}

@Override
@Cacheable(key = "#ipaCode", unless="#result == null")
public Organization getOrganizationByIpaCode(String ipaCode, String accessToken) {
return searchClient.getOrganizationByIpaCode(ipaCode, accessToken);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package it.gov.pagopa.payhub.auth.connector.organization.client;

import it.gov.pagopa.payhub.auth.connector.organization.config.OrganizationApisHolder;
import it.gov.pagopa.pu.p4pa_organization.dto.generated.Broker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;

@Service
@Slf4j
public class BrokerClient {

private final OrganizationApisHolder organizationApisHolder;

public BrokerClient(OrganizationApisHolder organizationApisHolder) {
this.organizationApisHolder = organizationApisHolder;
}

public Broker getBrokerById(Long id, String accessToken) {
try {
return organizationApisHolder.getBrokerEntityControllerApi(accessToken).crudGetBroker(String.valueOf(id));
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
log.info("Broker with ID {} not found.", id);
return null;
}
throw e;
} catch (Exception e) {
log.error("An unexpected error occurred: {}", e.getMessage(), e);
throw e;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package it.gov.pagopa.payhub.auth.connector.client;
package it.gov.pagopa.payhub.auth.connector.organization.client;

import it.gov.pagopa.payhub.auth.connector.config.OrganizationApisHolder;
import it.gov.pagopa.pu.p4pa_organization.dto.generated.Broker;
import it.gov.pagopa.payhub.auth.connector.organization.config.OrganizationApisHolder;
import it.gov.pagopa.pu.p4pa_organization.dto.generated.Organization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
Expand All @@ -18,22 +17,6 @@ public OrganizationSearchClient(OrganizationApisHolder organizationApisHolder) {
this.organizationApisHolder = organizationApisHolder;
}


public Broker getBrokerById(Long id, String accessToken) {
try {
return organizationApisHolder.getBrokerEntityControllerApi(accessToken).crudGetBroker(String.valueOf(id));
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
log.info("Broker with ID {} not found.", id);
return null;
}
throw e;
} catch (Exception e) {
log.error("An unexpected error occurred: {}", e.getMessage(), e);
throw e;
}
}

public Organization getOrganizationByIpaCode(String ipaCode, String accessToken) {
try {
return organizationApisHolder.getOrganizationSearchControllerApi(accessToken)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package it.gov.pagopa.payhub.auth.connector.config;
package it.gov.pagopa.payhub.auth.connector.organization.config;

import it.gov.pagopa.pu.p4pa_organization.controller.ApiClient;
import it.gov.pagopa.pu.p4pa_organization.controller.BaseApi;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.ErrorResponse;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.stream.Collectors;

Expand Down Expand Up @@ -63,18 +65,20 @@ public ResponseEntity<String> handleConflictException(RuntimeException ex, HttpS
return ResponseEntity.status(httpStatus).body(null);
}

@ExceptionHandler({ValidationException.class, HttpMessageNotReadableException.class, MethodArgumentNotValidException.class})
@ExceptionHandler({ValidationException.class, HttpMessageNotReadableException.class, MethodArgumentNotValidException.class, MethodArgumentTypeMismatchException.class})
public ResponseEntity<AuthErrorDTO> handleViolationException(Exception ex, HttpServletRequest request) {
return handleException(ex, request, HttpStatus.BAD_REQUEST, AuthErrorDTO.ErrorEnum.INVALID_REQUEST);
}

@ExceptionHandler({ServletException.class})
public ResponseEntity<AuthErrorDTO> handleServletException(ServletException ex, HttpServletRequest request) {
@ExceptionHandler({ServletException.class, ErrorResponseException.class})
public ResponseEntity<AuthErrorDTO> handleServletException(Exception ex, HttpServletRequest request) {
HttpStatusCode httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
AuthErrorDTO.ErrorEnum errorCode = AuthErrorDTO.ErrorEnum.AUTH_GENERIC_ERROR;
if (ex instanceof ErrorResponse errorResponse) {
httpStatus = errorResponse.getStatusCode();
if (httpStatus.is4xxClientError()) {
if(httpStatus.isSameCodeAs(HttpStatus.NOT_FOUND)) {
errorCode = AuthErrorDTO.ErrorEnum.AUTH_NOT_FOUND;
} else if (httpStatus.is4xxClientError()) {
errorCode = AuthErrorDTO.ErrorEnum.INVALID_REQUEST;
}
}
Expand Down Expand Up @@ -102,6 +106,9 @@ private static void logException(Exception ex, HttpServletRequest request, HttpS
getRequestDetails(request),
httpStatus.value(),
ex.getMessage());
if(log.isDebugEnabled() && ex.getCause()!=null){
log.debug("CausedBy: ", ex.getCause());
}
}

private static String buildReturnedMessage(Exception ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,29 @@ public class A2ALegacyClaims2UserInfoMapper {

public UserInfo map(String ipaCode) {
return UserInfo.builder()
.systemUser(true)
.issuer(ipaCode)
.userId(A2A_PREFIX + ipaCode)
.name(ipaCode)
.mappedExternalUserId(buildA2AMappedExternalUserId(ipaCode))
.name("A2A")
.familyName(ipaCode)
.fiscalCode(A2A_PREFIX + ipaCode)
.fiscalCode(ipaCode)
.organizations(Collections.singletonList(UserOrganizationRoles.builder()
.organizationIpaCode(ipaCode)
.roles(Collections.singletonList(Constants.ROLE_ADMIN))
.build()))
.build();
}

private String buildA2AMappedExternalUserId(String orgIpaCode) {
return A2A_PREFIX + orgIpaCode;
}

public static boolean isA2AMappedUser(String mappedExternalUserId){
return mappedExternalUserId.startsWith(A2A_PREFIX);
}

public static String extractOrgIpaCode(String mappedExternalUserId){
return mappedExternalUserId.substring(A2A_PREFIX.length());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import it.gov.pagopa.payhub.auth.service.AccessTokenBuilderService;
import it.gov.pagopa.payhub.auth.service.AuthnService;
import it.gov.pagopa.payhub.auth.service.ValidateTokenService;
import it.gov.pagopa.payhub.auth.service.a2a.legacy.JWTLegacyHandlerService;
import it.gov.pagopa.payhub.auth.service.m2m.legacy.JWTLegacyHandlerService;
import it.gov.pagopa.payhub.dto.generated.UserInfo;
import jakarta.annotation.Nonnull;
import jakarta.servlet.FilterChain;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package it.gov.pagopa.payhub.auth.service;

import it.gov.pagopa.payhub.auth.exception.custom.InvalidGrantTypeException;
import it.gov.pagopa.payhub.auth.service.a2a.ClientCredentialService;
import it.gov.pagopa.payhub.auth.service.a2a.ValidateClientCredentialsService;
import it.gov.pagopa.payhub.auth.service.m2m.ClientCredentialService;
import it.gov.pagopa.payhub.auth.service.m2m.ValidateClientCredentialsService;
import it.gov.pagopa.payhub.auth.service.exchange.ExchangeTokenService;
import it.gov.pagopa.payhub.auth.service.exchange.ValidateExternalTokenService;
import it.gov.pagopa.payhub.auth.service.logout.LogoutService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import it.gov.pagopa.payhub.auth.model.User;
import it.gov.pagopa.payhub.auth.repository.OperatorsRepository;
import it.gov.pagopa.payhub.auth.repository.UsersRepository;
import it.gov.pagopa.payhub.auth.service.a2a.ClientService;
import it.gov.pagopa.payhub.auth.service.m2m.ClientService;
import it.gov.pagopa.payhub.auth.service.user.UserService;
import it.gov.pagopa.payhub.auth.service.user.retrieve.OperatorDTOMapper;
import it.gov.pagopa.payhub.auth.service.user.retrieve.UserDTOMapper;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = RedisConfig.CACHE_NAME_ACCESS_TOKEN)
@CacheConfig(cacheNames = RedisConfig.CACHE_NAME_ACCESS_TOKEN, cacheManager = "redisCacheManager")
class TokenStoreServiceImpl implements TokenStoreService{
@Override
@CachePut(key = "#accessToken")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package it.gov.pagopa.payhub.auth.service.a2a;
package it.gov.pagopa.payhub.auth.service.m2m;

import it.gov.pagopa.payhub.auth.exception.custom.ClientUnauthorizedException;
import it.gov.pagopa.payhub.auth.mapper.ClientMapper;
Expand Down
Loading