Skip to content

Commit

Permalink
refactor: optimize pom, use Slf4j
Browse files Browse the repository at this point in the history
  • Loading branch information
BettyB979 committed Nov 22, 2023
1 parent 981c995 commit 82070e6
Show file tree
Hide file tree
Showing 35 changed files with 352 additions and 506 deletions.
18 changes: 0 additions & 18 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
<jakarta-version>3.1.0</jakarta-version>
<jeasy-version>5.0.0</jeasy-version>
<javafaker-version>1.0.2</javafaker-version>
<orgjson-version>20231013</orgjson-version>
</properties>
<dependencies>
<dependency>
Expand Down Expand Up @@ -83,13 +82,6 @@
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<!-- Manage JSONObject and JSONArray -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${orgjson-version}</version>
</dependency>



<!-- Fakers for poc data -->
Expand All @@ -114,12 +106,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
Expand All @@ -138,10 +124,6 @@
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.servers.Server;


@SpringBootApplication
public class DatacollectionManagementApplication extends SpringBootServletInitializer {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,6 @@ public class ApplicationConfig {
@Value("${fr.insee.datacollectionmanagement.api.questioning.url}")
private String questioningUrl;

@Value("#{'${fr.insee.datacollectionmanagement.public.urls}'.split(',')}")
List<String> publicUrls;
@Value("#{'${fr.insee.datacollectionmanagement.public.urls}'}")
String[] publicUrls;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

import fr.insee.survey.datacollectionmanagement.config.auth.user.User;
import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider;
import fr.insee.survey.datacollectionmanagement.constants.AuthConstants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -18,11 +18,9 @@
import java.util.UUID;

@Component
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);


@Autowired
ApplicationConfig applicationConfig;

Expand All @@ -40,7 +38,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons

switch (applicationConfig.getAuthType()) {

case "OIDC":
case AuthConstants.OIDC:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User currentUser = userProvider.getUser(authentication);
userId=(currentUser!=null && currentUser.getId()!=null ?currentUser.getId() : "anonymous");
Expand All @@ -56,7 +54,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
ThreadContext.put("method", method);


logger.info("["+userId.toUpperCase()+"] - ["+method+"] - ["+operationPath+"]");
log.info("["+userId.toUpperCase()+"] - ["+method+"] - ["+operationPath+"]");
return true;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
package fr.insee.survey.datacollectionmanagement.config;


import java.util.Arrays;

import fr.insee.survey.datacollectionmanagement.constants.AuthConstants;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.info.BuildProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.OAuthFlows;
import io.swagger.v3.oas.models.security.Scopes;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import java.util.Arrays;


@Configuration
Expand All @@ -36,7 +31,7 @@ public class OpenAPIConfiguration {

switch(applicationConfig.getAuthType()) {

case "OIDC":
case AuthConstants.OIDC:

OAuthFlows flows = new OAuthFlows();
OAuthFlow flow = new OAuthFlow();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package fr.insee.survey.datacollectionmanagement.config;


import java.util.Arrays;
import java.util.stream.StreamSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.AbstractEnvironment;
Expand All @@ -14,11 +10,13 @@
import org.springframework.core.env.MutablePropertySources;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.stream.StreamSupport;

@Component
@Slf4j
public class PropertyLogger {

private static final Logger LOGGER = LoggerFactory.getLogger(PropertyLogger.class);

private static boolean alreadyDisplayed=false;

@EventListener
Expand All @@ -28,7 +26,7 @@ public void handleContextRefresh(ContextRefreshedEvent event) {
if (!alreadyDisplayed) {


LOGGER.info("================================ Properties ================================");
log.info("================================ Properties ================================");
final MutablePropertySources sources = ((AbstractEnvironment) env).getPropertySources();
StreamSupport.stream(sources.spliterator(), false)
.filter(ps -> ps instanceof EnumerablePropertySource)
Expand All @@ -39,8 +37,8 @@ public void handleContextRefresh(ContextRefreshedEvent event) {
|| prop.contains("pw") || prop.contains("Password")))
.filter(prop -> prop.startsWith("fr.insee") || prop.startsWith("logging") || prop.startsWith("jwt") || prop.startsWith("spring"))
.sorted()
.forEach(prop -> LOGGER.info("{}: {}", prop, env.getProperty(prop)));
LOGGER.info("===========================================================================");
.forEach(prop -> log.info("{}: {}", prop, env.getProperty(prop)));
log.info("===========================================================================");
}
alreadyDisplayed=true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter;

import java.util.Collections;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
Expand Down Expand Up @@ -50,28 +52,17 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
referrerPolicy
.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN)
))
.anonymous(anonymousConfig -> anonymousConfig
.authorities("ROLE_ADMIN"))
.authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll())
.build();
}
@Bean
@Order(1)
SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception {
return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls()); }
return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, config.getPublicUrls()); }
@Bean
public UserProvider getUserProvider() {
return auth -> new User();
}

