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

run backend formatter and start fixing lint changes #1179

Closed
Closed
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
47 changes: 8 additions & 39 deletions .github/workflows/format-action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: 'Format'
on: [push]
jobs:

Frontend:
frontend:
runs-on: ubuntu-latest
defaults:
run:
Expand All @@ -15,33 +15,19 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22.10.0
node-version: ${{vars.NODE_VERSION}}

- name: Npm install
run: npm ci

- name: Format frontend
run: npm run format
run: npm run check

- name: Commit and Push formated frontend
shell: bash
env:
COMMITPREFIX: '[FM]'
run: |
git config --global user.email "[email protected]"
git config --global user.name "GitHub Actions"
git add . || {
echo "No files were changed, so we did not commit anything"
exit 1
}
git commit -m "$COMMITPREFIX Automated formating frontend" || {
echo "No changes to commit, skipping push"
exit 0
}
git push -f

Backend:
backend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: backend
steps:
- name: Checkout
uses: actions/checkout@v4
Expand All @@ -55,21 +41,4 @@ jobs:
settings-path: ${{github.workspace}}

- name: Format backend
run: mvn formatter:format -f backend/pom.xml

- name: Commit and Push formated backend
shell: bash
env:
COMMITPREFIX: '[FM]'
run: |
git config --global user.email "[email protected]"
git config --global user.name "GitHub Actions"
git add . || {
echo "No files were changed, so we did not commit anything"
exit 1
}
git commit -m "$COMMITPREFIX Automated formating backend" || {
echo "No changes to commit, skipping push"
exit 0
}
git push -f
run: mvn spotless:check
11 changes: 5 additions & 6 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,16 @@ USING DOCKER
- backend/target

Formatting:
- Check code formatting: `mvn formatter:validate`
- Format the code: `mvn formatter:format`
- Check code formatting: `mvn spotless:check`
- Format the code: `mvn spotless:apply`

The `compile` goal execute also a `formatter:format` goal.
The `compile` goal execute also a `spotless:apply` goal.

Verify the Backend for coverage check:
- `mvn clean verify`

## Formatting
We use the **formatter-maven-plugin** Plugin for formatting the Java code:
https://code.revelc.net/formatter-maven-plugin/

We use the **spotless** Plugin for formatting the Java code:
https://github.com/diffplug/spotless
## Build
_tbd_
34 changes: 21 additions & 13 deletions backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -231,24 +231,32 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>

<plugin>
<groupId>net.revelc.code.formatter</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<version>2.24.1</version>
<configuration>
<compilerSource>${maven.compiler.source}</compilerSource>
<compilerCompliance>${maven.compiler.source}</compilerCompliance>
<compilerTargetPlatform>${maven.compiler.source}</compilerTargetPlatform>
</configuration>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>2.43.0</version>
<executions>
<execution>
<id>code-format</id>
<goals>
<goal>format</goal>
<goal>apply</goal>
</goals>
</execution>
</executions>
<configuration>
<java>
<eclipse>
<version>4.26</version>
<file>${project.basedir}/src/main/resources/formatting.xml</file>
</eclipse>
<removeUnusedImports />
<importOrder>
<order>java|javax,ch.puzzle,org,com,com.diffplug,,\#com.diffplug,\#</order>
<semanticSort>true</semanticSort>
</importOrder>
<formatAnnotations />
</java>
</configuration>
</plugin>
</plugins>
</build>
Expand Down Expand Up @@ -305,9 +313,9 @@
<build>
<plugins>
<plugin>
<groupId>net.revelc.code.formatter</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<version>2.24.1</version>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>2.43.0</version>
<executions>
<execution>
<id>code-format</id>
Expand Down
5 changes: 1 addition & 4 deletions backend/src/main/java/ch/puzzle/okr/ErrorKey.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package ch.puzzle.okr;

