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(cors-security-headers): add cors and security headers to rest en… #367

Merged
merged 4 commits into from
Jun 9, 2023
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
29 changes: 15 additions & 14 deletions .github/workflows/gradle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ jobs:
with:
distribution: 'temurin'
java-version: 11
- uses: actions/setup-node@v2
- name: Set up NodeJS 18
uses: actions/setup-node@v2
with:
node-version: 18
- run: npm -g install @semantic-release/git semantic-release && semantic-release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- run: npx semantic-release@21.0.2
name: semantic version
- name: Set up Semantic Release
run: npm -g install @semantic-release/git semantic-release@21.0.3
- name: Semantic Release
run: npx semantic-release@21.0.3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Validate code formatting
Expand All @@ -47,7 +47,8 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Next steps will only run if generation code templates have been changed
- uses: dorny/paths-filter@v2
- name: Detect changes in generated code
uses: dorny/paths-filter@v2
id: changes
with:
filters: |
Expand All @@ -66,29 +67,29 @@ jobs:
distribution: 'temurin'
java-version: 17
# Generated code reactive
- name: Generate project to scan
- name: Generate reactive project to scan
if: steps.changes.outputs.templates == 'true'
run: ./generate_project.sh reactive
- name: Scan generated project dependencies
- name: Scan generated reactive project dependencies
if: steps.changes.outputs.templates == 'true'
working-directory: ./build/toscan
run: ./gradlew build dependencyCheckAnalyze && ./gradlew it && cat applications/app-service/build/reports/dependency-check-sonar.json
- name: Sonar analysis for generated project
- name: Sonar analysis for generated reactive project
if: github.event.pull_request.head.repo.fork == false && steps.changes.outputs.templates == 'true'
working-directory: ./build/toscan
run: ./gradlew sonarqube --stacktrace
-Dsonar.login=${{ secrets.SONAR_TOKEN_GENERATED }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Generated code reactive
- name: Generate project to scan [imperative]
# Generated code imperative
- name: Generate imperative project to scan
if: steps.changes.outputs.templates == 'true'
run: ./generate_project.sh imperative
- name: Scan generated project dependencies [imperative]
- name: Scan generated imperative project dependencies
if: steps.changes.outputs.templates == 'true'
working-directory: ./build/toscan
run: ./gradlew build dependencyCheckAnalyze && ./gradlew it && cat applications/app-service/build/reports/dependency-check-sonar.json
- name: Sonar analysis for generated project [imperative]
- name: Sonar analysis for generated imperative project
if: github.event.pull_request.head.repo.fork == false && steps.changes.outputs.templates == 'true'
working-directory: ./build/toscan
run: ./gradlew sonarqube --stacktrace
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ public void buildModule(ModuleBuilder builder) throws IOException, CleanExceptio
builder.appendToProperties("management.endpoints.web.exposure").put("include", "health");
}
builder.appendToProperties("management.endpoint.health.probes").put("enabled", true);
builder
.appendToProperties("cors")
.put("allowed-origins", "http://localhost:4200,http://localhost:8080");
new EntryPointRestMvcServer().buildModule(builder);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,8 @@ public void buildModule(ModuleBuilder builder) throws IOException, CleanExceptio
builder.appendToProperties("management.endpoints.web.exposure").put("include", "health");
}
builder.appendToProperties("management.endpoint.health.probes").put("enabled", true);
builder
.appendToProperties("cors")
.put("allowed-origins", "http://localhost:4200,http://localhost:8080");
}
}
33 changes: 33 additions & 0 deletions src/main/resources/entry-point/rest-mvc/cors-config.java.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package {{package}}.api.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

@Configuration
public class CorsConfig {

@Bean
public FilterRegistrationBean<CorsFilter> corsFilter(@Value("${cors.allowed-origins}") String origins) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(List.of(origins.split(",")));
config.setAllowedMethods(Arrays.asList("POST", "GET")); // TODO: Check others required methods
config.setAllowedHeaders(List.of(CorsConfiguration.ALL));

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);