private String[] publicUrls(){
String[] str = new String[config.getPublicUrls().size()];
for (int i = 0; i < config.getPublicUrls().size(); i++) {
str[i] = config.getPublicUrls().get(i);
}
return str;
return auth -> new User("anonymous", Collections.emptyList());
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig;
import fr.insee.survey.datacollectionmanagement.config.auth.user.User;
import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider;
import fr.insee.survey.datacollectionmanagement.constants.AuthConstants;
import fr.insee.survey.datacollectionmanagement.constants.Constants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -30,7 +31,7 @@

@Configuration
@EnableWebSecurity
@ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = "OIDC")
@ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = AuthConstants.OIDC)
@Slf4j
@AllArgsConstructor
public class OpenIDConnectSecurityContext {
Expand All @@ -46,6 +47,7 @@ public class OpenIDConnectSecurityContext {
protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
return http
.securityMatcher("/**")
//.addFilterAfter(new UserToMdcFilter(getUserProvider(config)), AuthorizationFilter.class)
.csrf(AbstractHttpConfigurer::disable)

Check failure

Code scanning / CodeQL

Disabled Spring CSRF protection High

CSRF vulnerability due to protection being disabled.
.cors(Customizer.withDefaults())
.headers(headers -> headers
Expand Down Expand Up @@ -78,9 +80,9 @@ protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
@Order(1)
SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception {
String tokenUrl = config.getKeyCloakUrl() + "/realms/" + config.getKeycloakRealm() + "/protocol/openid-connect/token";
String authorizedConnectionHost = config.getAuthType().equals("OIDC") ?
String authorizedConnectionHost = config.getAuthType().equals(AuthConstants.OIDC) ?
" " + tokenUrl : "";
return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls(), authorizedConnectionHost); }
return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, config.getPublicUrls(), authorizedConnectionHost); }

@Bean
public UserProvider getUserProvider() {
Expand All @@ -106,10 +108,6 @@ Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedAuthoritiesConverter(Appl
return new GrantedAuthorityConverter(applicationConfig);
}

private String[] publicUrls() {
return new String[]{"/csrf", "/", "/webjars/**", "/swagger-resources/**", "/environnement", Constants.API_HEALTHCHECK, "/actuator/**",
"/swagger-ui/*", "/swagger-ui/html", "/v3/api-docs/swagger-config", "/v3/api-docs", "/openapi.json"};
}


}
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package fr.insee.survey.datacollectionmanagement.config.auth.security;

import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
Expand All @@ -15,16 +12,14 @@
@Configuration
public class PublicSecurityFilterChain {

@Autowired
ApplicationConfig config;

SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls) throws Exception {
return buildSecurityPublicFilterChain(http, publicUrls, "");
}

SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls, String authorizedConnectionHost) throws Exception {
return http
.securityMatcher(publicUrls)
.csrf(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.headers(headers -> headers
.xssProtection(xssConfig -> xssConfig.headerValue(XXssProtectionHeaderWriter.HeaderValue.DISABLED))
Expand Down
Loading

0 comments on commit 82070e6

Please sign in to comment.