View Javadoc
1   /*
2    * Copyright (C) 2024 Provincie Zeeland
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   
7   package nl.b3p.planmonitorwonen.api.configuration;
8   
9   import com.fasterxml.jackson.annotation.JsonTypeInfo;
10  import java.lang.invoke.MethodHandles;
11  import java.nio.charset.StandardCharsets;
12  import javax.sql.DataSource;
13  import org.jspecify.annotations.NonNull;
14  import org.slf4j.Logger;
15  import org.slf4j.LoggerFactory;
16  import org.springframework.beans.factory.BeanClassLoaderAware;
17  import org.springframework.beans.factory.annotation.Qualifier;
18  import org.springframework.beans.factory.annotation.Value;
19  import org.springframework.boot.jdbc.DataSourceBuilder;
20  import org.springframework.context.annotation.Bean;
21  import org.springframework.context.annotation.Configuration;
22  import org.springframework.context.annotation.Primary;
23  import org.springframework.context.annotation.Profile;
24  import org.springframework.core.convert.ConversionFailedException;
25  import org.springframework.core.convert.ConversionService;
26  import org.springframework.core.convert.TypeDescriptor;
27  import org.springframework.core.convert.support.GenericConversionService;
28  import org.springframework.jdbc.core.simple.JdbcClient;
29  import org.springframework.jdbc.datasource.DataSourceTransactionManager;
30  import org.springframework.security.jackson.SecurityJacksonModules;
31  import org.springframework.session.config.SessionRepositoryCustomizer;
32  import org.springframework.session.jdbc.JdbcIndexedSessionRepository;
33  import org.springframework.session.jdbc.config.annotation.SpringSessionDataSource;
34  import org.springframework.session.jdbc.config.annotation.SpringSessionTransactionManager;
35  import org.springframework.session.jdbc.config.annotation.web.http.EnableJdbcHttpSession;
36  import org.springframework.transaction.PlatformTransactionManager;
37  import tools.jackson.core.JacksonException;
38  import tools.jackson.core.StreamReadFeature;
39  import tools.jackson.databind.DefaultTyping;
40  import tools.jackson.databind.SerializationFeature;
41  import tools.jackson.databind.json.JsonMapper;
42  import tools.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
43  
44  @Configuration
45  @EnableJdbcHttpSession
46  @Profile("!test")
47  public class JdbcSessionConfiguration implements BeanClassLoaderAware {
48    private static final Logger logger =
49        LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
50  
51    @Value("${spring.datasource.url}")
52    private String dataSourceUrl;
53  
54    @Value("${spring.datasource.username}")
55    private String dataSourceUsername;
56  
57    @Value("${spring.datasource.password}")
58    private String dataSourcePassword;
59  
60    @Value("${tailormap.datasource.url}")
61    private String sessionDataSourceUrl;
62  
63    @Value("${tailormap.datasource.username}")
64    private String sessionDataSourceUsername;
65  
66    @Value("${tailormap.datasource.password}")
67    private String sessionDataSourcePassword;
68  
69    private static final String CREATE_SESSION_ATTRIBUTE_QUERY = """
70  INSERT INTO %TABLE_NAME%_ATTRIBUTES (SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES)
71  VALUES (?, ?, convert_from(?, 'UTF8')::jsonb)
72  """;
73  
74    private static final String UPDATE_SESSION_ATTRIBUTE_QUERY = """
75  UPDATE %TABLE_NAME%_ATTRIBUTES
76  SET ATTRIBUTE_BYTES = encode(?, 'escape')::jsonb
77  WHERE SESSION_PRIMARY_ID = ?
78  AND ATTRIBUTE_NAME = ?
79  """;
80  
81    private ClassLoader classLoader;
82  
83    @Override
84    public void setBeanClassLoader(@NonNull ClassLoader classLoader) {
85      this.classLoader = classLoader;
86    }
87  
88    @Bean
89    public DataSource dataSource() {
90      DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
91      dataSourceBuilder.url(dataSourceUrl);
92      dataSourceBuilder.username(dataSourceUsername);
93      dataSourceBuilder.password(dataSourcePassword);
94      return dataSourceBuilder.build();
95    }
96  
97    @Bean
98    public JdbcClient jdbcClient(DataSource dataSource) {
99      return JdbcClient.create(dataSource);
100   }
101 
102   @Bean(name = "tailormapJdbcClient")
103   public JdbcClient tailormapJdbcClient(@Qualifier("tailormapDataSource") DataSource data) {
104     return JdbcClient.create(data);
105   }
106 
107   @Bean
108   SessionRepositoryCustomizer<JdbcIndexedSessionRepository> customizer() {
109     return (sessionRepository) -> {
110       sessionRepository.setCreateSessionAttributeQuery(CREATE_SESSION_ATTRIBUTE_QUERY);
111       sessionRepository.setUpdateSessionAttributeQuery(UPDATE_SESSION_ATTRIBUTE_QUERY);
112     };
113   }
114 
115   @Bean(name = {"springSessionDataSource", "tailormapDataSource"})
116   @SpringSessionDataSource
117   public DataSource sessionDataSource() {
118     DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
119     dataSourceBuilder.url(sessionDataSourceUrl);
120     dataSourceBuilder.username(sessionDataSourceUsername);
121     dataSourceBuilder.password(sessionDataSourcePassword);
122     return dataSourceBuilder.build();
123   }
124 
125   /**
126    * Transaction manager for the planmonitor-wonen database, used for @Transactional. Must be primary, otherwise the
127    * Spring Boot auto-configured transaction manager backs off because of the Spring Session transaction manager below
128    * and @Transactional would use the Tailormap database.
129    */
130   @Bean
131   @Primary
132   public PlatformTransactionManager transactionManager(DataSource dataSource) {
133     return new DataSourceTransactionManager(dataSource);
134   }
135 
136   @Bean
137   @SpringSessionTransactionManager
138   public PlatformTransactionManager springSessionTransactionManager(
139       @Qualifier("springSessionDataSource") DataSource springSessionDatasource) {
140     return new DataSourceTransactionManager(springSessionDatasource);
141   }
142 
143   @Bean("springSessionConversionService")
144   public ConversionService springSessionConversionService() {
145     BasicPolymorphicTypeValidator.Builder builder = BasicPolymorphicTypeValidator.builder()
146         .allowIfSubType("org.tailormap.api.security.")
147         .allowIfSubType("org.springframework.security.")
148         .allowIfSubType("java.util.")
149         .allowIfSubType(java.lang.Number.class)
150         .allowIfSubType("java.time.")
151         .allowIfBaseType(Object.class);
152 
153     JsonMapper mapper = JsonMapper.builder()
154         .configure(
155             StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION,
156             (logger.isDebugEnabled() || logger.isTraceEnabled()))
157         .configure(SerializationFeature.INDENT_OUTPUT, (logger.isDebugEnabled() || logger.isTraceEnabled()))
158         .addMixIn(
159             org.tailormap.api.security.TailormapUserDetailsImpl.class,
160             org.tailormap.api.security.TailormapUserDetailsImplMixin.class)
161         .addMixIn(
162             org.tailormap.api.security.TailormapOidcUser.class,
163             org.tailormap.api.security.TailormapOidcUserMixin.class)
164         .addModules(SecurityJacksonModules.getModules(this.classLoader, builder))
165         .activateDefaultTyping(builder.build(), DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY)
166         .build();
167 
168     final GenericConversionService converter = new GenericConversionService();
169     // Object -> byte[] (serialize to JSON bytes)
170     // this is not actually done in the application because sessions are
171     // read-only, so this is commented out but left here for possible future use
172     //    converter.addConverter(Object.class, byte[].class, source -> {
173     //      try {
174     //        logger.debug("Serializing Spring Session: {}", source);
175     //        return mapper.writerFor(Object.class).writeValueAsBytes(source);
176     //      } catch (JacksonException e) {
177     //        logger.error("Error serializing Spring Session object: {}", source, e);
178     //        throw new ConversionFailedException(
179     //            TypeDescriptor.forObject(source), TypeDescriptor.valueOf(byte[].class), source, e);
180     //      }
181     //    });
182     // byte[] -> Object (deserialize from JSON bytes)
183     converter.addConverter(byte[].class, Object.class, source -> {
184       try {
185         logger.debug(
186             "Deserializing Spring Session from bytes, length: {} ({})",
187             source.length,
188             new String(source, StandardCharsets.UTF_8));
189         return mapper.readValue(source, Object.class);
190       } catch (JacksonException e) {
191         String preview;
192         try {
193           String content = new String(source, StandardCharsets.UTF_8);
194           int maxLength = 256;
195           if (logger.isDebugEnabled() || logger.isTraceEnabled()) {
196             preview = content;
197           } else {
198             preview = content.length() > maxLength ? content.substring(0, maxLength) + "..." : content;
199           }
200         } catch (Exception ex) {
201           preview = "<unavailable>";
202         }
203         logger.error(
204             "Error deserializing Spring Session from bytes, length: {}, preview: {}",
205             source.length,
206             preview,
207             e);
208         throw new ConversionFailedException(
209             TypeDescriptor.valueOf(byte[].class), TypeDescriptor.valueOf(Object.class), source, e);
210       }
211     });
212 
213     return converter;
214   }
215 }