public enum ErrorKey {
ATTRIBUTE_NULL, ATTRIBUTE_CHANGED, ATTRIBUTE_SET_FORBIDDEN, ATTRIBUTE_NOT_SET, ATTRIBUTE_CANNOT_CHANGE,
ATTRIBUTE_MUST_BE_DRAFT, KEY_RESULT_CONVERSION, ALREADY_EXISTS_SAME_NAME, CONVERT_TOKEN, DATA_HAS_BEEN_UPDATED,
MODEL_NULL, MODEL_WITH_ID_NOT_FOUND, NOT_AUTHORIZED_TO_READ, NOT_AUTHORIZED_TO_WRITE, NOT_AUTHORIZED_TO_DELETE,
TOKEN_NULL, TRIED_TO_DELETE_LAST_ADMIN, TRIED_TO_REMOVE_LAST_OKR_CHAMPION
ATTRIBUTE_NULL, ATTRIBUTE_CHANGED, ATTRIBUTE_SET_FORBIDDEN, ATTRIBUTE_NOT_SET, ATTRIBUTE_CANNOT_CHANGE, ATTRIBUTE_MUST_BE_DRAFT, KEY_RESULT_CONVERSION, ALREADY_EXISTS_SAME_NAME, CONVERT_TOKEN, DATA_HAS_BEEN_UPDATED, MODEL_NULL, MODEL_WITH_ID_NOT_FOUND, NOT_AUTHORIZED_TO_READ, NOT_AUTHORIZED_TO_WRITE, NOT_AUTHORIZED_TO_DELETE, TOKEN_NULL, TRIED_TO_DELETE_LAST_ADMIN, TRIED_TO_REMOVE_LAST_OKR_CHAMPION
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ch.puzzle.okr;

import ch.puzzle.okr.multitenancy.FlywayMultitenantMigrationInitializer;

import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
Expand Down
17 changes: 8 additions & 9 deletions backend/src/main/java/ch/puzzle/okr/ForwardFilter.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
package ch.puzzle.okr;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.GenericFilterBean;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
import java.util.Arrays;

public class ForwardFilter extends GenericFilterBean {

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

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
logger.debug(String.format("====> pass through the filter '%s'", request.getRequestURI()));
filterChain.doFilter(servletRequest, servletResponse);
Expand Down
4 changes: 2 additions & 2 deletions backend/src/main/java/ch/puzzle/okr/OkrApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class OkrApplication {
public static void main(String[] args) {

new SpringApplicationBuilder(OkrApplication.class) //
.initializers(new OkrApplicationContextInitializer()) //
.run(args);
.initializers(new OkrApplicationContextInitializer()) //
.run(args);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ch.puzzle.okr;

import ch.puzzle.okr.multitenancy.HibernateContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
Expand Down
5 changes: 3 additions & 2 deletions backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package ch.puzzle.okr;

import java.util.Map;

import ch.puzzle.okr.exception.OkrResponseStatusException;

import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

@Component
public class OkrErrorAttributes extends DefaultErrorAttributes {

Expand Down
12 changes: 8 additions & 4 deletions backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
package ch.puzzle.okr;

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.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenAPI30Configuration {
@Bean
public OpenAPI customizeOpenAPI() {
final String securitySchemeName = "bearerAuth";
return new OpenAPI().addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
.components(new Components().addSecuritySchemes(securitySchemeName, new SecurityScheme()
.name(securitySchemeName).type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")));
.components(new Components().addSecuritySchemes(securitySchemeName,
new SecurityScheme().name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}

}
59 changes: 29 additions & 30 deletions backend/src/main/java/ch/puzzle/okr/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
package ch.puzzle.okr;

import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import com.nimbusds.jwt.proc.JWTClaimsSetAwareJWSKeySelector;
import com.nimbusds.jwt.proc.JWTProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -33,6 +28,12 @@
import org.springframework.security.web.header.writers.CrossOriginResourcePolicyHeaderWriter;
import org.springframework.security.web.header.writers.StaticHeadersWriter;

import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import com.nimbusds.jwt.proc.JWTClaimsSetAwareJWSKeySelector;
import com.nimbusds.jwt.proc.JWTProcessor;

import static org.springframework.security.web.header.writers.CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP;
import static org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER;
import static org.springframework.security.web.header.writers.XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK;
Expand All @@ -50,17 +51,20 @@ public class SecurityConfig {

@Bean
@Order(1) // Must be First order! Otherwise unauthorized Requests are sent to Controllers
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, @Value("${connect.src}") String connectSrc)
throws Exception {
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, @Value("${connect.src}") String connectSrc) throws Exception {

this.connectSrc = connectSrc;
setHeaders(http);
http.addFilterAfter(new ForwardFilter(), BasicAuthenticationFilter.class);
logger.debug("*** apiSecurityFilterChain reached");
return http.cors(Customizer.withDefaults())
.authorizeHttpRequests(e -> e.requestMatchers("/api/**").authenticated().anyRequest().permitAll())
.exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())).build();
.authorizeHttpRequests(e -> e.requestMatchers("/api/**")
.authenticated()
.anyRequest()
.permitAll())
.exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.build();
}

@Bean
Expand All @@ -81,22 +85,24 @@ JWTProcessor<SecurityContext> jwtProcessor(JWTClaimsSetAwareJWSKeySelector<Secur
JwtDecoder jwtDecoder(JWTProcessor<SecurityContext> jwtProcessor, OAuth2TokenValidator<Jwt> jwtValidator) {
NimbusJwtDecoder decoder = new NimbusJwtDecoder(jwtProcessor);
OAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefault(),
jwtValidator);
jwtValidator);
decoder.setJwtValidator(validator);
return decoder;
}

private HttpSecurity setHeaders(HttpSecurity http) throws Exception {
return http.headers(headers -> headers
.contentSecurityPolicy(c -> c.policyDirectives(okrContentSecurityPolicy()))
.crossOriginEmbedderPolicy(c -> c.policy(REQUIRE_CORP))
.crossOriginOpenerPolicy(c -> c.policy(OPENER_SAME_ORIGIN))
.crossOriginResourcePolicy(c -> c.policy(RESOURCE_SAME_ORIGIN))
.addHeaderWriter(new StaticHeadersWriter("X-Permitted-Cross-Domain-Policies", "none"))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::deny)
.xssProtection(c -> c.headerValue(ENABLED_MODE_BLOCK))
.httpStrictTransportSecurity(c -> c.includeSubDomains(true).maxAgeInSeconds(31536000))
.referrerPolicy(c -> c.policy(NO_REFERRER)).permissionsPolicy(c -> c.policy(okrPermissionPolicy())));
return http.headers(headers -> headers.contentSecurityPolicy(c -> c.policyDirectives(okrContentSecurityPolicy()))
.crossOriginEmbedderPolicy(c -> c.policy(REQUIRE_CORP))
.crossOriginOpenerPolicy(c -> c.policy(OPENER_SAME_ORIGIN))
.crossOriginResourcePolicy(c -> c.policy(RESOURCE_SAME_ORIGIN))
.addHeaderWriter(new StaticHeadersWriter("X-Permitted-Cross-Domain-Policies",
"none"))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::deny)
.xssProtection(c -> c.headerValue(ENABLED_MODE_BLOCK))
.httpStrictTransportSecurity(c -> c.includeSubDomains(true)
.maxAgeInSeconds(31536000))
.referrerPolicy(c -> c.policy(NO_REFERRER))
.permissionsPolicy(c -> c.policy(okrPermissionPolicy())));
}

private String okrContentSecurityPolicy() {
Expand All @@ -115,18 +121,11 @@ private String okrContentSecurityPolicy() {
}

private String okrPermissionPolicy() {
return "accelerometer=(), ambient-light-sensor=(), autoplay=(), "
+ "battery=(), camera=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), "
+ "execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=(),"
+ " geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), "
+ "midi=(), navigation-override=(), payment=(), picture-in-picture=(),"
+ " publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(self), "
+ "usb=(), web-share=(), xr-spatial-tracking=()";
return "accelerometer=(), ambient-light-sensor=(), autoplay=(), " + "battery=(), camera=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), " + "execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=()," + " geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), " + "midi=(), navigation-override=(), payment=(), picture-in-picture=()," + " publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(self), " + "usb=(), web-share=(), xr-spatial-tracking=()";
}

@Bean
public AuthenticationEventPublisher authenticationEventPublisher(
ApplicationEventPublisher applicationEventPublisher) {
public AuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import ch.puzzle.okr.models.User;
import ch.puzzle.okr.multitenancy.TenantContext;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
Expand Down
7 changes: 4 additions & 3 deletions backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package ch.puzzle.okr;

import java.lang.reflect.Method;
import java.text.MessageFormat;

import ch.puzzle.okr.models.User;
import ch.puzzle.okr.multitenancy.TenantContext;
import org.springframework.cache.interceptor.KeyGenerator;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import org.springframework.cache.interceptor.KeyGenerator;

public class UserKeyGenerator implements KeyGenerator {
@Override
Expand Down
Loading
Loading