final FilterRegistrationBean<CorsFilter> corsFilter = new FilterRegistrationBean<>(new CorsFilter(source));
corsFilter.setOrder(Ordered.HIGHEST_PRECEDENCE);
return corsFilter;
}
}
4 changes: 3 additions & 1 deletion src/main/resources/entry-point/rest-mvc/definition.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
{
"folders": [
"infrastructure/entry-points/api-rest/src/test/{{language}}/{{packagePath}}/api"
"infrastructure/entry-points/api-rest/src/test/{{language}}/{{packagePath}}/api/config"
],
"files": {},
"java": {
"entry-point/rest-mvc/api.java.mustache": "infrastructure/entry-points/api-rest/src/main/{{language}}/{{packagePath}}/api/ApiRest.java",
"entry-point/rest-mvc/cors-config.java.mustache": "infrastructure/entry-points/api-rest/src/main/{{language}}/{{packagePath}}/api/config/CorsConfig.java",
"entry-point/rest-mvc/security-headers-filter.java.mustache": "infrastructure/entry-points/api-rest/src/main/{{language}}/{{packagePath}}/api/config/SecurityHeadersFilter.java",
"entry-point/rest-mvc/api.unit.test.java.mustache": "infrastructure/entry-points/api-rest/src/test/{{language}}/{{packagePath}}/api/ApiRestTest.java",
"entry-point/rest-mvc/build.gradle.mustache": "infrastructure/entry-points/api-rest/build.gradle"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package {{package}}.api.config;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
@WebFilter("/**")
public class SecurityHeadersFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse header = (HttpServletResponse) response;
header.setHeader("Content-Security-Policy", "default-src 'self'; frame-ancestors 'self'; form-action 'self'");
header.setHeader("Strict-Transport-Security", "max-age=31536000;");
header.setHeader("X-Content-Type-Options", "nosniff");
header.setHeader("Server", "");
header.setHeader("Cache-Control", "no-store");
header.setHeader("Pragma", "no-cache");
header.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
chain.doFilter(request, response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package {{package}}.api.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

@Configuration
public class CorsConfig {

@Bean
CorsWebFilter corsWebFilter(@Value("${cors.allowed-origins}") String origins) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(List.of(origins.split(",")));
config.setAllowedMethods(Arrays.asList("POST", "GET")); // TODO: Check others required methods
config.setAllowedHeaders(List.of(CorsConfiguration.ALL));

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);

return new CorsWebFilter(source);
}
}
4 changes: 3 additions & 1 deletion src/main/resources/entry-point/rest-webflux/definition.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
{
"folders": [
"infrastructure/entry-points/reactive-web/src/test/{{language}}/{{packagePath}}/api"
"infrastructure/entry-points/reactive-web/src/test/{{language}}/{{packagePath}}/api/config"
],
"files": {
},
"java": {
"entry-point/rest-webflux/api.java.mustache": "infrastructure/entry-points/reactive-web/src/main/{{language}}/{{packagePath}}/api/ApiRest.java",
"entry-point/rest-webflux/cors-config.java.mustache": "infrastructure/entry-points/reactive-web/src/main/{{language}}/{{packagePath}}/api/config/CorsConfig.java",
"entry-point/rest-webflux/security-headers-filter.java.mustache": "infrastructure/entry-points/reactive-web/src/main/{{language}}/{{packagePath}}/api/config/SecurityHeadersConfig.java",
"entry-point/rest-webflux/api.unit.test.java.mustache": "infrastructure/entry-points/reactive-web/src/test/{{language}}/{{packagePath}}/api/ApiRestTest.java",
"entry-point/rest-webflux/build.gradle.mustache": "infrastructure/entry-points/reactive-web/build.gradle"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
"java": {
"entry-point/rest-webflux/router-functions/router.java.mustache": "infrastructure/entry-points/reactive-web/src/main/{{language}}/{{packagePath}}/api/RouterRest.java",
"entry-point/rest-webflux/router-functions/handler.java.mustache": "infrastructure/entry-points/reactive-web/src/main/{{language}}/{{packagePath}}/api/Handler.java",
"entry-point/rest-webflux/cors-config.java.mustache": "infrastructure/entry-points/reactive-web/src/main/{{language}}/{{packagePath}}/api/config/CorsConfig.java",
"entry-point/rest-webflux/security-headers-filter.java.mustache": "infrastructure/entry-points/reactive-web/src/main/{{language}}/{{packagePath}}/api/config/SecurityHeadersConfig.java",
"entry-point/rest-webflux/router-functions/router.unit.test.java.mustache": "infrastructure/entry-points/reactive-web/src/test/{{language}}/{{packagePath}}/api/RouterRestTest.java",
"entry-point/rest-webflux/build.gradle.mustache": "infrastructure/entry-points/reactive-web/build.gradle"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package {{package}}.api.config;

import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Component
public class SecurityHeadersConfig implements WebFilter {

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
HttpHeaders headers = exchange.getResponse().getHeaders();
headers.set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'self'; form-action 'self'");
headers.set("Strict-Transport-Security", "max-age=31536000;");
headers.set("X-Content-Type-Options", "nosniff");
headers.set("Server", "");
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
return chain.filter(exchange);
}
}