diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 99c1c92..b6569f8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -19,6 +19,8 @@ jobs: path: ~/.m2/repository key: maven-${{ hashFiles('pom.xml') }} restore-keys: maven- + - name: Check code formatting with Spotless + run: ./mvnw -B spotless:check - name: Check POMs against the Maven Central rules # Same PomChecker rules JReleaser applies during the release, run on every # PR so a POM that Maven Central would reject fails here instead of after diff --git a/spring-services-all/src/test/java/com/example/aggregate/AggregateApp.java b/spring-services-all/src/test/java/com/example/aggregate/AggregateApp.java index b5fa5e0..e363572 100644 --- a/spring-services-all/src/test/java/com/example/aggregate/AggregateApp.java +++ b/spring-services-all/src/test/java/com/example/aggregate/AggregateApp.java @@ -4,10 +4,10 @@ import org.springframework.boot.security.oauth2.server.resource.autoconfigure.OAuth2ResourceServerAutoConfiguration; /** - * A zero-config consumer application with the full reactor on the classpath - * ({@code spring-services-all}). It declares its own entity/repository ({@link Order}) and - * no {@code @Import}, {@code @EntityScan}, or {@code @EnableJpaRepositories} — every - * library module self-activates through its own auto-configuration. + * A zero-config consumer application with the full reactor on the classpath ({@code + * spring-services-all}). It declares its own entity/repository ({@link Order}) and + * no {@code @Import}, {@code @EntityScan}, or {@code @EnableJpaRepositories} — + * every library module self-activates through its own auto-configuration. */ @SpringBootApplication(exclude = OAuth2ResourceServerAutoConfiguration.class) public class AggregateApp {} diff --git a/spring-services-all/src/test/java/com/example/aggregate/AggregateStarterIntegrationTest.java b/spring-services-all/src/test/java/com/example/aggregate/AggregateStarterIntegrationTest.java index 0613375..bfddcb6 100644 --- a/spring-services-all/src/test/java/com/example/aggregate/AggregateStarterIntegrationTest.java +++ b/spring-services-all/src/test/java/com/example/aggregate/AggregateStarterIntegrationTest.java @@ -26,18 +26,18 @@ /** * Aggregate / zero-config starter integration test (spec 013 gate 1, relocated here per spec 014). * - *

Boots {@link AggregateApp} — a zero-config consumer with the full reactor - * ({@code spring-services-all}) on the classpath — and asserts that: + *

Boots {@link AggregateApp} — a zero-config consumer with the full reactor ({@code + * spring-services-all}) on the classpath — and asserts that: * *

*/ @SpringBootTest(classes = AggregateApp.class) diff --git a/spring-services-all/src/test/java/com/example/aggregate/AggregateTestConfig.java b/spring-services-all/src/test/java/com/example/aggregate/AggregateTestConfig.java index 85f484a..1dac2c7 100644 --- a/spring-services-all/src/test/java/com/example/aggregate/AggregateTestConfig.java +++ b/spring-services-all/src/test/java/com/example/aggregate/AggregateTestConfig.java @@ -7,9 +7,9 @@ import org.testcontainers.postgresql.PostgreSQLContainer; /** - * Test infrastructure for the aggregate context: a PostgreSQL Testcontainer and a stub - * {@link JwtDecoder} required by the core JWT security chain (the aggregate test does not exercise - * real JWT validation). + * Test infrastructure for the aggregate context: a PostgreSQL Testcontainer and a stub {@link + * JwtDecoder} required by the core JWT security chain (the aggregate test does not exercise real + * JWT validation). */ @TestConfiguration(proxyBeanMethods = false) public class AggregateTestConfig { diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/altcha/AltchaAutoConfiguration.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/altcha/AltchaAutoConfiguration.java index b9c5f39..0883673 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/altcha/AltchaAutoConfiguration.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/altcha/AltchaAutoConfiguration.java @@ -30,15 +30,15 @@ /** * Auto-configuration for the optional ALTCHA bot protection. * - *

Registered through this module's - * {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, but gated on - * {@code openelements.altcha.enabled=true} rather than on classpath presence: the module cannot work - * without a signing secret, and self-activation would fail the start-up of every application that - * consumes {@code spring-services-all} without configuring one. + *

Registered through this module's {@code + * META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, but gated on + * {@code openelements.altcha.enabled=true} rather than on classpath presence: the module cannot + * work without a signing secret, and self-activation would fail the start-up of every application + * that consumes {@code spring-services-all} without configuring one. * - *

Every bean is guarded by {@link ConditionalOnMissingBean}, so an application replaces a part — most - * likely the {@link ReplayStore} when it runs several instances — by declaring its own bean. The beans - * live on the auto-configuration itself, as in {@code StorageAutoConfiguration}, because + *

Every bean is guarded by {@link ConditionalOnMissingBean}, so an application replaces a part — + * most likely the {@link ReplayStore} when it runs several instances — by declaring its own bean. + * The beans live on the auto-configuration itself, as in {@code StorageAutoConfiguration}, because * {@code @ConditionalOnMissingBean} is only reliable while auto-configurations are being processed. * *

Runs after the auto-configurations that enable Spring Security, so that the module's filter @@ -52,89 +52,92 @@ @EnableConfigurationProperties(AltchaProperties.class) public class AltchaAutoConfiguration { - /** Creates the auto-configuration. */ - public AltchaAutoConfiguration() { - } + /** Creates the auto-configuration. */ + public AltchaAutoConfiguration() {} + + /** + * Remembers used challenges on the heap; correct for a single instance only. + * + * @return the store + */ + @Bean + @ConditionalOnMissingBean + public ReplayStore altchaReplayStore() { + return new InMemoryReplayStore(); + } + + /** + * Creates and verifies challenges. + * + * @param properties the configuration + * @param replayStore the store that remembers used challenges + * @return the verifier + */ + @Bean + @ConditionalOnMissingBean + public AltchaVerifier altchaVerifier( + final AltchaProperties properties, final ReplayStore replayStore) { + return new AltchaVerifier(properties, replayStore); + } + + /** + * The API for the application's endpoints. + * + * @param verifier the verifier + * @return the service + */ + @Bean + @ConditionalOnMissingBean + public AltchaService altchaService(final AltchaVerifier verifier) { + return new AltchaService(verifier); + } + + /** The web part: the challenge endpoint, its security filter chain and the error response. */ + @Configuration(proxyBeanMethods = false) + @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) + static class Web { - /** - * Remembers used challenges on the heap; correct for a single instance only. - * - * @return the store - */ @Bean @ConditionalOnMissingBean - public ReplayStore altchaReplayStore() { - return new InMemoryReplayStore(); + AltchaChallengeController altchaChallengeController(final AltchaService service) { + return new AltchaChallengeController(service); } /** - * Creates and verifies challenges. - * - * @param properties the configuration - * @param replayStore the store that remembers used challenges - * @return the verifier + * The error response. The {@link ProblemFactory} is passed as a provider rather than injected: + * it does not exist while {@code openelements.problem-details.enabled=false}, and that is + * exactly the case in which this handler must answer with the module's previous body. */ @Bean @ConditionalOnMissingBean - public AltchaVerifier altchaVerifier(final AltchaProperties properties, final ReplayStore replayStore) { - return new AltchaVerifier(properties, replayStore); + AltchaExceptionHandler altchaExceptionHandler( + final ObjectProvider problemFactory) { + return new AltchaExceptionHandler(problemFactory); } /** - * The API for the application's endpoints. - * - * @param verifier the verifier - * @return the service + * Permits anonymous {@code GET} on the challenge path and nothing else on it. Ordered ahead of + * the default JWT chain, which has no matcher and would otherwise demand a token from the + * visitor of a public form. The chain matches only this one path, so it cannot open anything + * else. */ @Bean - @ConditionalOnMissingBean - public AltchaService altchaService(final AltchaVerifier verifier) { - return new AltchaService(verifier); - } - - /** The web part: the challenge endpoint, its security filter chain and the error response. */ - @Configuration(proxyBeanMethods = false) - @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) - static class Web { - - @Bean - @ConditionalOnMissingBean - AltchaChallengeController altchaChallengeController(final AltchaService service) { - return new AltchaChallengeController(service); - } - - /** - * The error response. The {@link ProblemFactory} is passed as a provider rather than injected: - * it does not exist while {@code openelements.problem-details.enabled=false}, and that is - * exactly the case in which this handler must answer with the module's previous body. - */ - @Bean - @ConditionalOnMissingBean - AltchaExceptionHandler altchaExceptionHandler( - final ObjectProvider problemFactory) { - return new AltchaExceptionHandler(problemFactory); - } - - /** - * Permits anonymous {@code GET} on the challenge path and nothing else on it. Ordered ahead of - * the default JWT chain, which has no matcher and would otherwise demand a token from the - * visitor of a public form. The chain matches only this one path, so it cannot open anything - * else. - */ - @Bean - @Order(0) - @ConditionalOnClass(HttpSecurity.class) - @ConditionalOnBean(HttpSecurity.class) - @ConditionalOnMissingBean(name = "altchaSecurityFilterChain") - SecurityFilterChain altchaSecurityFilterChain(final HttpSecurity http, final AltchaProperties properties) - throws Exception { - http.securityMatcher(properties.challengePath()) - .authorizeHttpRequests(auth -> auth - .requestMatchers(HttpMethod.GET, properties.challengePath()).permitAll() - .anyRequest().denyAll()) - .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .csrf(csrf -> csrf.disable()); - return http.build(); - } + @Order(0) + @ConditionalOnClass(HttpSecurity.class) + @ConditionalOnBean(HttpSecurity.class) + @ConditionalOnMissingBean(name = "altchaSecurityFilterChain") + SecurityFilterChain altchaSecurityFilterChain( + final HttpSecurity http, final AltchaProperties properties) throws Exception { + http.securityMatcher(properties.challengePath()) + .authorizeHttpRequests( + auth -> + auth.requestMatchers(HttpMethod.GET, properties.challengePath()) + .permitAll() + .anyRequest() + .denyAll()) + .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .csrf(csrf -> csrf.disable()); + return http.build(); } + } } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/altcha/package-info.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/altcha/package-info.java index 0717a02..22c6245 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/altcha/package-info.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/altcha/package-info.java @@ -1,5 +1,6 @@ /** - * Null-marked package (JSpecify): every type is non-null unless annotated {@link org.jspecify.annotations.Nullable}. + * Null-marked package (JSpecify): every type is non-null unless annotated {@link + * org.jspecify.annotations.Nullable}. */ @NullMarked package com.openelements.spring.base.altcha; diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaChallengeController.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaChallengeController.java index f93b552..b0a5818 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaChallengeController.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaChallengeController.java @@ -17,25 +17,29 @@ @RestController public class AltchaChallengeController { - private final AltchaService service; + private final AltchaService service; - /** - * Creates the controller. - * - * @param service the service that creates the challenges - */ - public AltchaChallengeController(final AltchaService service) { - this.service = Objects.requireNonNull(service, "service must not be null"); - } + /** + * Creates the controller. + * + * @param service the service that creates the challenges + */ + public AltchaChallengeController(final AltchaService service) { + this.service = Objects.requireNonNull(service, "service must not be null"); + } - /** - * Creates a challenge. It is never cached, since each one can be used once. - * - * @return the challenge as JSON - */ - @GetMapping(value = "${openelements.altcha.challenge-path:" + AltchaProperties.DEFAULT_CHALLENGE_PATH + "}", - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity challenge() { - return ResponseEntity.ok().header(HttpHeaders.CACHE_CONTROL, "no-store").body(service.createChallenge()); - } + /** + * Creates a challenge. It is never cached, since each one can be used once. + * + * @return the challenge as JSON + */ + @GetMapping( + value = + "${openelements.altcha.challenge-path:" + AltchaProperties.DEFAULT_CHALLENGE_PATH + "}", + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity challenge() { + return ResponseEntity.ok() + .header(HttpHeaders.CACHE_CONTROL, "no-store") + .body(service.createChallenge()); + } } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaExceptionHandler.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaExceptionHandler.java index ed2cbdd..e417e00 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaExceptionHandler.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaExceptionHandler.java @@ -14,9 +14,9 @@ /** * Answers a failed bot check. * - *

With RFC 9457 problem details enabled — the default — the response is a {@code 400} problem of the - * matching {@link AltchaProblemType}, carrying the visitor's message in the language of the request as - * {@code detail}: + *

With RFC 9457 problem details enabled — the default — the response is a {@code 400} problem of + * the matching {@link AltchaProblemType}, carrying the visitor's message in the language of the + * request as {@code detail}: * *

{@code
  * {
@@ -29,47 +29,48 @@
  * }
  * }
* - *

With {@code openelements.problem-details.enabled=false} there is no {@link ProblemFactory} bean, and - * the handler answers {@code {"code": "altcha-expired", "message": …}} exactly as it did before. The - * stable identifier survives the switch either way: it is the {@code code} in the old body and the last - * segment of the {@code type} URI in the new one. + *

With {@code openelements.problem-details.enabled=false} there is no {@link ProblemFactory} + * bean, and the handler answers {@code {"code": "altcha-expired", "message": …}} exactly as it did + * before. The stable identifier survives the switch either way: it is the {@code code} in the old + * body and the last segment of the {@code type} URI in the new one. * - *

The advice applies to every controller, because the exception is thrown by the application's own - * endpoints. An application with another error format registers its own bean of this type and the library - * backs off. + *

The advice applies to every controller, because the exception is thrown by the application's + * own endpoints. An application with another error format registers its own bean of this type and + * the library backs off. */ @RestControllerAdvice public class AltchaExceptionHandler { - private final ObjectProvider problemFactory; + private final ObjectProvider problemFactory; - /** - * Creates the handler. - * - * @param problemFactory provider for the optional {@link ProblemFactory} bean; absent while - * {@code openelements.problem-details.enabled=false} - */ - public AltchaExceptionHandler(final ObjectProvider problemFactory) { - this.problemFactory = Objects.requireNonNull(problemFactory, "problemFactory must not be null"); - } + /** + * Creates the handler. + * + * @param problemFactory provider for the optional {@link ProblemFactory} bean; absent while + * {@code openelements.problem-details.enabled=false} + */ + public AltchaExceptionHandler(final ObjectProvider problemFactory) { + this.problemFactory = Objects.requireNonNull(problemFactory, "problemFactory must not be null"); + } - /** - * Renders the failed check. - * - * @param e the failed check - * @param request the request being handled, for {@code instance} and {@code traceId} - * @return status 400, as an RFC 9457 problem or — without problem details — as the previous - * {@code {code, message}} body - */ - @ExceptionHandler(AltchaVerificationException.class) - public ResponseEntity handle(final AltchaVerificationException e, final HttpServletRequest request) { - final ProblemFactory factory = problemFactory.getIfAvailable(); - if (factory == null) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body(Map.of("code", e.code(), "message", String.valueOf(e.getMessage()))); - } - final ProblemDetail problem = factory.create(AltchaProblemType.forResult(e.result()), - e.getMessage(), request); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(problem); + /** + * Renders the failed check. + * + * @param e the failed check + * @param request the request being handled, for {@code instance} and {@code traceId} + * @return status 400, as an RFC 9457 problem or — without problem details — as the previous + * {@code {code, message}} body + */ + @ExceptionHandler(AltchaVerificationException.class) + public ResponseEntity handle( + final AltchaVerificationException e, final HttpServletRequest request) { + final ProblemFactory factory = problemFactory.getIfAvailable(); + if (factory == null) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(Map.of("code", e.code(), "message", String.valueOf(e.getMessage()))); } + final ProblemDetail problem = + factory.create(AltchaProblemType.forResult(e.result()), e.getMessage(), request); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(problem); + } } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaProblemType.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaProblemType.java index 6855411..4896046 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaProblemType.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaProblemType.java @@ -7,68 +7,67 @@ /** * The problem types of a failed bot check. * - *

They live in this module rather than in {@code spring-services-core}'s - * {@link com.openelements.spring.base.problem.StandardProblemType}, so core knows no slug of an optional - * module. The slugs are the ones the module published as {@code code} before RFC 9457 problems existed, so a - * client that branched on {@code "altcha-expired"} now finds the same word at the end of the {@code type} - * URI. + *

They live in this module rather than in {@code spring-services-core}'s {@link + * com.openelements.spring.base.problem.StandardProblemType}, so core knows no slug of an optional + * module. The slugs are the ones the module published as {@code code} before RFC 9457 problems + * existed, so a client that branched on {@code "altcha-expired"} now finds the same word at the end + * of the {@code type} URI. * - *

All four are {@code 400}: a failed proof of work is a defect of the request, not of the visitor's - * authorisation. The title describes the type in English; the occurrence-specific text goes into - * {@code detail} and is localised, from the request's {@code Accept-Language}. + *

All four are {@code 400}: a failed proof of work is a defect of the request, not of the + * visitor's authorisation. The title describes the type in English; the occurrence-specific text + * goes into {@code detail} and is localised, from the request's {@code Accept-Language}. */ public enum AltchaProblemType implements ProblemType { - /** No payload: the widget did not run, or the form field is missing. */ - MISSING("altcha-missing", "Bot check missing"), + /** No payload: the widget did not run, or the form field is missing. */ + MISSING("altcha-missing", "Bot check missing"), - /** Not parseable, wrong signature, or wrong solution. */ - INVALID("altcha-invalid", "Bot check invalid"), + /** Not parseable, wrong signature, or wrong solution. */ + INVALID("altcha-invalid", "Bot check invalid"), - /** The challenge has expired. */ - EXPIRED("altcha-expired", "Bot check expired"), + /** The challenge has expired. */ + EXPIRED("altcha-expired", "Bot check expired"), - /** The challenge was already used. */ - REUSED("altcha-reused", "Bot check reused"); + /** The challenge was already used. */ + REUSED("altcha-reused", "Bot check reused"); - private final String slug; - private final String title; + private final String slug; + private final String title; - AltchaProblemType(final String slug, final String title) { - this.slug = slug; - this.title = title; - } + AltchaProblemType(final String slug, final String title) { + this.slug = slug; + this.title = title; + } - @Override - public String slug() { - return slug; - } + @Override + public String slug() { + return slug; + } - @Override - public HttpStatus status() { - return HttpStatus.BAD_REQUEST; - } + @Override + public HttpStatus status() { + return HttpStatus.BAD_REQUEST; + } - @Override - public String title() { - return title; - } + @Override + public String title() { + return title; + } - /** - * Returns the problem type for a failed verification. - * - * @param result the failed result - * @return the matching problem type - * @throws NullPointerException if {@code result} is {@code null} - * @throws IllegalArgumentException if {@code result} is - * {@link AltchaVerifier.VerificationResult#VERIFIED} — a success is - * not a problem - */ - public static AltchaProblemType forResult(final AltchaVerifier.VerificationResult result) { - Objects.requireNonNull(result, "result must not be null"); - if (result.verified()) { - throw new IllegalArgumentException("A verified result is no problem"); - } - return valueOf(result.name()); + /** + * Returns the problem type for a failed verification. + * + * @param result the failed result + * @return the matching problem type + * @throws NullPointerException if {@code result} is {@code null} + * @throws IllegalArgumentException if {@code result} is {@link + * AltchaVerifier.VerificationResult#VERIFIED} — a success is not a problem + */ + public static AltchaProblemType forResult(final AltchaVerifier.VerificationResult result) { + Objects.requireNonNull(result, "result must not be null"); + if (result.verified()) { + throw new IllegalArgumentException("A verified result is no problem"); } + return valueOf(result.name()); + } } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaProperties.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaProperties.java index 4b47562..1130ed8 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaProperties.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaProperties.java @@ -6,36 +6,39 @@ import org.springframework.boot.context.properties.bind.DefaultValue; /** - * Configuration of the ALTCHA bot protection, bound from the {@code openelements.altcha.*} namespace. + * Configuration of the ALTCHA bot protection, bound from the {@code openelements.altcha.*} + * namespace. * - *

ALTCHA protocol v2 (PBKDF2/SHA-256, matches the widget {@code altcha} 3.x): the browser searches - * a counter whose derived key starts with a given prefix. There is no {@code maxNumber} as in protocol - * v1; the difficulty is {@code cost × 16^keyPrefixLength} PBKDF2 iterations on average. + *

ALTCHA protocol v2 (PBKDF2/SHA-256, matches the widget {@code altcha} 3.x): the browser + * searches a counter whose derived key starts with a given prefix. There is no {@code maxNumber} as + * in protocol v1; the difficulty is {@code cost × 16^keyPrefixLength} PBKDF2 iterations on average. * - *

{@link #enabled()} defaults to {@code false}. The module needs a secret to sign challenges, and a - * module that self-activated on classpath presence would fail the start-up of every application that - * consumes {@code spring-services-all} without configuring one. + *

{@link #enabled()} defaults to {@code false}. The module needs a secret to sign challenges, + * and a module that self-activated on classpath presence would fail the start-up of every + * application that consumes {@code spring-services-all} without configuring one. * - * @param enabled whether the module is active - * @param hmacKey secret for signing the challenges, at least {@value #MIN_KEY_LENGTH} - * characters; required when the module is enabled, start-up fails without it - * @param expires how long a challenge can be solved and submitted - * @param cost PBKDF2 iterations per attempt + * @param enabled whether the module is active + * @param hmacKey secret for signing the challenges, at least {@value #MIN_KEY_LENGTH} characters; + * required when the module is enabled, start-up fails without it + * @param expires how long a challenge can be solved and submitted + * @param cost PBKDF2 iterations per attempt * @param keyPrefixLength length of the required key prefix in hex characters - * @param challengePath path of the endpoint that hands out challenges + * @param challengePath path of the endpoint that hands out challenges */ @ConfigurationProperties(prefix = "openelements.altcha") public record AltchaProperties( - @DefaultValue("false") boolean enabled, - @Nullable String hmacKey, - @DefaultValue("PT10M") Duration expires, - @DefaultValue("5000") int cost, - @DefaultValue("2") int keyPrefixLength, - @DefaultValue(AltchaProperties.DEFAULT_CHALLENGE_PATH) String challengePath) { + @DefaultValue("false") boolean enabled, + @Nullable String hmacKey, + @DefaultValue("PT10M") Duration expires, + @DefaultValue("5000") int cost, + @DefaultValue("2") int keyPrefixLength, + @DefaultValue(AltchaProperties.DEFAULT_CHALLENGE_PATH) String challengePath) { - /** The path of the challenge endpoint when {@code openelements.altcha.challenge-path} is unset. */ - public static final String DEFAULT_CHALLENGE_PATH = "/api/altcha/challenge"; + /** + * The path of the challenge endpoint when {@code openelements.altcha.challenge-path} is unset. + */ + public static final String DEFAULT_CHALLENGE_PATH = "/api/altcha/challenge"; - /** Minimum length of {@link #hmacKey()}. */ - public static final int MIN_KEY_LENGTH = 32; + /** Minimum length of {@link #hmacKey()}. */ + public static final int MIN_KEY_LENGTH = 32; } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaService.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaService.java index f1c873a..73ad1c2 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaService.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaService.java @@ -5,42 +5,43 @@ import org.springframework.context.i18n.LocaleContextHolder; /** - * Bot protection for endpoints that accept requests without authentication (forms): an endpoint calls - * {@link #requireVerified(String)} with the payload of the widget before it processes a request. + * Bot protection for endpoints that accept requests without authentication (forms): an endpoint + * calls {@link #requireVerified(String)} with the payload of the widget before it processes a + * request. */ public class AltchaService { - private final AltchaVerifier verifier; + private final AltchaVerifier verifier; - /** - * Creates the service. - * - * @param verifier the verifier that checks the payloads - */ - public AltchaService(final AltchaVerifier verifier) { - this.verifier = Objects.requireNonNull(verifier, "verifier must not be null"); - } + /** + * Creates the service. + * + * @param verifier the verifier that checks the payloads + */ + public AltchaService(final AltchaVerifier verifier) { + this.verifier = Objects.requireNonNull(verifier, "verifier must not be null"); + } - /** - * Verifies the payload of the widget (form field {@code altcha}) and marks the challenge as used. - * - * @param payload the Base64 payload, or {@code null} - * @throws AltchaVerificationException if the payload is missing, invalid, expired or was used - * before; the message is in the language of the current request - */ - public void requireVerified(final @Nullable String payload) { - final AltchaVerifier.VerificationResult result = verifier.verify(payload); - if (!result.verified()) { - throw new AltchaVerificationException(result, LocaleContextHolder.getLocale()); - } + /** + * Verifies the payload of the widget (form field {@code altcha}) and marks the challenge as used. + * + * @param payload the Base64 payload, or {@code null} + * @throws AltchaVerificationException if the payload is missing, invalid, expired or was used + * before; the message is in the language of the current request + */ + public void requireVerified(final @Nullable String payload) { + final AltchaVerifier.VerificationResult result = verifier.verify(payload); + if (!result.verified()) { + throw new AltchaVerificationException(result, LocaleContextHolder.getLocale()); } + } - /** - * Creates a new signed challenge. - * - * @return the challenge as JSON for the widget - */ - public String createChallenge() { - return verifier.createChallenge(); - } + /** + * Creates a new signed challenge. + * + * @return the challenge as JSON for the widget + */ + public String createChallenge() { + return verifier.createChallenge(); + } } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaVerificationException.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaVerificationException.java index 1988170..f49cda7 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaVerificationException.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaVerificationException.java @@ -7,66 +7,70 @@ import org.jspecify.annotations.Nullable; /** - * Thrown by {@link AltchaService#requireVerified(String)} if a request does not carry a valid ALTCHA - * solution. The module answers it with status 400 and {@code {"code": …, "message": …}} + * Thrown by {@link AltchaService#requireVerified(String)} if a request does not carry a valid + * ALTCHA solution. The module answers it with status 400 and {@code {"code": …, "message": …}} * ({@link AltchaExceptionHandler}). */ public class AltchaVerificationException extends RuntimeException { - private static final String BUNDLE = "com/openelements/spring/base/services/altcha/messages"; + private static final String BUNDLE = "com/openelements/spring/base/services/altcha/messages"; - /** - * The failed verification result. - */ - private final AltchaVerifier.VerificationResult result; + /** The failed verification result. */ + private final AltchaVerifier.VerificationResult result; - /** - * Creates the exception with a message for the visitor. - * - * @param result the failed verification result - * @param locale the language of the message; {@code null} means English - * @throws IllegalArgumentException if {@code result} is {@link AltchaVerifier.VerificationResult#VERIFIED} - */ - public AltchaVerificationException(final AltchaVerifier.VerificationResult result, - final @Nullable Locale locale) { - super(message(result, locale)); - this.result = result; - if (result.verified()) { - throw new IllegalArgumentException("A verified result is no failure"); - } + /** + * Creates the exception with a message for the visitor. + * + * @param result the failed verification result + * @param locale the language of the message; {@code null} means English + * @throws IllegalArgumentException if {@code result} is {@link + * AltchaVerifier.VerificationResult#VERIFIED} + */ + public AltchaVerificationException( + final AltchaVerifier.VerificationResult result, final @Nullable Locale locale) { + super(message(result, locale)); + this.result = result; + if (result.verified()) { + throw new IllegalArgumentException("A verified result is no failure"); } + } - /** - * Returns the failed verification result. - * - * @return the result - */ - public AltchaVerifier.VerificationResult result() { - return result; - } + /** + * Returns the failed verification result. + * + * @return the result + */ + public AltchaVerifier.VerificationResult result() { + return result; + } - /** - * Returns a stable code for clients, which does not change with the language of the message. - * - * @return the code, e.g. {@code altcha-missing} - */ - public String code() { - return "altcha-" + result.name().toLowerCase(Locale.ROOT); - } + /** + * Returns a stable code for clients, which does not change with the language of the message. + * + * @return the code, e.g. {@code altcha-missing} + */ + public String code() { + return "altcha-" + result.name().toLowerCase(Locale.ROOT); + } - /** - * Reads the message for the visitor from {@code messages*.properties} next to this class (English, - * German). Unknown languages get English, independent of the default locale of the JVM. - */ - static String message(final AltchaVerifier.VerificationResult result, final @Nullable Locale locale) { - Objects.requireNonNull(result, "result must not be null"); - final String key = result.name().toLowerCase(Locale.ROOT); - try { - final ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE, locale == null ? Locale.ENGLISH : locale, - ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_PROPERTIES)); - return bundle.getString(key); - } catch (final MissingResourceException e) { - return key; - } + /** + * Reads the message for the visitor from {@code messages*.properties} next to this class + * (English, German). Unknown languages get English, independent of the default locale of the JVM. + */ + static String message( + final AltchaVerifier.VerificationResult result, final @Nullable Locale locale) { + Objects.requireNonNull(result, "result must not be null"); + final String key = result.name().toLowerCase(Locale.ROOT); + try { + final ResourceBundle bundle = + ResourceBundle.getBundle( + BUNDLE, + locale == null ? Locale.ENGLISH : locale, + ResourceBundle.Control.getNoFallbackControl( + ResourceBundle.Control.FORMAT_PROPERTIES)); + return bundle.getString(key); + } catch (final MissingResourceException e) { + return key; } + } } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaVerifier.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaVerifier.java index e300d58..60647bb 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaVerifier.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/AltchaVerifier.java @@ -6,114 +6,123 @@ import org.jspecify.annotations.Nullable; /** - * Creates ALTCHA challenges and verifies the solutions sent by the widget: signature, expiry, solution - * and that the challenge was not used before. + * Creates ALTCHA challenges and verifies the solutions sent by the widget: signature, expiry, + * solution and that the challenge was not used before. * *

Endpoints use {@link AltchaService}, which turns a failed verification into an exception. This * class is the lower level for code that wants the {@link VerificationResult} itself. */ public class AltchaVerifier { - static final String ALGORITHM = "PBKDF2/SHA-256"; + static final String ALGORITHM = "PBKDF2/SHA-256"; - private final AltchaProperties properties; - private final String hmacKey; - private final ReplayStore replayStore; + private final AltchaProperties properties; + private final String hmacKey; + private final ReplayStore replayStore; - /** - * Creates the verifier. - * - * @param properties the configuration - * @param replayStore the store that remembers used challenges - * @throws IllegalStateException if no HMAC key of at least {@value AltchaProperties#MIN_KEY_LENGTH} - * characters is configured, so that start-up fails - */ - public AltchaVerifier(final AltchaProperties properties, final ReplayStore replayStore) { - this.properties = Objects.requireNonNull(properties, "properties must not be null"); - this.replayStore = Objects.requireNonNull(replayStore, "replayStore must not be null"); - final String key = properties.hmacKey(); - if (key == null || key.isBlank() || key.length() < AltchaProperties.MIN_KEY_LENGTH) { - throw new IllegalStateException("openelements.altcha.hmac-key must be set to a secret of at least " - + AltchaProperties.MIN_KEY_LENGTH + " characters (or remove openelements.altcha.enabled=true)"); - } - this.hmacKey = key; + /** + * Creates the verifier. + * + * @param properties the configuration + * @param replayStore the store that remembers used challenges + * @throws IllegalStateException if no HMAC key of at least {@value + * AltchaProperties#MIN_KEY_LENGTH} characters is configured, so that start-up fails + */ + public AltchaVerifier(final AltchaProperties properties, final ReplayStore replayStore) { + this.properties = Objects.requireNonNull(properties, "properties must not be null"); + this.replayStore = Objects.requireNonNull(replayStore, "replayStore must not be null"); + final String key = properties.hmacKey(); + if (key == null || key.isBlank() || key.length() < AltchaProperties.MIN_KEY_LENGTH) { + throw new IllegalStateException( + "openelements.altcha.hmac-key must be set to a secret of at least " + + AltchaProperties.MIN_KEY_LENGTH + + " characters (or remove openelements.altcha.enabled=true)"); } + this.hmacKey = key; + } - /** - * Creates a new signed challenge. - * - * @return the challenge as JSON for the widget - */ - public String createChallenge() { - try { - return Altcha.createChallenge(new Altcha.CreateChallengeOptions() - .algorithm(ALGORITHM) - .cost(properties.cost()) - .keyPrefixLength(properties.keyPrefixLength()) - .hmacSignatureSecret(hmacKey) - .expiresInSeconds(properties.expires().toSeconds())).toJson(); - } catch (final Exception e) { - throw new IllegalStateException("Can not create an ALTCHA challenge", e); - } + /** + * Creates a new signed challenge. + * + * @return the challenge as JSON for the widget + */ + public String createChallenge() { + try { + return Altcha.createChallenge( + new Altcha.CreateChallengeOptions() + .algorithm(ALGORITHM) + .cost(properties.cost()) + .keyPrefixLength(properties.keyPrefixLength()) + .hmacSignatureSecret(hmacKey) + .expiresInSeconds(properties.expires().toSeconds())) + .toJson(); + } catch (final Exception e) { + throw new IllegalStateException("Can not create an ALTCHA challenge", e); } + } - /** - * Verifies the payload of the widget (form field {@code altcha}). A verified challenge is marked as - * used. - * - * @param payload the Base64 payload, or {@code null} - * @return the result; never throws for invalid input - */ - public VerificationResult verify(final @Nullable String payload) { - if (payload == null || payload.isBlank()) { - return VerificationResult.MISSING; - } - final Altcha.Payload parsed; - final Altcha.VerifySolutionResult result; - try { - parsed = Altcha.parsePayload(payload.trim()); - result = Altcha.verifySolution(parsed.challenge(), parsed.solution(), hmacKey, Altcha.kdf(ALGORITHM)); - } catch (final Exception e) { - return VerificationResult.INVALID; - } - if (result.expired()) { - return VerificationResult.EXPIRED; - } - if (!result.verified()) { - return VerificationResult.INVALID; - } - final Number expiresAt = parsed.challenge().parameters().expiresAt(); - final Instant keepUntil = expiresAt != null ? Instant.ofEpochSecond(expiresAt.longValue()) - : Instant.now().plus(properties.expires()); - return replayStore.markUsed(parsed.challenge().signature(), keepUntil) ? VerificationResult.VERIFIED - : VerificationResult.REUSED; + /** + * Verifies the payload of the widget (form field {@code altcha}). A verified challenge is marked + * as used. + * + * @param payload the Base64 payload, or {@code null} + * @return the result; never throws for invalid input + */ + public VerificationResult verify(final @Nullable String payload) { + if (payload == null || payload.isBlank()) { + return VerificationResult.MISSING; + } + final Altcha.Payload parsed; + final Altcha.VerifySolutionResult result; + try { + parsed = Altcha.parsePayload(payload.trim()); + result = + Altcha.verifySolution( + parsed.challenge(), parsed.solution(), hmacKey, Altcha.kdf(ALGORITHM)); + } catch (final Exception e) { + return VerificationResult.INVALID; + } + if (result.expired()) { + return VerificationResult.EXPIRED; + } + if (!result.verified()) { + return VerificationResult.INVALID; } + final Number expiresAt = parsed.challenge().parameters().expiresAt(); + final Instant keepUntil = + expiresAt != null + ? Instant.ofEpochSecond(expiresAt.longValue()) + : Instant.now().plus(properties.expires()); + return replayStore.markUsed(parsed.challenge().signature(), keepUntil) + ? VerificationResult.VERIFIED + : VerificationResult.REUSED; + } - /** The outcome of {@link #verify(String)}. */ - public enum VerificationResult { + /** The outcome of {@link #verify(String)}. */ + public enum VerificationResult { - /** The payload carries a valid solution of an unused challenge. */ - VERIFIED, + /** The payload carries a valid solution of an unused challenge. */ + VERIFIED, - /** No payload: the widget did not run or the field is missing. */ - MISSING, + /** No payload: the widget did not run or the field is missing. */ + MISSING, - /** Not parseable, wrong signature or wrong solution. */ - INVALID, + /** Not parseable, wrong signature or wrong solution. */ + INVALID, - /** The challenge has expired. */ - EXPIRED, + /** The challenge has expired. */ + EXPIRED, - /** The challenge was already used. */ - REUSED; + /** The challenge was already used. */ + REUSED; - /** - * Returns whether this is the successful outcome. - * - * @return {@code true} for {@link #VERIFIED} - */ - public boolean verified() { - return this == VERIFIED; - } + /** + * Returns whether this is the successful outcome. + * + * @return {@code true} for {@link #VERIFIED} + */ + public boolean verified() { + return this == VERIFIED; } + } } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/InMemoryReplayStore.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/InMemoryReplayStore.java index 5120c95..0e3f351 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/InMemoryReplayStore.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/InMemoryReplayStore.java @@ -12,38 +12,38 @@ */ public final class InMemoryReplayStore implements ReplayStore { - private final Map used = new ConcurrentHashMap<>(); - private final Clock clock; + private final Map used = new ConcurrentHashMap<>(); + private final Clock clock; - /** Creates a store on the system clock. */ - public InMemoryReplayStore() { - this(Clock.systemUTC()); - } + /** Creates a store on the system clock. */ + public InMemoryReplayStore() { + this(Clock.systemUTC()); + } - /** - * Creates a store on the given clock. - * - * @param clock the clock that decides which entries have expired - */ - public InMemoryReplayStore(final Clock clock) { - this.clock = Objects.requireNonNull(clock, "clock must not be null"); - } + /** + * Creates a store on the given clock. + * + * @param clock the clock that decides which entries have expired + */ + public InMemoryReplayStore(final Clock clock) { + this.clock = Objects.requireNonNull(clock, "clock must not be null"); + } - @Override - public boolean markUsed(final String signature, final Instant expiresAt) { - Objects.requireNonNull(signature, "signature must not be null"); - Objects.requireNonNull(expiresAt, "expiresAt must not be null"); - final Instant now = clock.instant(); - used.values().removeIf(expiry -> expiry.isBefore(now)); - return used.putIfAbsent(signature, expiresAt) == null; - } + @Override + public boolean markUsed(final String signature, final Instant expiresAt) { + Objects.requireNonNull(signature, "signature must not be null"); + Objects.requireNonNull(expiresAt, "expiresAt must not be null"); + final Instant now = clock.instant(); + used.values().removeIf(expiry -> expiry.isBefore(now)); + return used.putIfAbsent(signature, expiresAt) == null; + } - /** - * Returns the number of remembered challenges. - * - * @return the number of remembered challenges - */ - public int size() { - return used.size(); - } + /** + * Returns the number of remembered challenges. + * + * @return the number of remembered challenges + */ + public int size() { + return used.size(); + } } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/ReplayStore.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/ReplayStore.java index 8cac8b1..a92b4fa 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/ReplayStore.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/ReplayStore.java @@ -11,13 +11,13 @@ */ public interface ReplayStore { - /** - * Marks a challenge as used. - * - * @param signature the signature of the challenge - * @param expiresAt until when the challenge must be remembered; after it, the challenge is rejected - * as expired anyway - * @return {@code true} if the challenge was not used before - */ - boolean markUsed(String signature, Instant expiresAt); + /** + * Marks a challenge as used. + * + * @param signature the signature of the challenge + * @param expiresAt until when the challenge must be remembered; after it, the challenge is + * rejected as expired anyway + * @return {@code true} if the challenge was not used before + */ + boolean markUsed(String signature, Instant expiresAt); } diff --git a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/package-info.java b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/package-info.java index e30394f..4de88bd 100644 --- a/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/package-info.java +++ b/spring-services-altcha/src/main/java/com/openelements/spring/base/services/altcha/package-info.java @@ -1,16 +1,16 @@ /** - * Bot protection for endpoints that accept requests without authentication, with - * ALTCHA: a self-hosted proof of work, without an external service + * Bot protection for endpoints that accept requests without authentication, with ALTCHA: a self-hosted proof of work, without an external service * and without cookies. * - *

The widget on the page fetches a signed challenge from - * {@link com.openelements.spring.base.services.altcha.AltchaChallengeController}, solves it in the - * browser and sends the solution with the form. The endpoint that receives the form calls - * {@link com.openelements.spring.base.services.altcha.AltchaService#requireVerified(String)}; a failed + *

The widget on the page fetches a signed challenge from {@link + * com.openelements.spring.base.services.altcha.AltchaChallengeController}, solves it in the browser + * and sends the solution with the form. The endpoint that receives the form calls {@link + * com.openelements.spring.base.services.altcha.AltchaService#requireVerified(String)}; a failed * check becomes a {@code 400} with a stable code and a message in the language of the request. * - *

Null-marked package (JSpecify): every type is non-null unless annotated - * {@link org.jspecify.annotations.Nullable}. + *

Null-marked package (JSpecify): every type is non-null unless annotated {@link + * org.jspecify.annotations.Nullable}. */ @NullMarked package com.openelements.spring.base.services.altcha; diff --git a/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaAutoConfigurationTest.java b/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaAutoConfigurationTest.java index 84f22e7..85fd09e 100644 --- a/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaAutoConfigurationTest.java +++ b/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaAutoConfigurationTest.java @@ -18,71 +18,89 @@ /** * Activation tests for {@link AltchaAutoConfiguration}. * - *

The module is opt-in, so the interesting behaviour is that nothing happens without - * {@code openelements.altcha.enabled=true} — in particular no start-up failure for a missing secret — - * and that an enabled module without a secret refuses to start. + *

The module is opt-in, so the interesting behaviour is that nothing happens without {@code + * openelements.altcha.enabled=true} — in particular no start-up failure for a missing secret — and + * that an enabled module without a secret refuses to start. */ @DisplayName("AltchaAutoConfiguration") class AltchaAutoConfigurationTest { - private static final String KEY = "auto-configuration-test-key-with-32-characters"; + private static final String KEY = "auto-configuration-test-key-with-32-characters"; - private final WebApplicationContextRunner runner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AltchaAutoConfiguration.class)); + private final WebApplicationContextRunner runner = + new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(AltchaAutoConfiguration.class)); - private final WebApplicationContextRunner enabled = runner.withPropertyValues( - "openelements.altcha.enabled=true", "openelements.altcha.hmac-key=" + KEY); + private final WebApplicationContextRunner enabled = + runner.withPropertyValues( + "openelements.altcha.enabled=true", "openelements.altcha.hmac-key=" + KEY); - @Test - @DisplayName("Registers nothing and needs no secret while openelements.altcha.enabled is unset") - void inertByDefault() { - runner.run(context -> assertThat(context).hasNotFailed() + @Test + @DisplayName("Registers nothing and needs no secret while openelements.altcha.enabled is unset") + void inertByDefault() { + runner.run( + context -> + assertThat(context) + .hasNotFailed() .doesNotHaveBean(AltchaService.class) .doesNotHaveBean(AltchaChallengeController.class) .doesNotHaveBean(AltchaExceptionHandler.class)); - } + } - @Test - @DisplayName("Registers service, endpoint and error handler with defaults when enabled") - void activatesWhenEnabled() { - enabled.run(context -> { - assertThat(context).hasNotFailed() - .hasSingleBean(AltchaVerifier.class) - .hasSingleBean(AltchaService.class) - .hasSingleBean(AltchaChallengeController.class) - .hasSingleBean(AltchaExceptionHandler.class); - assertThat(context.getBean(ReplayStore.class)).isInstanceOf(InMemoryReplayStore.class); - final AltchaProperties properties = context.getBean(AltchaProperties.class); - assertThat(properties.challengePath()).isEqualTo(AltchaProperties.DEFAULT_CHALLENGE_PATH); - assertThat(properties.expires()).hasMinutes(10); + @Test + @DisplayName("Registers service, endpoint and error handler with defaults when enabled") + void activatesWhenEnabled() { + enabled.run( + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(AltchaVerifier.class) + .hasSingleBean(AltchaService.class) + .hasSingleBean(AltchaChallengeController.class) + .hasSingleBean(AltchaExceptionHandler.class); + assertThat(context.getBean(ReplayStore.class)).isInstanceOf(InMemoryReplayStore.class); + final AltchaProperties properties = context.getBean(AltchaProperties.class); + assertThat(properties.challengePath()).isEqualTo(AltchaProperties.DEFAULT_CHALLENGE_PATH); + assertThat(properties.expires()).hasMinutes(10); }); - } + } - @Test - @DisplayName("Fails start-up when enabled without openelements.altcha.hmac-key") - void doesNotStartWithoutHmacKey() { - runner.withPropertyValues("openelements.altcha.enabled=true") - .run(context -> assertThat(context).hasFailed() - .getFailure().rootCause().hasMessageContaining("openelements.altcha.hmac-key")); - } + @Test + @DisplayName("Fails start-up when enabled without openelements.altcha.hmac-key") + void doesNotStartWithoutHmacKey() { + runner + .withPropertyValues("openelements.altcha.enabled=true") + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .rootCause() + .hasMessageContaining("openelements.altcha.hmac-key")); + } - @Test - @DisplayName("Backs off for a ReplayStore of the application") - void usesAReplayStoreOfTheApplication() { - final ReplayStore shared = (signature, expiresAt) -> true; - enabled.withBean(ReplayStore.class, () -> shared).run(context -> - assertThat(context.getBean(ReplayStore.class)).isSameAs(shared)); - } + @Test + @DisplayName("Backs off for a ReplayStore of the application") + void usesAReplayStoreOfTheApplication() { + final ReplayStore shared = (signature, expiresAt) -> true; + enabled + .withBean(ReplayStore.class, () -> shared) + .run(context -> assertThat(context.getBean(ReplayStore.class)).isSameAs(shared)); + } - @Test - @DisplayName("Registers only the service outside a servlet web application") - void noWebPartOutsideAWebApplication() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AltchaAutoConfiguration.class)) - .withPropertyValues("openelements.altcha.enabled=true", "openelements.altcha.hmac-key=" + KEY) - .run(context -> assertThat(context).hasNotFailed() - .hasSingleBean(AltchaService.class) - .doesNotHaveBean(AltchaChallengeController.class) - .doesNotHaveBean(AltchaExceptionHandler.class)); - } + @Test + @DisplayName("Registers only the service outside a servlet web application") + void noWebPartOutsideAWebApplication() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(AltchaAutoConfiguration.class)) + .withPropertyValues( + "openelements.altcha.enabled=true", "openelements.altcha.hmac-key=" + KEY) + .run( + context -> + assertThat(context) + .hasNotFailed() + .hasSingleBean(AltchaService.class) + .doesNotHaveBean(AltchaChallengeController.class) + .doesNotHaveBean(AltchaExceptionHandler.class)); + } } diff --git a/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaProblemDetailsDisabledWebTest.java b/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaProblemDetailsDisabledWebTest.java index 69794c8..d8ccd63 100644 --- a/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaProblemDetailsDisabledWebTest.java +++ b/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaProblemDetailsDisabledWebTest.java @@ -27,68 +27,88 @@ * *

What is tested

* - *

That the escape hatch is a complete rollback for this module, not a partial one. An application - * that cannot migrate its clients to {@code type} URIs sets the property and must get back exactly what - * this module published before: status {@code 400}, {@code Content-Type: application/json}, and a body - * of precisely {@code code} and {@code message} — no {@code type}, no {@code traceId}, nothing extra for - * a strict client to trip over. + *

That the escape hatch is a complete rollback for this module, not a partial one. An + * application that cannot migrate its clients to {@code type} URIs sets the property and must get + * back exactly what this module published before: status {@code 400}, {@code Content-Type: + * application/json}, and a body of precisely {@code code} and {@code message} — no {@code type}, no + * {@code traceId}, nothing extra for a strict client to trip over. * - *

The localisation of {@code message} is asserted too, because that behaviour predates problem details - * and must survive the switch untouched. + *

The localisation of {@code message} is asserted too, because that behaviour predates problem + * details and must survive the switch untouched. * *

How it is tested

* - *

The same {@link WebApplicationContextRunner} set-up as {@link AltchaWebTest}, including - * {@link ProblemDetailsAutoConfiguration} — the property, not the absence of the auto-configuration, is - * what has to disable the feature. The application fixture is reused from {@link AltchaWebTest} so the - * two configurations are compared on identical ground. + *

The same {@link WebApplicationContextRunner} set-up as {@link AltchaWebTest}, including {@link + * ProblemDetailsAutoConfiguration} — the property, not the absence of the auto-configuration, is + * what has to disable the feature. The application fixture is reused from {@link AltchaWebTest} so + * the two configurations are compared on identical ground. */ @DisplayName("ALTCHA over HTTP without problem details") class AltchaProblemDetailsDisabledWebTest { - private final WebApplicationContextRunner runner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AltchaAutoConfiguration.class, SecurityAutoConfiguration.class, - ServletWebSecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - JacksonAutoConfiguration.class, ProblemDetailsAutoConfiguration.class, - TraceAutoConfiguration.class)) - .withUserConfiguration(AltchaWebTest.Application.class) - .withPropertyValues("openelements.altcha.enabled=true", - "openelements.altcha.hmac-key=web-test-altcha-key-with-at-least-32-characters", - "openelements.altcha.cost=1", "openelements.altcha.key-prefix-length=1", - "openelements.problem-details.enabled=false"); + private final WebApplicationContextRunner runner = + new WebApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + AltchaAutoConfiguration.class, + SecurityAutoConfiguration.class, + ServletWebSecurityAutoConfiguration.class, + WebMvcAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, + JacksonAutoConfiguration.class, + ProblemDetailsAutoConfiguration.class, + TraceAutoConfiguration.class)) + .withUserConfiguration(AltchaWebTest.Application.class) + .withPropertyValues( + "openelements.altcha.enabled=true", + "openelements.altcha.hmac-key=web-test-altcha-key-with-at-least-32-characters", + "openelements.altcha.cost=1", + "openelements.altcha.key-prefix-length=1", + "openelements.problem-details.enabled=false"); - @Test - @DisplayName("Answers with the previous {code, message} body and nothing else") - void answersWithThePreviousBody() { - runner.run(context -> { - final MockMvc mvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) context) - .apply(springSecurity()).build(); + @Test + @DisplayName("Answers with the previous {code, message} body and nothing else") + void answersWithThePreviousBody() { + runner.run( + context -> { + final MockMvc mvc = + MockMvcBuilders.webAppContextSetup((WebApplicationContext) context) + .apply(springSecurity()) + .build(); - mvc.perform(post("/api/form").header(HttpHeaders.ACCEPT_LANGUAGE, "de")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.code").value("altcha-missing")) - .andExpect(jsonPath("$.message").value( - org.hamcrest.Matchers.startsWith("Die Prüfung gegen automatisierte Anfragen fehlt."))) - .andExpect(jsonPath("$.type").doesNotExist()) - .andExpect(jsonPath("$.title").doesNotExist()) - .andExpect(jsonPath("$.status").doesNotExist()) - .andExpect(jsonPath("$.traceId").doesNotExist()); + mvc.perform(post("/api/form").header(HttpHeaders.ACCEPT_LANGUAGE, "de")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.code").value("altcha-missing")) + .andExpect( + jsonPath("$.message") + .value( + org.hamcrest.Matchers.startsWith( + "Die Prüfung gegen automatisierte Anfragen fehlt."))) + .andExpect(jsonPath("$.type").doesNotExist()) + .andExpect(jsonPath("$.title").doesNotExist()) + .andExpect(jsonPath("$.status").doesNotExist()) + .andExpect(jsonPath("$.traceId").doesNotExist()); }); - } + } - @Test - @DisplayName("Keeps the English message for a request in another language") - void keepsTheEnglishFallback() { - runner.run(context -> { - final MockMvc mvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) context) - .apply(springSecurity()).build(); + @Test + @DisplayName("Keeps the English message for a request in another language") + void keepsTheEnglishFallback() { + runner.run( + context -> { + final MockMvc mvc = + MockMvcBuilders.webAppContextSetup((WebApplicationContext) context) + .apply(springSecurity()) + .build(); - mvc.perform(post("/api/form").header(HttpHeaders.ACCEPT_LANGUAGE, "en")) - .andExpect(jsonPath("$.code").value("altcha-missing")) - .andExpect(jsonPath("$.message").value( - org.hamcrest.Matchers.startsWith("The check against automated requests is missing."))); + mvc.perform(post("/api/form").header(HttpHeaders.ACCEPT_LANGUAGE, "en")) + .andExpect(jsonPath("$.code").value("altcha-missing")) + .andExpect( + jsonPath("$.message") + .value( + org.hamcrest.Matchers.startsWith( + "The check against automated requests is missing."))); }); - } + } } diff --git a/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaWebTest.java b/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaWebTest.java index a390574..c04aa8a 100644 --- a/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaWebTest.java +++ b/spring-services-altcha/src/test/java/com/openelements/spring/base/altcha/AltchaWebTest.java @@ -43,144 +43,170 @@ * situation the module's own chain exists for: without it the visitor of the form could not fetch a * challenge. * - *

RFC 9457 problem details are active, as they are by default in a real application, so the failure - * responses are problems. The slug a client branches on is unchanged from the {@code code} this module - * published before — it is now the last segment of the {@code type} URI. The opposite configuration is - * covered by {@link AltchaProblemDetailsDisabledWebTest}. + *

RFC 9457 problem details are active, as they are by default in a real application, so the + * failure responses are problems. The slug a client branches on is unchanged from the {@code code} + * this module published before — it is now the last segment of the {@code type} URI. The opposite + * configuration is covered by {@link AltchaProblemDetailsDisabledWebTest}. */ @DisplayName("ALTCHA over HTTP") class AltchaWebTest { - private static final String CHALLENGE = "/api/altcha/challenge"; - - /** The default {@code openelements.problem-details.type-base}. */ - static final String TYPE_BASE = "https://open-elements.com/problems/spring-services/"; - - private final WebApplicationContextRunner runner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AltchaAutoConfiguration.class, SecurityAutoConfiguration.class, - ServletWebSecurityAutoConfiguration.class, - WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - JacksonAutoConfiguration.class, ProblemDetailsAutoConfiguration.class, - TraceAutoConfiguration.class)) - .withUserConfiguration(Application.class) - .withPropertyValues("openelements.altcha.enabled=true", - "openelements.altcha.hmac-key=web-test-altcha-key-with-at-least-32-characters", - "openelements.altcha.cost=1", "openelements.altcha.key-prefix-length=1"); - - @Test - @DisplayName("Hands out challenges without authentication and never lets them be cached") - void challengeIsPublic() { - run(mvc -> mvc.perform(get(CHALLENGE)) + private static final String CHALLENGE = "/api/altcha/challenge"; + + /** The default {@code openelements.problem-details.type-base}. */ + static final String TYPE_BASE = "https://open-elements.com/problems/spring-services/"; + + private final WebApplicationContextRunner runner = + new WebApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + AltchaAutoConfiguration.class, + SecurityAutoConfiguration.class, + ServletWebSecurityAutoConfiguration.class, + WebMvcAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, + JacksonAutoConfiguration.class, + ProblemDetailsAutoConfiguration.class, + TraceAutoConfiguration.class)) + .withUserConfiguration(Application.class) + .withPropertyValues( + "openelements.altcha.enabled=true", + "openelements.altcha.hmac-key=web-test-altcha-key-with-at-least-32-characters", + "openelements.altcha.cost=1", + "openelements.altcha.key-prefix-length=1"); + + @Test + @DisplayName("Hands out challenges without authentication and never lets them be cached") + void challengeIsPublic() { + run( + mvc -> + mvc.perform(get(CHALLENGE)) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store")) .andExpect(jsonPath("$.signature").isNotEmpty())); - } - - @Test - @DisplayName("Opens only GET on the challenge path and nothing else") - void opensNothingElse() { - run(mvc -> { - mvc.perform(post(CHALLENGE)).andExpect(status().isForbidden()); - mvc.perform(get("/api/anything")).andExpect(status().isForbidden()); + } + + @Test + @DisplayName("Opens only GET on the challenge path and nothing else") + void opensNothingElse() { + run( + mvc -> { + mvc.perform(post(CHALLENGE)).andExpect(status().isForbidden()); + mvc.perform(get("/api/anything")).andExpect(status().isForbidden()); }); - } - - @Test - @DisplayName("Accepts a form with a solved challenge once") - void acceptsASolvedChallengeOnce() { - run(mvc -> { - final String challenge = mvc.perform(get(CHALLENGE)).andReturn().getResponse().getContentAsString(); - final String payload = AltchaSolver.solve(challenge); - mvc.perform(post("/api/form").param("altcha", payload)).andExpect(status().isOk()); - mvc.perform(post("/api/form").param("altcha", payload)) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType("application/problem+json")) - .andExpect(jsonPath("$.type").value(TYPE_BASE + "altcha-reused")) - .andExpect(jsonPath("$.title").value("Bot check reused")) - .andExpect(jsonPath("$.status").value(400)) - .andExpect(jsonPath("$.code").doesNotExist()); + } + + @Test + @DisplayName("Accepts a form with a solved challenge once") + void acceptsASolvedChallengeOnce() { + run( + mvc -> { + final String challenge = + mvc.perform(get(CHALLENGE)).andReturn().getResponse().getContentAsString(); + final String payload = AltchaSolver.solve(challenge); + mvc.perform(post("/api/form").param("altcha", payload)).andExpect(status().isOk()); + mvc.perform(post("/api/form").param("altcha", payload)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType("application/problem+json")) + .andExpect(jsonPath("$.type").value(TYPE_BASE + "altcha-reused")) + .andExpect(jsonPath("$.title").value("Bot check reused")) + .andExpect(jsonPath("$.status").value(400)) + .andExpect(jsonPath("$.code").doesNotExist()); }); - } - - /** - * The title stays English because it describes the type and must not change from occurrence - * to occurrence (RFC 9457 §3.1.2); the visitor-facing sentence is the {@code detail}, and that one - * follows the request's language. - */ - @Test - @DisplayName("Answers a form without a solution with a 400 problem whose detail is in the request language") - void rejectsAFormWithoutSolution() { - run(mvc -> { - mvc.perform(post("/api/form").header(HttpHeaders.ACCEPT_LANGUAGE, "de")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType("application/problem+json")) - .andExpect(jsonPath("$.type").value(TYPE_BASE + "altcha-missing")) - .andExpect(jsonPath("$.title").value("Bot check missing")) - .andExpect(jsonPath("$.traceId").value(org.hamcrest.Matchers.matchesPattern("[0-9a-f]{32}"))) - .andExpect(jsonPath("$.detail").value( - org.hamcrest.Matchers.startsWith("Die Prüfung gegen automatisierte Anfragen fehlt."))); - mvc.perform(post("/api/form").header(HttpHeaders.ACCEPT_LANGUAGE, "en")) - .andExpect(jsonPath("$.title").value("Bot check missing")) - .andExpect(jsonPath("$.detail").value( - org.hamcrest.Matchers.startsWith("The check against automated requests is missing."))); + } + + /** + * The title stays English because it describes the type and must not change from + * occurrence to occurrence (RFC 9457 §3.1.2); the visitor-facing sentence is the {@code detail}, + * and that one follows the request's language. + */ + @Test + @DisplayName( + "Answers a form without a solution with a 400 problem whose detail is in the request language") + void rejectsAFormWithoutSolution() { + run( + mvc -> { + mvc.perform(post("/api/form").header(HttpHeaders.ACCEPT_LANGUAGE, "de")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType("application/problem+json")) + .andExpect(jsonPath("$.type").value(TYPE_BASE + "altcha-missing")) + .andExpect(jsonPath("$.title").value("Bot check missing")) + .andExpect( + jsonPath("$.traceId").value(org.hamcrest.Matchers.matchesPattern("[0-9a-f]{32}"))) + .andExpect( + jsonPath("$.detail") + .value( + org.hamcrest.Matchers.startsWith( + "Die Prüfung gegen automatisierte Anfragen fehlt."))); + mvc.perform(post("/api/form").header(HttpHeaders.ACCEPT_LANGUAGE, "en")) + .andExpect(jsonPath("$.title").value("Bot check missing")) + .andExpect( + jsonPath("$.detail") + .value( + org.hamcrest.Matchers.startsWith( + "The check against automated requests is missing."))); }); - } - - @Test - @DisplayName("Answers an unparseable solution with the altcha-invalid problem") - void rejectsAnInvalidSolution() { - run(mvc -> mvc.perform(post("/api/form").param("altcha", "not-a-payload")) + } + + @Test + @DisplayName("Answers an unparseable solution with the altcha-invalid problem") + void rejectsAnInvalidSolution() { + run( + mvc -> + mvc.perform(post("/api/form").param("altcha", "not-a-payload")) .andExpect(status().isBadRequest()) .andExpect(content().contentType("application/problem+json")) .andExpect(jsonPath("$.type").value(TYPE_BASE + "altcha-invalid")) .andExpect(jsonPath("$.title").value("Bot check invalid"))); - } - - private void run(final MvcAssertion assertion) { - runner.run(context -> { - final MockMvc mvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) context) - .apply(springSecurity()).build(); - assertion.accept(mvc); + } + + private void run(final MvcAssertion assertion) { + runner.run( + context -> { + final MockMvc mvc = + MockMvcBuilders.webAppContextSetup((WebApplicationContext) context) + .apply(springSecurity()) + .build(); + assertion.accept(mvc); }); + } + + @FunctionalInterface + private interface MvcAssertion { + void accept(MockMvc mvc) throws Exception; + } + + @Configuration(proxyBeanMethods = false) + static class Application { + + @Bean + @Order(2) + SecurityFilterChain defaultChain(final HttpSecurity http) throws Exception { + http.authorizeHttpRequests( + auth -> auth.requestMatchers("/api/form").permitAll().anyRequest().authenticated()) + .csrf(csrf -> csrf.disable()); + return http.build(); } - @FunctionalInterface - private interface MvcAssertion { - void accept(MockMvc mvc) throws Exception; + @Bean + FormController formController(final AltchaService altcha) { + return new FormController(altcha); } + } - @Configuration(proxyBeanMethods = false) - static class Application { - - @Bean - @Order(2) - SecurityFilterChain defaultChain(final HttpSecurity http) throws Exception { - http.authorizeHttpRequests(auth -> auth - .requestMatchers("/api/form").permitAll() - .anyRequest().authenticated()) - .csrf(csrf -> csrf.disable()); - return http.build(); - } - - @Bean - FormController formController(final AltchaService altcha) { - return new FormController(altcha); - } - } - - @RestController - static class FormController { + @RestController + static class FormController { - private final AltchaService altcha; + private final AltchaService altcha; - FormController(final AltchaService altcha) { - this.altcha = altcha; - } + FormController(final AltchaService altcha) { + this.altcha = altcha; + } - @PostMapping("/api/form") - String submit(@RequestParam(name = "altcha", required = false) final @Nullable String payload) { - altcha.requireVerified(payload); - return "ok"; - } + @PostMapping("/api/form") + String submit(@RequestParam(name = "altcha", required = false) final @Nullable String payload) { + altcha.requireVerified(payload); + return "ok"; } + } } diff --git a/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaProblemTypeTest.java b/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaProblemTypeTest.java index f24ddad..8760857 100644 --- a/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaProblemTypeTest.java +++ b/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaProblemTypeTest.java @@ -19,13 +19,13 @@ *

Two things: * *

* *

How it is tested

@@ -35,47 +35,51 @@ @DisplayName("AltchaProblemType") class AltchaProblemTypeTest { - @ParameterizedTest(name = "[{index}] {0} → {1}") - @CsvSource({ - "MISSING, altcha-missing, Bot check missing", - "INVALID, altcha-invalid, Bot check invalid", - "EXPIRED, altcha-expired, Bot check expired", - "REUSED, altcha-reused, Bot check reused", - }) - @DisplayName("Slug, status and title of each constant are frozen") - void constantsAreFrozen(final AltchaProblemType type, final String slug, final String title) { - assertThat(type.slug()).isEqualTo(slug); - assertThat(type.title()).isEqualTo(title); - assertThat(type.status()).isEqualTo(HttpStatus.BAD_REQUEST); - } + @ParameterizedTest(name = "[{index}] {0} → {1}") + @CsvSource({ + "MISSING, altcha-missing, Bot check missing", + "INVALID, altcha-invalid, Bot check invalid", + "EXPIRED, altcha-expired, Bot check expired", + "REUSED, altcha-reused, Bot check reused", + }) + @DisplayName("Slug, status and title of each constant are frozen") + void constantsAreFrozen(final AltchaProblemType type, final String slug, final String title) { + assertThat(type.slug()).isEqualTo(slug); + assertThat(type.title()).isEqualTo(title); + assertThat(type.status()).isEqualTo(HttpStatus.BAD_REQUEST); + } - @ParameterizedTest - @EnumSource(value = AltchaVerifier.VerificationResult.class, names = "VERIFIED", mode = EnumSource.Mode.EXCLUDE) - @DisplayName("The slug equals the code the module published before problem details") - void slugsMatchThePreviousCodes(final AltchaVerifier.VerificationResult result) { - final String previousCode = new AltchaVerificationException(result, null).code(); + @ParameterizedTest + @EnumSource( + value = AltchaVerifier.VerificationResult.class, + names = "VERIFIED", + mode = EnumSource.Mode.EXCLUDE) + @DisplayName("The slug equals the code the module published before problem details") + void slugsMatchThePreviousCodes(final AltchaVerifier.VerificationResult result) { + final String previousCode = new AltchaVerificationException(result, null).code(); - assertThat(AltchaProblemType.forResult(result).slug()).isEqualTo(previousCode); - } + assertThat(AltchaProblemType.forResult(result).slug()).isEqualTo(previousCode); + } - @ParameterizedTest - @EnumSource(AltchaProblemType.class) - @DisplayName("Every constant satisfies the ProblemType contract") - void everyConstantIsValid(final AltchaProblemType type) { - ProblemType.validate(type); - } + @ParameterizedTest + @EnumSource(AltchaProblemType.class) + @DisplayName("Every constant satisfies the ProblemType contract") + void everyConstantIsValid(final AltchaProblemType type) { + ProblemType.validate(type); + } - @Test - @DisplayName("A verified result is not a problem") - void verifiedResultIsRejected() { - assertThatThrownBy(() -> AltchaProblemType.forResult(AltchaVerifier.VerificationResult.VERIFIED)) - .isInstanceOf(IllegalArgumentException.class); - } + @Test + @DisplayName("A verified result is not a problem") + void verifiedResultIsRejected() { + assertThatThrownBy( + () -> AltchaProblemType.forResult(AltchaVerifier.VerificationResult.VERIFIED)) + .isInstanceOf(IllegalArgumentException.class); + } - @Test - @DisplayName("A null result is rejected") - void nullResultIsRejected() { - assertThatThrownBy(() -> AltchaProblemType.forResult(null)) - .isInstanceOf(NullPointerException.class); - } + @Test + @DisplayName("A null result is rejected") + void nullResultIsRejected() { + assertThatThrownBy(() -> AltchaProblemType.forResult(null)) + .isInstanceOf(NullPointerException.class); + } } diff --git a/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaServiceTest.java b/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaServiceTest.java index 5d425ae..255f5db 100644 --- a/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaServiceTest.java +++ b/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaServiceTest.java @@ -11,78 +11,90 @@ class AltchaServiceTest { - private static final String KEY = "unit-test-altcha-key-with-at-least-32-characters"; + private static final String KEY = "unit-test-altcha-key-with-at-least-32-characters"; - private final AltchaService service = new AltchaService( - new AltchaVerifier(AltchaVerifierTest.properties(KEY), new InMemoryReplayStore())); + private final AltchaService service = + new AltchaService( + new AltchaVerifier(AltchaVerifierTest.properties(KEY), new InMemoryReplayStore())); - @AfterEach - void resetLocale() { - LocaleContextHolder.resetLocaleContext(); - } + @AfterEach + void resetLocale() { + LocaleContextHolder.resetLocaleContext(); + } - @Test - void acceptsASolvedChallengeOnce() throws Exception { - final String payload = AltchaSolver.solve(service.createChallenge()); + @Test + void acceptsASolvedChallengeOnce() throws Exception { + final String payload = AltchaSolver.solve(service.createChallenge()); - assertThatCode(() -> service.requireVerified(payload)).doesNotThrowAnyException(); - assertThatThrownBy(() -> service.requireVerified(payload)) - .isInstanceOfSatisfying(AltchaVerificationException.class, e -> { - assertThat(e.result()).isEqualTo(AltchaVerifier.VerificationResult.REUSED); - assertThat(e.code()).isEqualTo("altcha-reused"); - }); - } + assertThatCode(() -> service.requireVerified(payload)).doesNotThrowAnyException(); + assertThatThrownBy(() -> service.requireVerified(payload)) + .isInstanceOfSatisfying( + AltchaVerificationException.class, + e -> { + assertThat(e.result()).isEqualTo(AltchaVerifier.VerificationResult.REUSED); + assertThat(e.code()).isEqualTo("altcha-reused"); + }); + } - @Test - void rejectsMissingAndInvalidPayloadsWithStableCodes() { - assertThatThrownBy(() -> service.requireVerified(null)) - .isInstanceOfSatisfying(AltchaVerificationException.class, - e -> assertThat(e.code()).isEqualTo("altcha-missing")); - assertThatThrownBy(() -> service.requireVerified("bm8gYWx0Y2hh")) - .isInstanceOfSatisfying(AltchaVerificationException.class, - e -> assertThat(e.code()).isEqualTo("altcha-invalid")); - } + @Test + void rejectsMissingAndInvalidPayloadsWithStableCodes() { + assertThatThrownBy(() -> service.requireVerified(null)) + .isInstanceOfSatisfying( + AltchaVerificationException.class, + e -> assertThat(e.code()).isEqualTo("altcha-missing")); + assertThatThrownBy(() -> service.requireVerified("bm8gYWx0Y2hh")) + .isInstanceOfSatisfying( + AltchaVerificationException.class, + e -> assertThat(e.code()).isEqualTo("altcha-invalid")); + } - @Test - void messagesFollowTheLanguageOfTheRequest() { - LocaleContextHolder.setLocale(Locale.GERMAN); - assertThatThrownBy(() -> service.requireVerified(null)) - .hasMessageStartingWith("Die Prüfung gegen automatisierte Anfragen fehlt."); + @Test + void messagesFollowTheLanguageOfTheRequest() { + LocaleContextHolder.setLocale(Locale.GERMAN); + assertThatThrownBy(() -> service.requireVerified(null)) + .hasMessageStartingWith("Die Prüfung gegen automatisierte Anfragen fehlt."); - LocaleContextHolder.setLocale(Locale.ENGLISH); - assertThatThrownBy(() -> service.requireVerified(null)) - .hasMessageStartingWith("The check against automated requests is missing."); - } + LocaleContextHolder.setLocale(Locale.ENGLISH); + assertThatThrownBy(() -> service.requireVerified(null)) + .hasMessageStartingWith("The check against automated requests is missing."); + } - @Test - void unknownLanguagesGetEnglishIndependentOfTheJvmDefault() { - final Locale before = Locale.getDefault(); - try { - Locale.setDefault(Locale.GERMANY); - assertThat(AltchaVerificationException.message(AltchaVerifier.VerificationResult.EXPIRED, - Locale.forLanguageTag("fr"))).startsWith("The check against automated requests has expired."); - } finally { - Locale.setDefault(before); - } + @Test + void unknownLanguagesGetEnglishIndependentOfTheJvmDefault() { + final Locale before = Locale.getDefault(); + try { + Locale.setDefault(Locale.GERMANY); + assertThat( + AltchaVerificationException.message( + AltchaVerifier.VerificationResult.EXPIRED, Locale.forLanguageTag("fr"))) + .startsWith("The check against automated requests has expired."); + } finally { + Locale.setDefault(before); } + } - @Test - void everyFailureHasAMessageInBothLanguages() { - for (AltchaVerifier.VerificationResult result : AltchaVerifier.VerificationResult.values()) { - if (result.verified()) { - continue; - } - for (Locale locale : new Locale[]{Locale.ENGLISH, Locale.GERMAN}) { - final String message = AltchaVerificationException.message(result, locale); - assertThat(message).as(result + " " + locale).isNotEqualTo(result.name().toLowerCase(Locale.ROOT)) - .endsWith("."); - } - } + @Test + void everyFailureHasAMessageInBothLanguages() { + for (AltchaVerifier.VerificationResult result : AltchaVerifier.VerificationResult.values()) { + if (result.verified()) { + continue; + } + for (Locale locale : new Locale[] {Locale.ENGLISH, Locale.GERMAN}) { + final String message = AltchaVerificationException.message(result, locale); + assertThat(message) + .as(result + " " + locale) + .isNotEqualTo(result.name().toLowerCase(Locale.ROOT)) + .endsWith("."); + } } + } - @Test - void aVerifiedResultIsNoFailure() { - assertThatThrownBy(() -> new AltchaVerificationException(AltchaVerifier.VerificationResult.VERIFIED, - Locale.ENGLISH)).isInstanceOf(IllegalArgumentException.class); - } + @Test + void aVerifiedResultIsNoFailure() { + assertThatThrownBy( + () -> + new AltchaVerificationException( + AltchaVerifier.VerificationResult.VERIFIED, Locale.ENGLISH)) + .isInstanceOf(IllegalArgumentException.class); + } } diff --git a/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaSolver.java b/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaSolver.java index ce54ece..1df5379 100644 --- a/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaSolver.java +++ b/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaSolver.java @@ -5,31 +5,44 @@ import org.altcha.altcha.v2.Altcha; /** - * Solves ALTCHA challenges like the widget does and encodes the payload of the form field {@code altcha}. + * Solves ALTCHA challenges like the widget does and encodes the payload of the form field {@code + * altcha}. */ public final class AltchaSolver { - private AltchaSolver() { - } + private AltchaSolver() {} - /** - * @param challengeJson the challenge as returned by {@code the challenge endpoint} - * @return the Base64 payload for the form field {@code altcha} - */ - public static String solve(final String challengeJson) throws Exception { - // parsePayload is the only public JSON parser of the library: wrap the challenge with a dummy solution - final Altcha.Challenge challenge = Altcha.parsePayload(base64("{\"challenge\":" + challengeJson - + ",\"solution\":{\"counter\":0,\"derivedKey\":\"00\"}}")).challenge(); - return solve(challenge); - } + /** + * @param challengeJson the challenge as returned by {@code the challenge endpoint} + * @return the Base64 payload for the form field {@code altcha} + */ + public static String solve(final String challengeJson) throws Exception { + // parsePayload is the only public JSON parser of the library: wrap the challenge with a dummy + // solution + final Altcha.Challenge challenge = + Altcha.parsePayload( + base64( + "{\"challenge\":" + + challengeJson + + ",\"solution\":{\"counter\":0,\"derivedKey\":\"00\"}}")) + .challenge(); + return solve(challenge); + } - public static String solve(final Altcha.Challenge challenge) throws Exception { - final Altcha.Solution solution = Altcha.solveChallenge(challenge, Altcha.kdf(challenge.parameters().algorithm())); - return base64("{\"challenge\":" + challenge.toJson() + ",\"solution\":{\"counter\":" + solution.counter() - + ",\"derivedKey\":\"" + solution.derivedKey() + "\"}}"); - } + public static String solve(final Altcha.Challenge challenge) throws Exception { + final Altcha.Solution solution = + Altcha.solveChallenge(challenge, Altcha.kdf(challenge.parameters().algorithm())); + return base64( + "{\"challenge\":" + + challenge.toJson() + + ",\"solution\":{\"counter\":" + + solution.counter() + + ",\"derivedKey\":\"" + + solution.derivedKey() + + "\"}}"); + } - private static String base64(final String json) { - return Base64.getEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8)); - } + private static String base64(final String json) { + return Base64.getEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8)); + } } diff --git a/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaVerifierTest.java b/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaVerifierTest.java index 31e49ab..9019e19 100644 --- a/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaVerifierTest.java +++ b/spring-services-altcha/src/test/java/com/openelements/spring/base/services/altcha/AltchaVerifierTest.java @@ -10,52 +10,66 @@ class AltchaVerifierTest { - private static final String KEY = "unit-test-altcha-key-with-at-least-32-characters"; + private static final String KEY = "unit-test-altcha-key-with-at-least-32-characters"; - private final AltchaVerifier verifier = new AltchaVerifier(properties(KEY), new InMemoryReplayStore()); + private final AltchaVerifier verifier = + new AltchaVerifier(properties(KEY), new InMemoryReplayStore()); - @Test - void acceptsASolvedChallengeOnce() throws Exception { - final String payload = AltchaSolver.solve(verifier.createChallenge()); - assertThat(verifier.verify(payload)).isEqualTo(AltchaVerifier.VerificationResult.VERIFIED); - assertThat(verifier.verify(payload)).isEqualTo(AltchaVerifier.VerificationResult.REUSED); - } + @Test + void acceptsASolvedChallengeOnce() throws Exception { + final String payload = AltchaSolver.solve(verifier.createChallenge()); + assertThat(verifier.verify(payload)).isEqualTo(AltchaVerifier.VerificationResult.VERIFIED); + assertThat(verifier.verify(payload)).isEqualTo(AltchaVerifier.VerificationResult.REUSED); + } - @Test - void rejectsMissingInvalidForeignAndExpiredPayloads() throws Exception { - assertThat(verifier.verify(null)).isEqualTo(AltchaVerifier.VerificationResult.MISSING); - assertThat(verifier.verify(" ")).isEqualTo(AltchaVerifier.VerificationResult.MISSING); - assertThat(verifier.verify("bm8gYWx0Y2hh")).isEqualTo(AltchaVerifier.VerificationResult.INVALID); - assertThat(verifier.verify(AltchaSolver.solve(challenge("another-key-with-at-least-32-characters-x", - Instant.now().plusSeconds(60))))).isEqualTo(AltchaVerifier.VerificationResult.INVALID); - assertThat(verifier.verify(AltchaSolver.solve(challenge(KEY, Instant.now().minusSeconds(60))))) - .isEqualTo(AltchaVerifier.VerificationResult.EXPIRED); - } + @Test + void rejectsMissingInvalidForeignAndExpiredPayloads() throws Exception { + assertThat(verifier.verify(null)).isEqualTo(AltchaVerifier.VerificationResult.MISSING); + assertThat(verifier.verify(" ")).isEqualTo(AltchaVerifier.VerificationResult.MISSING); + assertThat(verifier.verify("bm8gYWx0Y2hh")) + .isEqualTo(AltchaVerifier.VerificationResult.INVALID); + assertThat( + verifier.verify( + AltchaSolver.solve( + challenge( + "another-key-with-at-least-32-characters-x", + Instant.now().plusSeconds(60))))) + .isEqualTo(AltchaVerifier.VerificationResult.INVALID); + assertThat(verifier.verify(AltchaSolver.solve(challenge(KEY, Instant.now().minusSeconds(60))))) + .isEqualTo(AltchaVerifier.VerificationResult.EXPIRED); + } - @Test - void requiresAnHmacKey() { - for (String key : new String[]{null, " ", "too-short"}) { - assertThatThrownBy(() -> new AltchaVerifier(properties(key), new InMemoryReplayStore())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("openelements.altcha.hmac-key"); - } + @Test + void requiresAnHmacKey() { + for (String key : new String[] {null, " ", "too-short"}) { + assertThatThrownBy(() -> new AltchaVerifier(properties(key), new InMemoryReplayStore())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("openelements.altcha.hmac-key"); } + } - @Test - void replayStoreForgetsExpiredChallenges() { - final InMemoryReplayStore store = new InMemoryReplayStore(); - assertThat(store.markUsed("a", Instant.now().minusSeconds(1))).isTrue(); - assertThat(store.markUsed("b", Instant.now().plusSeconds(60))).isTrue(); - assertThat(store.size()).isEqualTo(1); - assertThat(store.markUsed("b", Instant.now().plusSeconds(60))).isFalse(); - } + @Test + void replayStoreForgetsExpiredChallenges() { + final InMemoryReplayStore store = new InMemoryReplayStore(); + assertThat(store.markUsed("a", Instant.now().minusSeconds(1))).isTrue(); + assertThat(store.markUsed("b", Instant.now().plusSeconds(60))).isTrue(); + assertThat(store.size()).isEqualTo(1); + assertThat(store.markUsed("b", Instant.now().plusSeconds(60))).isFalse(); + } - private static Altcha.Challenge challenge(final String key, final Instant expiresAt) throws Exception { - return Altcha.createChallenge(new Altcha.CreateChallengeOptions().algorithm("PBKDF2/SHA-256").cost(1) - .keyPrefixLength(1).hmacSignatureSecret(key).expiresAt(expiresAt.getEpochSecond())); - } + private static Altcha.Challenge challenge(final String key, final Instant expiresAt) + throws Exception { + return Altcha.createChallenge( + new Altcha.CreateChallengeOptions() + .algorithm("PBKDF2/SHA-256") + .cost(1) + .keyPrefixLength(1) + .hmacSignatureSecret(key) + .expiresAt(expiresAt.getEpochSecond())); + } - static AltchaProperties properties(final String key) { - return new AltchaProperties(true, key, Duration.ofMinutes(10), 1, 1, AltchaProperties.DEFAULT_CHALLENGE_PATH); - } + static AltchaProperties properties(final String key) { + return new AltchaProperties( + true, key, Duration.ofMinutes(10), 1, 1, AltchaProperties.DEFAULT_CHALLENGE_PATH); + } } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/FullSpringServiceConfig.java b/spring-services-core/src/main/java/com/openelements/spring/base/FullSpringServiceConfig.java index 76b964c..4e53c82 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/FullSpringServiceConfig.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/FullSpringServiceConfig.java @@ -34,23 +34,25 @@ *
  • {@link TagConfig} — taggable-entity support. *
  • {@link WebhookConfig} — outbound webhook subscriptions and dispatching. *
  • {@link AuditConfig} — Audit log of every data lifecycle event with user attribution. - *
  • {@link DataConfig} — generic data layer; contributes the database reachability check - * {@link com.openelements.spring.base.data.DbHealthService}. + *
  • {@link DataConfig} — generic data layer; contributes the database reachability check {@link + * com.openelements.spring.base.data.DbHealthService}. * */ @Import({ - SecurityConfig.class, - DataConfig.class, - ApiKeyConfig.class, - SettingsConfig.class, - TagConfig.class, - WebhookConfig.class, - AuditConfig.class, - CommentConfig.class, - TranslationConfig.class + SecurityConfig.class, + DataConfig.class, + ApiKeyConfig.class, + SettingsConfig.class, + TagConfig.class, + WebhookConfig.class, + AuditConfig.class, + CommentConfig.class, + TranslationConfig.class }) public class FullSpringServiceConfig { - /** Creates the aggregate configuration; all feature configurations are wired via {@code @Import}. */ + /** + * Creates the aggregate configuration; all feature configurations are wired via {@code @Import}. + */ public FullSpringServiceConfig() {} } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/SpringServicesCoreAutoConfiguration.java b/spring-services-core/src/main/java/com/openelements/spring/base/SpringServicesCoreAutoConfiguration.java index 8fbf65a..61194b7 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/SpringServicesCoreAutoConfiguration.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/SpringServicesCoreAutoConfiguration.java @@ -15,13 +15,13 @@ /** * Core auto-configuration that turns {@code spring-services-core} into a real Spring Boot starter. * - *

    Each optional feature module ({@code -slack}, {@code -search}, {@code -dbbackup}, {@code -email}, - * {@code -mcp}) ships its own {@code @AutoConfiguration} guarded by {@code @ConditionalOnClass}; this - * class configures only the always-present core features. + *

    Each optional feature module ({@code -slack}, {@code -search}, {@code -dbbackup}, {@code + * -email}, {@code -mcp}) ships its own {@code @AutoConfiguration} guarded by + * {@code @ConditionalOnClass}; this class configures only the always-present core features. * *

    Registered through {@code META-INF/spring/ - * org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so a consuming application only - * needs the dependency on the classpath — no {@code @Import}, {@code @EntityScan} or + * org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so a consuming application + * only needs the dependency on the classpath — no {@code @Import}, {@code @EntityScan} or * {@code @EnableJpaRepositories}. * *

    The configuration {@link Import}s {@link FullSpringServiceConfig} (the aggregate of every @@ -30,13 +30,13 @@ * {@code oe_spring_services} schema (see {@link com.openelements.spring.base.data.DbSchema}), they * never collide with the application's own tables. * - *

    Ordering is binding, not incidental. The additive-scan mechanism only works if - * the registrar has appended the library package before Hibernate's entity scan and Spring - * Data's repository registrar read {@link AutoConfigurationPackages}. Both readers are themselves - * auto-configuration-driven, and auto-configuration ordering is otherwise unspecified — therefore - * this class declares {@link AutoConfigureBefore @AutoConfigureBefore} against - * {@link HibernateJpaAutoConfiguration} and {@link DataJpaRepositoriesAutoConfiguration}. The - * guarantee is proven by an integration test, not assumed. + *

    Ordering is binding, not incidental. The additive-scan mechanism only works + * if the registrar has appended the library package before Hibernate's entity scan and + * Spring Data's repository registrar read {@link AutoConfigurationPackages}. Both readers are + * themselves auto-configuration-driven, and auto-configuration ordering is otherwise unspecified — + * therefore this class declares {@link AutoConfigureBefore @AutoConfigureBefore} against {@link + * HibernateJpaAutoConfiguration} and {@link DataJpaRepositoriesAutoConfiguration}. The guarantee is + * proven by an integration test, not assumed. * *

    {@link ConditionalOnClass @ConditionalOnClass(EntityManagerFactory.class)} keeps the starter * inert in an application that has no JPA on the classpath. @@ -53,9 +53,7 @@ @Import({FullSpringServiceConfig.class, SpringServicesCoreAutoConfiguration.PackageRegistrar.class}) public class SpringServicesCoreAutoConfiguration { - /** - * Creates the auto-configuration; all beans are contributed via the imported configurations. - */ + /** Creates the auto-configuration; all beans are contributed via the imported configurations. */ public SpringServicesCoreAutoConfiguration() {} /** Root package of the library — scanned for both entities and Spring Data repositories. */ @@ -66,10 +64,10 @@ public SpringServicesCoreAutoConfiguration() {} * Spring Data's repository scan (both default to {@code AutoConfigurationPackages}) cover the * application's package(s) and the library's. * - *

    Deliberately does not use {@code @EntityScan}: that would make - * {@code EntityScanPackages} non-empty and thereby suppress Boot's default scan of the - * application's own package. Appending to {@link AutoConfigurationPackages} keeps - * {@code EntityScanPackages} empty, so the union of application and library packages is scanned. + *

    Deliberately does not use {@code @EntityScan}: that would make {@code + * EntityScanPackages} non-empty and thereby suppress Boot's default scan of the application's own + * package. Appending to {@link AutoConfigurationPackages} keeps {@code EntityScanPackages} empty, + * so the union of application and library packages is scanned. */ static class PackageRegistrar implements ImportBeanDefinitionRegistrar { diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/data/DataConfig.java b/spring-services-core/src/main/java/com/openelements/spring/base/data/DataConfig.java index 7727ff8..a3168e2 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/data/DataConfig.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/data/DataConfig.java @@ -7,12 +7,12 @@ /** * Spring configuration for the generic data layer. * - *

    Most of this package consists of abstractions the application subclasses - * ({@link AbstractEntity}, {@link AbstractDbBackedDataService}) and therefore needs no bean - * registration. The only ready-to-use bean the package contributes is {@link DbHealthService}. + *

    Most of this package consists of abstractions the application subclasses ({@link + * AbstractEntity}, {@link AbstractDbBackedDataService}) and therefore needs no bean registration. + * The only ready-to-use bean the package contributes is {@link DbHealthService}. * - *

    The bean is declared explicitly rather than via {@code @ComponentScan} + {@code @Service}. - * A single bean does not justify a package scan, and an explicit {@code @Bean} method cannot be + *

    The bean is declared explicitly rather than via {@code @ComponentScan} + {@code @Service}. A + * single bean does not justify a package scan, and an explicit {@code @Bean} method cannot be * registered twice when a consumer both imports this configuration and scans the library package. */ @Configuration(proxyBeanMethods = false) diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/data/DbHealthService.java b/spring-services-core/src/main/java/com/openelements/spring/base/data/DbHealthService.java index db8ab28..b908083 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/data/DbHealthService.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/data/DbHealthService.java @@ -9,14 +9,14 @@ import org.slf4j.LoggerFactory; /** - * Answers the single question "is the database reachable right now?" for the {@link DataSource} - * the application is configured with. + * Answers the single question "is the database reachable right now?" for the {@link DataSource} the + * application is configured with. * - *

    The check is a real round-trip: it borrows a connection from the pool and executes a - * statement on it. That distinguishes it from merely inspecting the {@code DataSource} bean — - * an application that booted successfully can still have a dead database (network partition, - * exhausted pool, database restarted, credentials rotated), and a bean-level check would report - * healthy in all of those cases. + *

    The check is a real round-trip: it borrows a connection from the pool and executes a statement + * on it. That distinguishes it from merely inspecting the {@code DataSource} bean — an application + * that booted successfully can still have a dead database (network partition, exhausted pool, + * database restarted, credentials rotated), and a bean-level check would report healthy in all of + * those cases. * *

    Typical use is an application-owned health or readiness endpoint: * @@ -40,22 +40,22 @@ * } * *

    The library deliberately ships no endpoint and no status enum of its own: HTTP path, - * authorization, response shape and the vocabulary used for "up" and "down" are the - * application's decisions. This service only supplies the fact. + * authorization, response shape and the vocabulary used for "up" and "down" are the application's + * decisions. This service only supplies the fact. * *

    The returned value is a point-in-time observation and is never cached — every call issues a * new round-trip. Callers that poll frequently (Kubernetes probes, uptime monitors) should - * therefore be aware that each call occupies a pooled connection for the duration of the query, - * and that a saturated pool makes the call block for up to the pool's connection timeout. + * therefore be aware that each call occupies a pooled connection for the duration of the query, and + * that a saturated pool makes the call block for up to the pool's connection timeout. */ public class DbHealthService { private static final Logger LOG = LoggerFactory.getLogger(DbHealthService.class); /** - * The cheapest round-trip that proves a borrowed connection can actually execute a statement: - * it touches no table, takes no lock, and is accepted by every database this library is used - * with (PostgreSQL in production, H2 in tests). + * The cheapest round-trip that proves a borrowed connection can actually execute a statement: it + * touches no table, takes no lock, and is accepted by every database this library is used with + * (PostgreSQL in production, H2 in tests). */ private static final String VALIDATION_QUERY = "SELECT 1"; @@ -76,10 +76,10 @@ public DbHealthService(final DataSource dataSource) { * succeeded. * *

    Never throws: any {@link SQLException} — and any {@link RuntimeException} raised by the - * connection pool, for example a connection-acquisition timeout — is caught, logged at - * {@code WARN} (with the stack trace at {@code DEBUG}) and reported as {@code false}. A health - * check that fails with an exception would force every caller into a {@code try}/{@code catch} - * to arrive at the same answer. + * connection pool, for example a connection-acquisition timeout — is caught, logged at {@code + * WARN} (with the stack trace at {@code DEBUG}) and reported as {@code false}. A health check + * that fails with an exception would force every caller into a {@code try}/{@code catch} to + * arrive at the same answer. * * @return {@code true} if a connection could be borrowed and the validation query executed, * {@code false} otherwise diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/data/image/ImageData.java b/spring-services-core/src/main/java/com/openelements/spring/base/data/image/ImageData.java index 0c24802..1f8ae54 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/data/image/ImageData.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/data/image/ImageData.java @@ -25,7 +25,8 @@ public record ImageData(@NonNull byte[] data, @NonNull ImageType imageType) { /** * Validates the components, rejecting {@code null}, empty, and oversized image data. * - * @throws IllegalArgumentException if {@code data} is empty or larger than {@link #MAX_IMAGE_SIZE} + * @throws IllegalArgumentException if {@code data} is empty or larger than {@link + * #MAX_IMAGE_SIZE} */ public ImageData { Objects.requireNonNull(data, "data must not be null"); diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/data/image/util/HeicSupportCheck.java b/spring-services-core/src/main/java/com/openelements/spring/base/data/image/util/HeicSupportCheck.java index 9f3acbe..1addd81 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/data/image/util/HeicSupportCheck.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/data/image/util/HeicSupportCheck.java @@ -25,8 +25,8 @@ public HeicSupportCheck() {} /** * Verifies that HEIC/HEIF images can be decoded by the current runtime. * - * @return {@code true} if a reader is registered and the bundled probe image decodes, - * {@code false} otherwise + * @return {@code true} if a reader is registered and the bundled probe image decodes, {@code + * false} otherwise */ public static boolean verifyHeicSupport() { final boolean readerRegistered = diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/data/image/util/ImageUtilities.java b/spring-services-core/src/main/java/com/openelements/spring/base/data/image/util/ImageUtilities.java index 9eb74f6..5209b3d 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/data/image/util/ImageUtilities.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/data/image/util/ImageUtilities.java @@ -56,7 +56,8 @@ public static ImageData toJpeg(@NonNull ImageData data, int maxWidth, int maxHei } /** - * Converts the given raw image bytes to JPEG and scales the result to fit within the given bounds. + * Converts the given raw image bytes to JPEG and scales the result to fit within the given + * bounds. * * @param data the source image bytes * @param contentType the MIME content type of the source image diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/data/package-info.java b/spring-services-core/src/main/java/com/openelements/spring/base/data/package-info.java index 1a7eefa..363c8a9 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/data/package-info.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/data/package-info.java @@ -133,12 +133,12 @@ * *

    Database reachability

    * - *

    Besides the abstractions above, the package ships one ready-to-use bean: - * {@link com.openelements.spring.base.data.DbHealthService}, registered by - * {@link com.openelements.spring.base.data.DataConfig}. It answers whether the configured - * {@code DataSource} is reachable right now by borrowing a connection and executing a - * validation query on it, so an application that booted against a database that has since died - * reports the truth instead of a cached "up": + *

    Besides the abstractions above, the package ships one ready-to-use bean: {@link + * com.openelements.spring.base.data.DbHealthService}, registered by {@link + * com.openelements.spring.base.data.DataConfig}. It answers whether the configured {@code + * DataSource} is reachable right now by borrowing a connection and executing a validation + * query on it, so an application that booted against a database that has since died reports the + * truth instead of a cached "up": * *

    {@code
      * if (!dbHealthService.isDatabaseReachable()) {
    @@ -151,8 +151,8 @@
      *
      * 

    Tenant-aware variants

    * - *

    For multi-tenant services, see the {@code spring-services-tenant} module (package - * {@code com.openelements.spring.base.tenant}), which provides the tenant-scoped counterparts of the + *

    For multi-tenant services, see the {@code spring-services-tenant} module (package {@code + * com.openelements.spring.base.tenant}), which provides the tenant-scoped counterparts of the * abstractions defined here. */ package com.openelements.spring.base.data; diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/events/GenericDataEvent.java b/spring-services-core/src/main/java/com/openelements/spring/base/events/GenericDataEvent.java index d6bf510..4a33135 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/events/GenericDataEvent.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/events/GenericDataEvent.java @@ -19,9 +19,9 @@ * event about a {@code BookDto}?". * *

    The captured type is also reported to Spring through {@link ResolvableTypeProvider}, so that a - * listener declared for {@code OnObjectUpdate} is only invoked for book events. Without it, - * Spring could not resolve the type parameter of an event instance and would dispatch every {@code - * OnObjectUpdate} to that listener. + * listener declared for {@code OnObjectUpdate} is only invoked for book events. Without + * it, Spring could not resolve the type parameter of an event instance and would dispatch every + * {@code OnObjectUpdate} to that listener. * *

    Application code should normally not extend this class directly — use one of the concrete * subtypes {@link OnObjectCreate}, {@link OnObjectUpdate} or {@link OnObjectDelete} so that diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/events/OnObjectUpdate.java b/spring-services-core/src/main/java/com/openelements/spring/base/events/OnObjectUpdate.java index 9c7d8d1..b46aac7 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/events/OnObjectUpdate.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/events/OnObjectUpdate.java @@ -15,8 +15,8 @@ *

    * diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/events/package-info.java b/spring-services-core/src/main/java/com/openelements/spring/base/events/package-info.java index 52cc45f..5f70833 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/events/package-info.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/events/package-info.java @@ -14,8 +14,8 @@ * has been inserted. *
  • {@link com.openelements.spring.base.events.OnObjectUpdate} — published after an existing * entity has been updated. It carries the state before the update when the publisher knows it - * (see {@link com.openelements.spring.base.events.OnObjectUpdate#isPreviousKnown()}); the data - * services always supply it and publish no event for an update that changed nothing. + * (see {@link com.openelements.spring.base.events.OnObjectUpdate#isPreviousKnown()}); the + * data services always supply it and publish no event for an update that changed nothing. *
  • {@link com.openelements.spring.base.events.OnObjectDelete} — published after an entity has * been deleted. * diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfo.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfo.java index c4751b5..b31b48d 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfo.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfo.java @@ -6,16 +6,16 @@ * A read-only snapshot of "which build is running": the artifact coordinates, the Git commit, and a * compact SBOM summary. * - *

    Returned by {@link ApplicationInfoService#getApplicationInfo()}, which never returns - * {@code null}: fields the build did not provide are simply {@code null}. The SBOM is carried only - * as a {@link SbomSummary} here; the full component list is fetched separately via - * {@link ApplicationInfoService#findSbom()} so a small info endpoint need not serialise hundreds of + *

    Returned by {@link ApplicationInfoService#getApplicationInfo()}, which never returns {@code + * null}: fields the build did not provide are simply {@code null}. The SBOM is carried only as a + * {@link SbomSummary} here; the full component list is fetched separately via {@link + * ApplicationInfoService#findSbom()} so a small info endpoint need not serialise hundreds of * components. * - *

    There is deliberately no build-timestamp field: with reproducible builds - * {@code project.build.outputTimestamp} is a fixed constant, so a build time would describe the - * parent release rather than this deployment. A build is identified by {@link #version()} and the - * commit hash in {@link #git()} — both true statements about the code. + *

    There is deliberately no build-timestamp field: with reproducible builds {@code + * project.build.outputTimestamp} is a fixed constant, so a build time would describe the parent + * release rather than this deployment. A build is identified by {@link #version()} and the commit + * hash in {@link #git()} — both true statements about the code. * * @param group the artifact group / Maven {@code groupId}, or {@code null} if no build-info was * produced @@ -36,8 +36,8 @@ public record ApplicationInfo( @Nullable SbomSummary sbom) { /** - * Returns an {@code ApplicationInfo} with every field {@code null} — the value used when the build - * produced no metadata at all. + * Returns an {@code ApplicationInfo} with every field {@code null} — the value used when the + * build produced no metadata at all. * * @return an all-{@code null} {@code ApplicationInfo}; never {@code null} */ diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoAutoConfiguration.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoAutoConfiguration.java index dec1c06..b0929e9 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoAutoConfiguration.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoAutoConfiguration.java @@ -14,8 +14,8 @@ * Auto-configuration that contributes the {@link ApplicationInfoService}. * *

    Registered as a second entry in {@code - * META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so it activates - * whenever {@code spring-services-core} is on the classpath. Unlike {@link + * META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so it + * activates whenever {@code spring-services-core} is on the classpath. Unlike {@link * com.openelements.spring.base.SpringServicesCoreAutoConfiguration} it is not * guarded by {@code @ConditionalOnClass(EntityManagerFactory.class)} and is not imported by {@code * FullSpringServiceConfig}: application info has nothing to do with JPA and must work in an @@ -33,11 +33,14 @@ @EnableConfigurationProperties(ApplicationInfoProperties.class) public class ApplicationInfoAutoConfiguration { - /** Creates the auto-configuration; the service is contributed by {@link #applicationInfoService}. */ + /** + * Creates the auto-configuration; the service is contributed by {@link #applicationInfoService}. + */ public ApplicationInfoAutoConfiguration() {} /** - * Contributes the default {@link ApplicationInfoService}, unless the application declares its own. + * Contributes the default {@link ApplicationInfoService}, unless the application declares its + * own. * * @param buildProperties provider for the optional {@link BuildProperties} bean * @param gitProperties provider for the optional {@link GitProperties} bean diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoProperties.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoProperties.java index 441f70e..d30d4af 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoProperties.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoProperties.java @@ -7,12 +7,12 @@ * Configuration for {@link ApplicationInfoService}, bound from the {@code openelements.info.*} * namespace. * - *

    The {@code openelements.} prefix (rather than {@code open-elements.}) matches the prefixes used - * by the {@code scim}, {@code mcp} and {@code db-backup} features; the inconsistency with + *

    The {@code openelements.} prefix (rather than {@code open-elements.}) matches the prefixes + * used by the {@code scim}, {@code mcp} and {@code db-backup} features; the inconsistency with * {@code slack} / {@code email} predates this feature. * - * @param sbom SBOM-reading configuration; defaulted when the {@code openelements.info.sbom} block is - * omitted + * @param sbom SBOM-reading configuration; defaulted when the {@code openelements.info.sbom} block + * is omitted */ @ConfigurationProperties("openelements.info") public record ApplicationInfoProperties(@DefaultValue Sbom sbom) { diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoService.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoService.java index 7915b92..6d53ac2 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoService.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/ApplicationInfoService.java @@ -18,8 +18,8 @@ * and, as a Git fallback, {@code build.commit}), {@link GitProperties} (Git metadata) and a * CycloneDX SBOM on the classpath — and exposes them through an immutable {@link ApplicationInfo} * plus a full {@link SbomDocument}. It adds no build timestamp, reads no secrets, and never fails - * startup: a build that produced no metadata yields an all-{@code null} {@link ApplicationInfo}, and - * an unreadable SBOM yields no SBOM plus a single {@code WARN}. + * startup: a build that produced no metadata yields an all-{@code null} {@link ApplicationInfo}, + * and an unreadable SBOM yields no SBOM plus a single {@code WARN}. * *

    Both values are computed once in the constructor and cached in final fields: the service is * immutable and trivially thread-safe, the SBOM file is read exactly once, and any warning about an @@ -75,8 +75,8 @@ public ApplicationInfoService( * Returns the build snapshot: artifact coordinates, Git info and an SBOM summary. The * full component list is deliberately not carried here — use {@link #findSbom()} for that. * - * @return the cached {@link ApplicationInfo}; never {@code null}. Fields the build did not provide - * are {@code null} + * @return the cached {@link ApplicationInfo}; never {@code null}. Fields the build did not + * provide are {@code null} */ public ApplicationInfo getApplicationInfo() { return applicationInfo; @@ -85,8 +85,8 @@ public ApplicationInfo getApplicationInfo() { /** * Returns the full parsed SBOM. * - * @return the cached SBOM document, or empty if no SBOM was found, it could not be parsed, or SBOM - * reading is disabled + * @return the cached SBOM document, or empty if no SBOM was found, it could not be parsed, or + * SBOM reading is disabled */ public Optional findSbom() { return sbom; @@ -146,7 +146,9 @@ private static Optional resolveSbom( return null; } - /** Mirrors {@code GitProperties.getShortCommitId()}: first seven chars, or the whole short hash. */ + /** + * Mirrors {@code GitProperties.getShortCommitId()}: first seven chars, or the whole short hash. + */ private static String shorten(final String commitId) { return commitId.length() > 7 ? commitId.substring(0, 7) : commitId; } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/CycloneDxReader.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/CycloneDxReader.java index 0365869..1bf8902 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/CycloneDxReader.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/CycloneDxReader.java @@ -164,8 +164,8 @@ private List aggregateLicenses(final List components) { } /** - * Returns the trimmed text value of {@code field} on {@code node}, or {@code null} if the field is - * absent, {@code null}, a non-scalar, or blank. + * Returns the trimmed text value of {@code field} on {@code node}, or {@code null} if the field + * is absent, {@code null}, a non-scalar, or blank. */ private static @Nullable String text(final @Nullable JsonNode node, final String field) { if (node == null) { diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/GitInfo.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/GitInfo.java index a8b48df..ba7306f 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/GitInfo.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/GitInfo.java @@ -9,9 +9,8 @@ * *

    A {@code GitInfo} exists only when a commit hash is known — the absence of a commit is * represented by a {@code null} {@link ApplicationInfo#git()}, not by a {@code GitInfo} full of - * {@code null}s. The hash is sourced either from {@code git.properties} on the classpath root (where - * {@code .git} - * was present at build time) or, as a fallback, from {@code build.commit} in + * {@code null}s. The hash is sourced either from {@code git.properties} on the classpath root + * (where {@code .git} was present at build time) or, as a fallback, from {@code build.commit} in * {@code build-info.properties} (the container build that receives the hash as a build argument); * see {@link ApplicationInfoService} for the precedence rule. * diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomComponent.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomComponent.java index 2df61bc..a1bcf30 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomComponent.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomComponent.java @@ -16,12 +16,12 @@ * @param name the component name (Maven {@code artifactId}); never {@code null} — a CycloneDX * component without a name is not a valid component * @param version the component version, or {@code null} if the SBOM did not declare one - * @param type the CycloneDX component type ({@code "library"}, {@code "application"}, - * {@code "framework"}, …), or {@code null} if absent + * @param type the CycloneDX component type ({@code "library"}, {@code "application"}, {@code + * "framework"}, …), or {@code null} if absent * @param purl the package URL uniquely identifying the artifact, or {@code null} if absent - * @param licenses the licenses declared for this component, each collapsed to a single string - * (SPDX id, else free-text name, else expression); never {@code null}, never contains - * {@code null}, and always unmodifiable + * @param licenses the licenses declared for this component, each collapsed to a single string (SPDX + * id, else free-text name, else expression); never {@code null}, never contains {@code null}, + * and always unmodifiable */ public record SbomComponent( @Nullable String group, diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomDocument.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomDocument.java index 36d7b4b..c7432de 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomDocument.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomDocument.java @@ -5,9 +5,9 @@ /** * The full parsed CycloneDX SBOM: its {@link SbomSummary} plus the complete list of components. * - *

    Returned by {@link ApplicationInfoService#findSbom()}. The {@link #summary()} is the same value - * carried by {@link ApplicationInfo#sbom()}, so the small info payload and the full admin view agree - * on format, serial number, component count and license union. + *

    Returned by {@link ApplicationInfoService#findSbom()}. The {@link #summary()} is the same + * value carried by {@link ApplicationInfo#sbom()}, so the small info payload and the full admin + * view agree on format, serial number, component count and license union. * * @param summary the compact summary of this SBOM; never {@code null} * @param components every component in the SBOM's {@code components} array; never {@code null}, diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomSummary.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomSummary.java index b9c738b..6d0bbdc 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomSummary.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/SbomSummary.java @@ -9,20 +9,20 @@ * *

    This is the SBOM view returned by {@link ApplicationInfoService#getApplicationInfo()}, so an * application can expose a small {@code /api/info} payload without serialising several hundred - * components on every request. The full list is available separately via - * {@link ApplicationInfoService#findSbom()}. + * components on every request. The full list is available separately via {@link + * ApplicationInfoService#findSbom()}. * *

    The SBOM's {@code metadata.timestamp} is deliberately not exposed: with reproducible - * builds it is a fixed constant and would misrepresent "when was this built?". The - * {@code serialNumber} is kept because {@code cyclonedx-maven-plugin} derives it deterministically - * from the SBOM's content, so it identifies the document without asserting a time. + * builds it is a fixed constant and would misrepresent "when was this built?". The {@code + * serialNumber} is kept because {@code cyclonedx-maven-plugin} derives it deterministically from + * the SBOM's content, so it identifies the document without asserting a time. * * @param bomFormat the SBOM format, always {@code "CycloneDX"} for a document this reader accepts, * or {@code null} if the field was absent * @param specVersion the CycloneDX spec version (e.g. {@code "1.6"}), or {@code null} if absent * @param serialNumber the SBOM serial number (e.g. {@code "urn:uuid:…"}), or {@code null} if absent - * @param application the component declared under {@code metadata.component} — the artifact the SBOM - * describes — or {@code null} if the SBOM carried no {@code metadata.component} + * @param application the component declared under {@code metadata.component} — the artifact the + * SBOM describes — or {@code null} if the SBOM carried no {@code metadata.component} * @param componentCount the number of entries in the SBOM's {@code components} array * @param licenses the distinct, sorted union of every license declared by any component; never * {@code null}, never contains {@code null}, and always unmodifiable diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/info/package-info.java b/spring-services-core/src/main/java/com/openelements/spring/base/info/package-info.java index eff2985..81e9870 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/info/package-info.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/info/package-info.java @@ -3,20 +3,21 @@ * *

    This package answers one operational question — "which build is running, and what is it * made of?" — through a single service, {@link - * com.openelements.spring.base.info.ApplicationInfoService}, and an immutable record model rooted at - * {@link com.openelements.spring.base.info.ApplicationInfo}. + * com.openelements.spring.base.info.ApplicationInfoService}, and an immutable record model rooted + * at {@link com.openelements.spring.base.info.ApplicationInfo}. * *

    Data sources

    * *

    All inputs are produced by the build, never by this library: * *

      - *
    • Artifact coordinates — from {@code META-INF/build-info.properties}, exposed by Spring - * Boot as {@link org.springframework.boot.info.BuildProperties}. + *
    • Artifact coordinates — from {@code META-INF/build-info.properties}, exposed by + * Spring Boot as {@link org.springframework.boot.info.BuildProperties}. *
    • Git metadata — from {@code git.properties} on the classpath root (Spring Boot's - * default for {@code spring.info.git.location}; not under {@code META-INF}), exposed as {@link - * org.springframework.boot.info.GitProperties}; with a fallback to {@code build.commit} in - * {@code build-info.properties} for container builds that have no {@code .git} directory. + * default for {@code spring.info.git.location}; not under {@code META-INF}), exposed + * as {@link org.springframework.boot.info.GitProperties}; with a fallback to {@code + * build.commit} in {@code build-info.properties} for container builds that have no {@code + * .git} directory. *
    • SBOM — a CycloneDX document on the classpath (default {@code * META-INF/sbom/application.cdx.json}), parsed by the package-private {@link * com.openelements.spring.base.info.CycloneDxReader}. @@ -27,7 +28,8 @@ *
        *
      • The service is contributed by {@link * com.openelements.spring.base.info.ApplicationInfoAutoConfiguration}, which is not - * guarded by JPA — application info must work in an application that has no persistence layer. + * guarded by JPA — application info must work in an application that has no persistence + * layer. *
      • No build timestamp is exposed anywhere in the model: it would be a fixed reproducible-build * constant, not an answer to "when was this deployed?". *
      • The library exposes no REST endpoint. An SBOM is an attack-surface map, so the diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/BodyErrors.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/BodyErrors.java index 06b43eb..6d9ef3f 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/BodyErrors.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/BodyErrors.java @@ -26,8 +26,8 @@ * ConstraintViolation} around, which it does for every Bean Validation failure. That is the path * that honours {@code @JsonProperty} and the configured naming strategy. A failure reported by a * plain Spring {@link org.springframework.validation.Validator} has no constraint violation to - * unwrap, so its field expression is converted structurally instead — the best available answer, and - * still a valid pointer. + * unwrap, so its field expression is converted structurally instead — the best available answer, + * and still a valid pointer. * *

        Rejected values are never included. {@link FieldError#getRejectedValue()} is * not read anywhere in this class: the value the client sent is frequently the personal data the @@ -124,9 +124,10 @@ private static String message(final ObjectError error) { * @return the target's class, or {@link Object} when the target is not available */ private static Class rootType(final Errors errors) { - final Object target = errors instanceof org.springframework.validation.BindingResult result - ? result.getTarget() - : null; + final Object target = + errors instanceof org.springframework.validation.BindingResult result + ? result.getTarget() + : null; return target != null ? target.getClass() : Object.class; } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/DefaultProblemFactory.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/DefaultProblemFactory.java index c1d6baa..d538bfd 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/DefaultProblemFactory.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/DefaultProblemFactory.java @@ -59,8 +59,7 @@ public ProblemDetail create( } @Override - public ProblemDetail create( - final ProblemException exception, final HttpServletRequest request) { + public ProblemDetail create(final ProblemException exception, final HttpServletRequest request) { Objects.requireNonNull(exception, "exception must not be null"); final ProblemDetail problem = @@ -74,8 +73,8 @@ public ProblemDetail create( * *

        A path that cannot be parsed as a URI reference yields no {@code instance} at all. This is * the error renderer: it runs when something has already gone wrong, and throwing here would - * replace a considered {@code 404} with an unconsidered {@code 500} and lose the original failure. - * One optional member is the cheaper loss. + * replace a considered {@code 404} with an unconsidered {@code 500} and lose the original + * failure. One optional member is the cheaper loss. * * @param request the request being handled * @return the original request path on an error dispatch, the current path otherwise — never with diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/JsonPointers.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/JsonPointers.java index a98bd87..8111063 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/JsonPointers.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/JsonPointers.java @@ -1,24 +1,24 @@ package com.openelements.spring.base.problem; -import tools.jackson.databind.BeanDescription; -import tools.jackson.databind.JavaType; -import tools.jackson.databind.ObjectMapper; -import tools.jackson.databind.SerializationConfig; -import tools.jackson.databind.introspect.ClassIntrospector; -import tools.jackson.databind.introspect.BeanPropertyDefinition; import jakarta.validation.ElementKind; import jakarta.validation.Path; import jakarta.validation.Path.Node; import java.util.Objects; import org.jspecify.annotations.Nullable; +import tools.jackson.databind.BeanDescription; +import tools.jackson.databind.JavaType; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.SerializationConfig; +import tools.jackson.databind.introspect.BeanPropertyDefinition; +import tools.jackson.databind.introspect.ClassIntrospector; /** * Turns a Bean Validation {@link Path} into an RFC 6901 JSON pointer into the request body. * *

        A validation error has to point at the request the client sent, not at the Java object the * server bound it to. Those two differ whenever {@code @JsonProperty} renames a field or a {@link - * tools.jackson.databind.PropertyNamingStrategy} is configured, which is the normal case for - * a snake_case API: + * tools.jackson.databind.PropertyNamingStrategy} is configured, which is the normal case for a + * snake_case API: * *

        {@code
          * record Address(@JsonProperty("postal_code") @Pattern(regexp = "[0-9]{5}") String postalCode) {}
        @@ -33,10 +33,11 @@
          * guess. A type Jackson cannot introspect falls back to the Java property name for that one segment
          * — a slightly wrong pointer is more useful to a client than no error at all.
          *
        - * 

        Indexes and map keys become their own segments ({@code items[0].name} → {@code /items/0/name}), - * and keys are escaped per RFC 6901 §3: {@code ~} → {@code ~0}, {@code /} → {@code ~1}, in that - * order. A class-level constraint has no property segment and yields the pointer of the object it - * sits on — {@code ""} for the body root, which RFC 6901 defines as "the whole document". + *

        Indexes and map keys become their own segments ({@code items[0].name} → {@code + * /items/0/name}), and keys are escaped per RFC 6901 §3: {@code ~} → {@code ~0}, {@code /} → {@code + * ~1}, in that order. A class-level constraint has no property segment and yields the pointer of + * the object it sits on — {@code ""} for the body root, which RFC 6901 defines as "the whole + * document". */ final class JsonPointers { @@ -89,8 +90,8 @@ String pointer(final Class rootType, final Path path) { * Decides whether a path node describes a position inside the request body. * *

        Method-level validation prefixes the path with the method and its parameter; neither exists - * in the JSON document, so both are skipped. {@code BEAN} nodes carry a class-level constraint and - * contribute no segment of their own. + * in the JSON document, so both are skipped. {@code BEAN} nodes carry a class-level constraint + * and contribute no segment of their own. * * @param node the path node * @return {@code true} if the node contributes to the pointer diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ParameterMessages.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ParameterMessages.java index 5a9646e..47ce900 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ParameterMessages.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ParameterMessages.java @@ -47,9 +47,14 @@ private ParameterMessages() { * reason falls back to a generic one rather than writing {@code null} into the response * @return one sentence, ending in a full stop */ - static String invalid( - final String location, final String name, final @Nullable String reason) { - return "Invalid " + location + " parameter '" + name + "': " + withoutTrailingStop(reason) + "."; + static String invalid(final String location, final String name, final @Nullable String reason) { + return "Invalid " + + location + + " parameter '" + + name + + "': " + + withoutTrailingStop(reason) + + "."; } /** diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemAuthenticationEntryPoint.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemAuthenticationEntryPoint.java index dd44a3c..1be4948 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemAuthenticationEntryPoint.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemAuthenticationEntryPoint.java @@ -24,9 +24,9 @@ * Spring Security precisely so that a {@code 401} is not the one response without one. * *

        {@code detail} is the {@link AuthenticationException}'s message, as the previous {@code - * message} field was. The library only ever feeds short, well-known reasons into this path — - * {@code "Invalid API key"}, Spring Security's own {@code "Full authentication is required to access - * this resource"} — and never reflects anything the client sent. + * message} field was. The library only ever feeds short, well-known reasons into this path — {@code + * "Invalid API key"}, Spring Security's own {@code "Full authentication is required to access this + * resource"} — and never reflects anything the client sent. */ public class ProblemAuthenticationEntryPoint implements AuthenticationEntryPoint { diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemBody.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemBody.java index 7ac39f3..2c4a367 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemBody.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemBody.java @@ -28,9 +28,9 @@ * *

        Members come out in the order RFC 9457 lists them — {@code type}, {@code title}, {@code * status}, {@code detail}, {@code instance} — followed by the extensions in insertion order, so two - * responses for the same problem are byte-identical. {@code detail} and {@code instance} are omitted - * rather than written as {@code null}: RFC 9457 §3.1 makes them optional, and {@code "detail": null} - * says nothing a client can act on. + * responses for the same problem are byte-identical. {@code detail} and {@code instance} are + * omitted rather than written as {@code null}: RFC 9457 §3.1 makes them optional, and {@code + * "detail": null} says nothing a client can act on. */ final class ProblemBody { diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsAutoConfiguration.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsAutoConfiguration.java index e350bfc..1c10e97 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsAutoConfiguration.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsAutoConfiguration.java @@ -28,10 +28,10 @@ * *

        Boot contributes two beans this feature replaces, and both back off only for a bean that * already exists: {@code BasicErrorController} ({@code @ConditionalOnMissingBean(ErrorController)}) - * and its own {@code ProblemDetailsExceptionHandler} ({@code - * @ConditionalOnMissingBean(ResponseEntityExceptionHandler)}). Declaring {@code before} both - * auto-configurations is what makes the library's beans win; without it the outcome would depend on - * auto-configuration ordering, which is unspecified. + * and its own {@code ProblemDetailsExceptionHandler} + * ({@code @ConditionalOnMissingBean(ResponseEntityExceptionHandler)}). Declaring {@code before} + * both auto-configurations is what makes the library's beans win; without it the outcome would + * depend on auto-configuration ordering, which is unspecified. * *

        What an application can replace

        * @@ -107,8 +107,8 @@ public ProblemDetailsExceptionHandler problemDetailsExceptionHandler( * decides whether a bean is a request handler by looking for {@code @Controller} on the type the * bean factory reports, which for a {@code @Bean} method is its declared return type. * Declaring the interface would leave {@code /error} unmapped: the context would start, the bean - * would exist, {@code BasicErrorController} would still back off — and every container error would - * answer {@code 404} instead of its real status. + * would exist, {@code BasicErrorController} would still back off — and every container error + * would answer {@code 404} instead of its real status. * *

        The method is package-private because its return type is: the class is an implementation * detail, and nothing outside this package has reason to inject it. @@ -125,11 +125,12 @@ ProblemErrorController problemErrorController( } /** - * Inserts the catch-all resolver directly after Spring's {@link ExceptionHandlerExceptionResolver}. + * Inserts the catch-all resolver directly after Spring's {@link + * ExceptionHandlerExceptionResolver}. * - *

        The position is the contract: after the advice resolver, so no application {@code - * @ExceptionHandler} can be shadowed, and before {@code ResponseStatusExceptionResolver} and - * {@code DefaultHandlerExceptionResolver}, so {@code @ResponseStatus} and {@code + *

        The position is the contract: after the advice resolver, so no application + * {@code @ExceptionHandler} can be shadowed, and before {@code ResponseStatusExceptionResolver} + * and {@code DefaultHandlerExceptionResolver}, so {@code @ResponseStatus} and {@code * ResponseStatusException} are rendered as problems rather than as Spring's own error page. * * @param problemFactory builds the problems @@ -157,8 +158,7 @@ public void extendHandlerExceptionResolvers(final List * @return the index to insert at; the end of the chain if the advice resolver is absent, which * only happens when an application has replaced the whole chain */ - private static int afterExceptionHandlerResolver( - final List resolvers) { + private static int afterExceptionHandlerResolver(final List resolvers) { for (int i = 0; i < resolvers.size(); i++) { if (resolvers.get(i) instanceof ExceptionHandlerExceptionResolver) { return i + 1; diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsExceptionHandler.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsExceptionHandler.java index dcd44ee..819f1ea 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsExceptionHandler.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsExceptionHandler.java @@ -41,8 +41,8 @@ *

        Ordered at {@link Ordered#LOWEST_PRECEDENCE}, so any application {@code @ControllerAdvice} * wins. An application advice that handles one of the exceptions below — {@code * MethodArgumentNotValidException}, say — has the same order by default, and which of two - * equally ordered advices wins depends on bean registration order, which is not a contract. - * Such an advice must therefore carry an explicit {@code @Order}. + * equally ordered advices wins depends on bean registration order, which is not a contract. Such an + * advice must therefore carry an explicit {@code @Order}. * *

        What it maps

        * @@ -65,8 +65,8 @@ * *

        Failures on the request body become {@code errors} entries with a JSON pointer. * Failures on query, path and header parameters are described in {@code detail} instead, because a - * pointer addresses a location in a JSON document and a parameter has none. A request that gets both - * wrong is a {@code validation-failed} carrying the body's {@code errors} and the parameters' + * pointer addresses a location in a JSON document and a parameter has none. A request that gets + * both wrong is a {@code validation-failed} carrying the body's {@code errors} and the parameters' * sentences: * * @@ -80,9 +80,9 @@ *

        What never reaches the client

        * *

        No rejected value, no Jackson parser message and no class name. Spring's own detail for a type - * mismatch is {@code Failed to convert 'size' with value: 'jane@example.com'}; this handler replaces - * it. For the exceptions it does not override, Spring's detail is kept — those messages name the - * offending header or method, not the payload. + * mismatch is {@code Failed to convert 'size' with value: 'jane@example.com'}; this handler + * replaces it. For the exceptions it does not override, Spring's detail is kept — those messages + * name the offending header or method, not the payload. */ @RestControllerAdvice @Order(Ordered.LOWEST_PRECEDENCE) @@ -113,8 +113,7 @@ protected ResponseEntity handleMethodArgumentNotValid( final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { - final ProblemDetail problem = - problem(StandardProblemType.VALIDATION_FAILED, null, request); + final ProblemDetail problem = problem(StandardProblemType.VALIDATION_FAILED, null, request); problem.setProperty(ProblemMembers.ERRORS, bodyErrors.from(ex.getBindingResult())); return handleExceptionInternal(ex, problem, headers, status, request); } @@ -134,7 +133,8 @@ protected ResponseEntity handleHandlerMethodValidationException( for (final ParameterValidationResult result : ex.getParameterValidationResults()) { if (isRequestBody(result.getMethodParameter()) - && result instanceof org.springframework.validation.method.ParameterErrors parameterErrors) { + && result + instanceof org.springframework.validation.method.ParameterErrors parameterErrors) { errors.addAll(bodyErrors.from(parameterErrors)); } else { parameterSentences.addAll(sentencesFor(result)); @@ -143,7 +143,9 @@ protected ResponseEntity handleHandlerMethodValidationException( final String detail = ParameterMessages.join(parameterSentences); final ProblemType type = - errors.isEmpty() ? StandardProblemType.INVALID_PARAMETER : StandardProblemType.VALIDATION_FAILED; + errors.isEmpty() + ? StandardProblemType.INVALID_PARAMETER + : StandardProblemType.VALIDATION_FAILED; final ProblemDetail problem = problem(type, detail, request); if (!errors.isEmpty()) { problem.setProperty(ProblemMembers.ERRORS, List.copyOf(errors)); @@ -151,7 +153,8 @@ protected ResponseEntity handleHandlerMethodValidationException( return handleExceptionInternal(ex, problem, headers, status, request); } - // --- malformed and unusable input --------------------------------------------------------------- + // --- malformed and unusable input + // --------------------------------------------------------------- @Override protected ResponseEntity handleHttpMessageNotReadable( @@ -239,9 +242,9 @@ protected ResponseEntity handleMissingPathVariable( * Converts the body of every standard MVC exception into a problem. * *

        The base class has already decided the status and the response headers — {@code Allow} on a - * {@code 405}, {@code Accept} on a {@code 415} — and those are kept. Only the body is replaced, by - * the problem for that status, carrying Spring's own detail when it has one. Spring's details for - * these exceptions name the method, the media type or the header, never the payload. + * {@code 405}, {@code Accept} on a {@code 415} — and those are kept. Only the body is replaced, + * by the problem for that status, carrying Spring's own detail when it has one. Spring's details + * for these exceptions name the method, the media type or the header, never the payload. * *

        The overrides above pass their own {@link ProblemDetail} as {@code body}; it is used as is. * @@ -277,7 +280,8 @@ protected ResponseEntity handleExceptionInternal( */ private ProblemDetail asProblem( final Exception ex, final HttpStatusCode statusCode, final WebRequest request) { - final String detail = ex instanceof ErrorResponse errorResponse ? errorResponse.getBody().getDetail() : null; + final String detail = + ex instanceof ErrorResponse errorResponse ? errorResponse.getBody().getDetail() : null; return problem(StandardProblemType.forStatus(statusCode.value()), detail, request); } @@ -309,7 +313,8 @@ private static HttpServletRequest servletRequest(final WebRequest request) { : null; if (servletRequest == null) { throw new IllegalStateException( - "ProblemDetailsExceptionHandler requires a servlet request but got " + request.getClass()); + "ProblemDetailsExceptionHandler requires a servlet request but got " + + request.getClass()); } return servletRequest; } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsProperties.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsProperties.java index b17560d..9c85015 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsProperties.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemDetailsProperties.java @@ -15,15 +15,15 @@ * openelements.problem-details.include-instance=true * } * - * @param enabled whether error responses are RFC 9457 problems. Defaults to {@code true}. Setting it - * to {@code false} restores the behaviour from before this feature: a JSON {@code 401} with + * @param enabled whether error responses are RFC 9457 problems. Defaults to {@code true}. Setting + * it to {@code false} restores the behaviour from before this feature: a JSON {@code 401} with * {@code status}/{@code error}/{@code message}, Spring Boot's {@code BasicErrorController}, and * ALTCHA's {@code {code, message}} body. The trace filter keeps running either way * @param typeBase the base URI every {@code type} member is built from, by appending the problem * type's slug. Must be an absolute URI whose path ends with {@code /}. Applies to the library's * types and the application's alike — an application that publishes its own problem - * documentation sets its own base and the library's types move under it. Defaults to - * {@code https://open-elements.com/problems/spring-services/} + * documentation sets its own base and the library's types move under it. Defaults to {@code + * https://open-elements.com/problems/spring-services/} * @param includeInstance whether the problem carries an {@code instance} member with the request * path. The query string is never included, with or without this flag, because it may carry * personal data. Defaults to {@code true} diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemErrorController.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemErrorController.java index ab100c8..0e21d0c 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemErrorController.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemErrorController.java @@ -16,18 +16,18 @@ * Renders errors that never reached a controller. * *

        Replaces Spring Boot's {@code BasicErrorController} on {@code server.error.path}. Everything - * the servlet container produces by itself, and every {@code response.sendError(...)} from a filter, - * arrives here through the container's {@code ERROR} dispatch — which is the one error path Spring - * MVC's exception handling never sees. + * the servlet container produces by itself, and every {@code response.sendError(...)} from a + * filter, arrives here through the container's {@code ERROR} dispatch — which is the one error path + * Spring MVC's exception handling never sees. * - *

        The response is always {@code application/problem+json}, whatever the request asked for. Spring - * Boot would offer an HTML page to a browser; this library serves APIs, and an HTML error page from - * an API endpoint is of no use to its caller. Writing the body directly, rather than returning it - * for content negotiation, is what makes that unconditional. + *

        The response is always {@code application/problem+json}, whatever the request asked for. + * Spring Boot would offer an HTML page to a browser; this library serves APIs, and an HTML error + * page from an API endpoint is of no use to its caller. Writing the body directly, rather than + * returning it for content negotiation, is what makes that unconditional. * *

        No {@code detail} is set. The text that reaches this point comes from the servlet container or - * from a {@code sendError(status, message)} somewhere in a filter: it is not curated, is sometimes a - * stack-trace fragment, and is never written with a client in mind. The status, the type and the + * from a {@code sendError(status, message)} somewhere in a filter: it is not curated, is sometimes + * a stack-trace fragment, and is never written with a client in mind. The status, the type and the * trace ID carry everything that can be said responsibly. * *

        {@code instance} reports the path the client asked for, taken from {@code @@ -58,7 +58,8 @@ public void handleError(final HttpServletRequest request, final HttpServletRespo final int status = statusOf(request); final ProblemDetail problem = problemFactory.create(StandardProblemType.forStatus(status), null, request); - // forStatus(...) reports 500 for a code HttpStatus does not know; the dispatch knows the real one. + // forStatus(...) reports 500 for a code HttpStatus does not know; the dispatch knows the real + // one. problem.setStatus(status); responseWriter.write(response, problem); } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemException.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemException.java index 765df7b..a93f039 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemException.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemException.java @@ -174,7 +174,9 @@ private static Map copyProperties(final Map propertie Objects.requireNonNull(value, "value of property '" + key + "' must not be null"); if (RESERVED_MEMBERS.contains(key)) { throw new IllegalArgumentException( - "'" + key + "' is written by the library and must not be used as an extension member"); + "'" + + key + + "' is written by the library and must not be used as an extension member"); } copy.put(key, value); }); diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemHandlerExceptionResolver.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemHandlerExceptionResolver.java index c251f10..9035f49 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemHandlerExceptionResolver.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemHandlerExceptionResolver.java @@ -27,10 +27,10 @@ /** * The last resort: turns anything still unhandled into a problem. * - *

        Registered directly after Spring's {@code ExceptionHandlerExceptionResolver}, so every - * {@code @ExceptionHandler} in the application — with or without an {@code @Order} — has already had - * its chance. That position is the whole point of this class being a resolver rather than another - * {@code @ControllerAdvice}: two advices without an explicit order both sit at {@code + *

        Registered directly after Spring's {@code ExceptionHandlerExceptionResolver}, so + * every {@code @ExceptionHandler} in the application — with or without an {@code @Order} — has + * already had its chance. That position is the whole point of this class being a resolver rather + * than another {@code @ControllerAdvice}: two advices without an explicit order both sit at {@code * LOWEST_PRECEDENCE} and the winner depends on bean registration order, which is not a contract. A * resolver placed after the advice resolver can never shadow an application handler. * @@ -52,11 +52,12 @@ * *

        What it deliberately does not resolve

        * - *

        {@link AccessDeniedException}, including Spring Security's {@code AuthorizationDeniedException} - * from method security. Resolving it here would take the decision away from Spring Security's {@code - * ExceptionTranslationFilter}, which answers {@code 401} for an anonymous caller and {@code 403} for - * an authenticated one. Letting it propagate keeps that distinction and still produces a problem - * body, written by {@code ProblemAccessDeniedHandler} or the chain's authentication entry point. + *

        {@link AccessDeniedException}, including Spring Security's {@code + * AuthorizationDeniedException} from method security. Resolving it here would take the decision + * away from Spring Security's {@code ExceptionTranslationFilter}, which answers {@code 401} for an + * anonymous caller and {@code 403} for an authenticated one. Letting it propagate keeps that + * distinction and still produces a problem body, written by {@code ProblemAccessDeniedHandler} or + * the chain's authentication entry point. * *

        What a {@code 500} tells the client

        * @@ -130,7 +131,8 @@ private ProblemDetail toProblem( final ProblemDetail problem = problemFactory.create( StandardProblemType.forStatus(status), errorResponse.getBody().getDetail(), request); - // forStatus(...) reports 500 for a code HttpStatus does not know; the occurrence knows better. + // forStatus(...) reports 500 for a code HttpStatus does not know; the occurrence knows + // better. problem.setStatus(status); return problem; } @@ -147,10 +149,10 @@ && isControllerBoundary(violations, handler)) { * Decides whether a {@link ConstraintViolationException} describes the request or a bug. * *

        It describes the request only when every violation was raised on the handler method - * the request is being dispatched to — the shape produced by a controller annotated {@code - * @Validated}. A violation from a {@code @Validated} service deeper down means the application - * built an invalid argument itself: that is a server-side defect, and answering {@code 400} would - * blame the client for it and hide the bug. + * the request is being dispatched to — the shape produced by a controller annotated + * {@code @Validated}. A violation from a {@code @Validated} service deeper down means the + * application built an invalid argument itself: that is a server-side defect, and answering + * {@code 400} would blame the client for it and hide the bug. * * @param violations the exception * @param handler the handler the request was dispatched to @@ -165,8 +167,7 @@ private static boolean isControllerBoundary( if (constraintViolations == null || constraintViolations.isEmpty()) { return false; } - return constraintViolations.stream() - .allMatch(violation -> raisedOn(violation, handlerMethod)); + return constraintViolations.stream().allMatch(violation -> raisedOn(violation, handlerMethod)); } /** diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemResponseWriter.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemResponseWriter.java index e72ebc0..a6127a6 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemResponseWriter.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemResponseWriter.java @@ -16,10 +16,10 @@ * and have to write the response themselves — this class is what they use, so a {@code 401} written * by a filter is byte-for-byte the same shape as a {@code 409} written by a controller. * - *

        The response is committed with {@code Content-Type: application/problem+json} regardless of the - * request's {@code Accept} header. Content negotiation on an error is of no use to anyone: a browser - * asking for {@code text/html} still gets the problem, because this library serves APIs and has no - * HTML error pages to offer. + *

        The response is committed with {@code Content-Type: application/problem+json} regardless of + * the request's {@code Accept} header. Content negotiation on an error is of no use to anyone: a + * browser asking for {@code text/html} still gets the problem, because this library serves APIs and + * has no HTML error pages to offer. * *

        The body is built by {@link ProblemBody} rather than serialised from the {@link ProblemDetail} * directly, so a problem written here has exactly the same members, in the same order, as one diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemType.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemType.java index 7538cec..8dce6fd 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemType.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/ProblemType.java @@ -7,8 +7,8 @@ /** * One kind of error, identified by a stable slug. * - *

        A problem type is the machine-readable half of an RFC 9457 problem. The slug is appended to the - * configured base URI ({@code openelements.problem-details.type-base}) to form the {@code type} + *

        A problem type is the machine-readable half of an RFC 9457 problem. The slug is appended to + * the configured base URI ({@code openelements.problem-details.type-base}) to form the {@code type} * member of the response: * *

        {@code
        @@ -17,13 +17,13 @@
          * }
        * *

        Clients compare the full {@code type} URI, never the {@code status} or the - * {@code title}. A slug is therefore public API: changing one breaks every consumer that branches on - * it, exactly like renaming a REST path. + * {@code title}. A slug is therefore public API: changing one breaks every consumer that branches + * on it, exactly like renaming a REST path. * *

        Defining application types

        * - *

        An enum is the usual form, because it gives the application one place that lists every error it - * can produce: + *

        An enum is the usual form, because it gives the application one place that lists every error + * it can produce: * *

        {@code
          * public enum CrmProblemType implements ProblemType {
        @@ -46,9 +46,9 @@
          * }
          * }
        * - *

        For a handful of types, constants built with {@link #of(String, HttpStatus, String)} do just as - * well. An enum cannot be a record and a record cannot be an enum, which is why this is an interface - * rather than a record: both shapes have to be possible. + *

        For a handful of types, constants built with {@link #of(String, HttpStatus, String)} do just + * as well. An enum cannot be a record and a record cannot be an enum, which is why this is an + * interface rather than a record: both shapes have to be possible. * *

        An enum that builds its constants by hand bypasses the validation {@link #of(String, * HttpStatus, String)} performs. Call {@link #validate(ProblemType)} from a test — or from the enum @@ -108,8 +108,8 @@ static ProblemType of(final String slug, final HttpStatus status, final String t * Checks that a problem type satisfies the contract of {@link #slug()}, {@link #status()} and * {@link #title()}. * - *

        Intended for implementations that do not go through {@link #of(String, HttpStatus, String)} — - * typically an application enum. Calling it from a test over {@code values()} turns a typo in a + *

        Intended for implementations that do not go through {@link #of(String, HttpStatus, String)} + * — typically an application enum. Calling it from a test over {@code values()} turns a typo in a * slug into a build failure instead of a response no client recognises. * * @param type the type to check diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/SimpleProblemType.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/SimpleProblemType.java index 3547b65..e6bef28 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/SimpleProblemType.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/SimpleProblemType.java @@ -17,9 +17,9 @@ record SimpleProblemType(String slug, HttpStatus status, String title) implement * Builds a validated instance. * *

        The check runs after construction rather than in a compact constructor, so it can reuse - * {@link ProblemType#validate(ProblemType)} — the same method application enums are told to call — - * instead of duplicating the rules. Nothing outside this package can construct the record without - * passing through here. + * {@link ProblemType#validate(ProblemType)} — the same method application enums are told to call + * — instead of duplicating the rules. Nothing outside this package can construct the record + * without passing through here. * * @param slug the stable identifier * @param status the HTTP status diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/StandardProblemType.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/StandardProblemType.java index fb2591f..cf981ad 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/StandardProblemType.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/StandardProblemType.java @@ -19,14 +19,14 @@ * runtime. Clients compare the full {@code type} URI, so a slug is as binding as a REST path — and * Spring's constant names are not stable enough to carry one: Spring Framework 6 renamed {@code * PAYLOAD_TOO_LARGE} to {@code CONTENT_TOO_LARGE} and {@code UNPROCESSABLE_ENTITY} to {@code - * UNPROCESSABLE_CONTENT}. Deriving the slug would have silently changed two published type URIs on a - * Spring upgrade. The names here follow RFC 9110, not Spring. + * UNPROCESSABLE_CONTENT}. Deriving the slug would have silently changed two published type URIs on + * a Spring upgrade. The names here follow RFC 9110, not Spring. * *

        Two RFC 9110 statuses are deliberately absent. {@code 418} is listed as unused by §15.5.19. - * {@code 421 Misdirected Request} has no {@link HttpStatus} constant in Spring Framework 6 — it is a - * connection-level status produced by a reverse proxy, not by a request handler — and this enum does - * not invent one. Both resolve through {@link #forStatus(int)} to a synthesised {@code http-} - * type, like any other status without a name. + * {@code 421 Misdirected Request} has no {@link HttpStatus} constant in Spring Framework 6 — it is + * a connection-level status produced by a reverse proxy, not by a request handler — and this enum + * does not invent one. Both resolve through {@link #forStatus(int)} to a synthesised {@code + * http-} type, like any other status without a name. */ public enum StandardProblemType implements ProblemType { @@ -105,8 +105,7 @@ public enum StandardProblemType implements ProblemType { /** {@code 502} — an upstream server returned an invalid response. */ BAD_GATEWAY("bad-gateway", HttpStatus.BAD_GATEWAY, "Bad Gateway"), /** {@code 503} — the server is temporarily unable to handle the request. */ - SERVICE_UNAVAILABLE( - "service-unavailable", HttpStatus.SERVICE_UNAVAILABLE, "Service Unavailable"), + SERVICE_UNAVAILABLE("service-unavailable", HttpStatus.SERVICE_UNAVAILABLE, "Service Unavailable"), /** {@code 504} — an upstream server did not respond in time. */ GATEWAY_TIMEOUT("gateway-timeout", HttpStatus.GATEWAY_TIMEOUT, "Gateway Timeout"), /** {@code 505} — the HTTP version is not supported. */ @@ -115,7 +114,8 @@ public enum StandardProblemType implements ProblemType { HttpStatus.HTTP_VERSION_NOT_SUPPORTED, "HTTP Version Not Supported"), /** {@code 507} — the server cannot store the representation (RFC 4918). */ - INSUFFICIENT_STORAGE("insufficient-storage", HttpStatus.INSUFFICIENT_STORAGE, "Insufficient Storage"), + INSUFFICIENT_STORAGE( + "insufficient-storage", HttpStatus.INSUFFICIENT_STORAGE, "Insufficient Storage"), /** {@code 508} — an infinite loop was detected (RFC 5842). */ LOOP_DETECTED("loop-detected", HttpStatus.LOOP_DETECTED, "Loop Detected"), /** {@code 511} — the client must authenticate to gain network access (RFC 6585). */ @@ -124,7 +124,9 @@ public enum StandardProblemType implements ProblemType { HttpStatus.NETWORK_AUTHENTICATION_REQUIRED, "Network Authentication Required"), - /** {@code 400} — one or more fields of the request body failed validation. Carries {@code errors}. */ + /** + * {@code 400} — one or more fields of the request body failed validation. Carries {@code errors}. + */ VALIDATION_FAILED("validation-failed", HttpStatus.BAD_REQUEST, "Validation failed"), /** {@code 400} — the request body could not be parsed at all. */ MALFORMED_REQUEST("malformed-request", HttpStatus.BAD_REQUEST, "Malformed request"), @@ -132,8 +134,8 @@ public enum StandardProblemType implements ProblemType { INVALID_PARAMETER("invalid-parameter", HttpStatus.BAD_REQUEST, "Invalid parameter"); /** - * Status code to the constant that names that status. The four cause-describing types are - * deliberately absent, so {@code forStatus(400)} is {@link #BAD_REQUEST} and never {@link + * Status code to the constant that names that status. The four cause-describing types + * are deliberately absent, so {@code forStatus(400)} is {@link #BAD_REQUEST} and never {@link * #VALIDATION_FAILED}. */ private static final Map BY_STATUS = byStatus(); @@ -166,15 +168,15 @@ public String title() { /** * Returns the problem type that names the given HTTP status. * - *

        {@code 400} yields {@link #BAD_REQUEST}, {@code 500} yields {@link #INTERNAL_ERROR}. A status - * without a constant — {@code 418}, or a code outside the registry — yields a synthesised type with - * the slug {@code http-} and the title {@code HTTP }, so a response never loses its - * {@code type} member just because the status is unusual. + *

        {@code 400} yields {@link #BAD_REQUEST}, {@code 500} yields {@link #INTERNAL_ERROR}. A + * status without a constant — {@code 418}, or a code outside the registry — yields a synthesised + * type with the slug {@code http-} and the title {@code HTTP }, so a response never + * loses its {@code type} member just because the status is unusual. * *

        For a code that {@link HttpStatus} itself does not know, the synthesised type reports {@link * HttpStatus#INTERNAL_SERVER_ERROR} from {@link #status()}. Callers that know the real code — the - * error controller does — set it on the {@code ProblemDetail} afterwards, so the body always agrees - * with the status line. + * error controller does — set it on the {@code ProblemDetail} afterwards, so the body always + * agrees with the status line. * * @param statusCode the HTTP status code of the response * @return the matching problem type, never {@code null} diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/problem/package-info.java b/spring-services-core/src/main/java/com/openelements/spring/base/problem/package-info.java index 19db714..576781a 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/problem/package-info.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/problem/package-info.java @@ -20,8 +20,8 @@ * } * } * - *

        The format follows the GovStack API Design Guide, chapter 11, so an application can implement a - * GovStack building block without writing an error layer of its own. SCIM keeps its RFC 7644 + *

        The format follows the GovStack API Design Guide, chapter 11, so an application can implement + * a GovStack building block without writing an error layer of its own. SCIM keeps its RFC 7644 * envelope and is untouched by any of this. * *

        Clients compare {@code type}

        @@ -64,12 +64,12 @@ *

        What never reaches the client

        * *

        The message of an unexpected exception, its class name and its stack trace; Jackson's parser - * messages; rejected parameter and field values; and the query string, which {@code instance} always - * omits. What connects a client's report to the log entry is the {@code traceId} — see {@link - * com.openelements.spring.base.trace}. + * messages; rejected parameter and field values; and the query string, which {@code instance} + * always omits. What connects a client's report to the log entry is the {@code traceId} — see + * {@link com.openelements.spring.base.trace}. * - *

        A {@code detail} written by the application is sent verbatim, and so is an interpolated - * Bean Validation message. A message template that uses {@code ${validatedValue}} will therefore echo - * the rejected value; that is the developer's choice, not the library's. + *

        A {@code detail} written by the application is sent verbatim, and so is an + * interpolated Bean Validation message. A message template that uses {@code ${validatedValue}} will + * therefore echo the rejected value; that is the developer's choice, not the library's. */ package com.openelements.spring.base.problem; diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/security/AuthService.java b/spring-services-core/src/main/java/com/openelements/spring/base/security/AuthService.java index aabbe31..014044d 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/security/AuthService.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/security/AuthService.java @@ -90,8 +90,8 @@ public Authentication getAuthentication() { * request carries only an anonymous token, or none at all). The two are equal peers — neither is * deprecated. * - * @return an {@link Optional} holding the current authentication, or empty if none is bound to the - * security context + * @return an {@link Optional} holding the current authentication, or empty if none is bound to + * the security context */ @NonNull public Optional findAuthentication() { @@ -105,22 +105,22 @@ public Optional findAuthentication() { *

        Every authority whose value starts with {@link Roles#AUTHORITY_PREFIX} contributes its * prefix-free remainder to the result — so an authority {@code ROLE_IT-ADMIN} becomes the role * name {@code IT-ADMIN}, directly comparable against the {@link Roles} constants (e.g. {@code - * authService.getRoles().contains(Roles.ROLE_IT_ADMIN)}). Authorities that do not carry the prefix - * — most notably the {@code SCOPE_*} authorities derived from the JWT {@code scope} claim — are - * excluded, as is a bare or whitespace-only {@code ROLE_} authority. Comparison is + * authService.getRoles().contains(Roles.ROLE_IT_ADMIN)}). Authorities that do not carry the + * prefix — most notably the {@code SCOPE_*} authorities derived from the JWT {@code scope} claim + * — are excluded, as is a bare or whitespace-only {@code ROLE_} authority. Comparison is * case-sensitive, matching Spring Security's own {@code hasRole(...)} evaluation. * - *

        Unlike every other accessor on this class, this method never throws because of missing - * authentication state: an absent security context, a {@code null} authority collection, or {@code - * null} entries within it all yield an empty set rather than an exception. It never returns more - * roles than the caller actually holds. + *

        Unlike every other accessor on this class, this method never throws because of + * missing authentication state: an absent security context, a {@code null} authority collection, + * or {@code null} entries within it all yield an empty set rather than an exception. It never + * returns more roles than the caller actually holds. * - *

        Which names, not how they authenticated. The returned set answers which role names - * the caller carries; it must never be used to infer how the caller authenticated. A - * JWT whose {@code roles} claim contains {@code API_KEY} or {@code ANONYMOUS} produces exactly that - * role name, indistinguishable from what {@code ApiKeyAuthenticationFilter} or the anonymous filter - * produce. The authentication mechanism is answered by the {@link Authentication} type, not by a - * role name. + *

        Which names, not how they authenticated. The returned set answers which role + * names the caller carries; it must never be used to infer how the caller + * authenticated. A JWT whose {@code roles} claim contains {@code API_KEY} or {@code ANONYMOUS} + * produces exactly that role name, indistinguishable from what {@code ApiKeyAuthenticationFilter} + * or the anonymous filter produce. The authentication mechanism is answered by the {@link + * Authentication} type, not by a role name. * *

        The result is an immutable snapshot of the current request's roles: mutation attempts * throw {@link UnsupportedOperationException}, and {@code contains(null)} throws {@link @@ -128,8 +128,8 @@ public Optional findAuthentication() { * security-context state that should degrade closed). Hold it for the duration of the request * rather than calling this method once per role check. * - * @return an immutable set of prefix-free role names, empty if the caller holds none; never {@code - * null} + * @return an immutable set of prefix-free role names, empty if the caller holds none; never + * {@code null} */ @NonNull public Set getRoles() { @@ -139,8 +139,7 @@ public Set getRoles() { .orElseGet(Set::of); } - private static Set toRoleNames( - final Collection authorities) { + private static Set toRoleNames(final Collection authorities) { if (authorities == null) { return Set.of(); } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/security/JsonAuthenticationEntryPoint.java b/spring-services-core/src/main/java/com/openelements/spring/base/security/JsonAuthenticationEntryPoint.java index f666cfd..7c32613 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/security/JsonAuthenticationEntryPoint.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/security/JsonAuthenticationEntryPoint.java @@ -22,15 +22,15 @@ * { "status": 401, "error": "Unauthorized", "message": "" } * } * - *

        Two beans of this type are wired in {@link SecurityConfig}: one for the JWT chain (with - * {@code WWW-Authenticate: Bearer}) and one for the external API-key chain (with - * {@code WWW-Authenticate: ApiKey realm="external"}). The scheme value is constructor-injected so - * the same class serves both chains and stays RFC 7235 §3.1 compliant. + *

        Two beans of this type are wired in {@link SecurityConfig}: one for the JWT chain (with {@code + * WWW-Authenticate: Bearer}) and one for the external API-key chain (with {@code WWW-Authenticate: + * ApiKey realm="external"}). The scheme value is constructor-injected so the same class serves both + * chains and stays RFC 7235 §3.1 compliant. * *

        The {@code message} field carries the {@link AuthenticationException#getMessage()} of the * triggering exception. The library only feeds short, well-known reason strings into this path - * ({@code "Invalid API key"}, Spring Security defaults like {@code "Full authentication is - * required to access this resource"}) — no user-supplied content is reflected. + * ({@code "Invalid API key"}, Spring Security defaults like {@code "Full authentication is required + * to access this resource"}) — no user-supplied content is reflected. */ public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint { @@ -41,9 +41,9 @@ public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint { * Creates a new entry point that writes authentication failures as a JSON response. * * @param objectMapper the application's Jackson mapper, used to write the JSON body - * @param wwwAuthenticateHeader the value to send in the {@code WWW-Authenticate} response - * header — typically {@code "Bearer"} for the JWT chain or - * {@code "ApiKey realm=\"external\""} for the API-key chain + * @param wwwAuthenticateHeader the value to send in the {@code WWW-Authenticate} response header + * — typically {@code "Bearer"} for the JWT chain or {@code "ApiKey realm=\"external\""} for + * the API-key chain */ public JsonAuthenticationEntryPoint( final ObjectMapper objectMapper, final String wwwAuthenticateHeader) { diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/security/SecurityConfig.java b/spring-services-core/src/main/java/com/openelements/spring/base/security/SecurityConfig.java index f7e9f01..fc5a985 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/security/SecurityConfig.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/security/SecurityConfig.java @@ -44,10 +44,9 @@ * *

          *
        • {@link #externalApiFilterChain(HttpSecurity, ApiKeyAuthenticationFilter, - * AuthenticationEntryPoint, AccessDeniedHandler)} ({@code @Order(1)}) — matches - * {@code /api/external/**} and - * uses API-key authentication only. Read-only access (GET/HEAD/OPTIONS) is enforced - * declaratively at the chain level; all other HTTP methods are denied. + * AuthenticationEntryPoint, AccessDeniedHandler)} ({@code @Order(1)}) — matches {@code + * /api/external/**} and uses API-key authentication only. Read-only access (GET/HEAD/OPTIONS) + * is enforced declaratively at the chain level; all other HTTP methods are denied. *
        • {@link #defaultFilterChain(HttpSecurity, AuthenticationEntryPoint, AccessDeniedHandler)} * ({@code @Order(2)}) — matches everything else and uses OAuth2/JWT authentication only. The * {@code X-API-Key} header is silently ignored on this chain. @@ -63,13 +62,13 @@ * *

          Error responses

          * - *

          While {@code openelements.problem-details.enabled} is on (the default), both chains answer with - * RFC 9457 problems: {@code ProblemAuthenticationEntryPoint} for a {@code 401} and - * {@code ProblemAccessDeniedHandler} for a {@code 403}. Setting the property to {@code false} - * restores exactly what this library produced before — {@link JsonAuthenticationEntryPoint} on the - * {@code 401}, Spring Security's empty body on the {@code 403} — so the switch is a complete - * rollback rather than a partial one. The bean names stay the same in both cases, because - * other modules inject them by qualifier. + *

          While {@code openelements.problem-details.enabled} is on (the default), both chains answer + * with RFC 9457 problems: {@code ProblemAuthenticationEntryPoint} for a {@code 401} and {@code + * ProblemAccessDeniedHandler} for a {@code 403}. Setting the property to {@code false} restores + * exactly what this library produced before — {@link JsonAuthenticationEntryPoint} on the {@code + * 401}, Spring Security's empty body on the {@code 403} — so the switch is a complete rollback + * rather than a partial one. The bean names stay the same in both cases, because other + * modules inject them by qualifier. */ @Configuration(proxyBeanMethods = false) @ComponentScan(basePackageClasses = SecurityConfig.class) @@ -98,8 +97,8 @@ public SecurityConfig(final ApiKeyDataService apiKeyDataService) { /** * Entry point for the JWT chain — issues a {@code WWW-Authenticate: Bearer} header alongside an - * RFC 9457 {@code 401} problem. Used by Spring Security's - * {@code oauth2ResourceServer.authenticationEntryPoint(...)} hook on the default chain. + * RFC 9457 {@code 401} problem. Used by Spring Security's {@code + * oauth2ResourceServer.authenticationEntryPoint(...)} hook on the default chain. * * @param problemFactory builds the problem body * @param responseWriter writes it onto the raw response @@ -119,8 +118,8 @@ public AuthenticationEntryPoint problemJwtAuthenticationEntryPoint( /** * Entry point for the external API-key chain — issues a {@code WWW-Authenticate: ApiKey} header * alongside an RFC 9457 {@code 401} problem. Invoked by {@link ApiKeyAuthenticationFilter} on an - * invalid API key, and by Spring Security's - * {@code exceptionHandling.authenticationEntryPoint(...)} hook on the external chain. + * invalid API key, and by Spring Security's {@code + * exceptionHandling.authenticationEntryPoint(...)} hook on the external chain. * * @param problemFactory builds the problem body * @param responseWriter writes it onto the raw response @@ -143,8 +142,8 @@ public AuthenticationEntryPoint problemApiKeyAuthenticationEntryPoint( * * @param problemFactory builds the problem body * @param responseWriter writes it onto the raw response - * @return the access-denied handler; the bean simply does not exist while problem details are off, - * in which case Spring Security's default empty-body behaviour returns + * @return the access-denied handler; the bean simply does not exist while problem details are + * off, in which case Spring Security's default empty-body behaviour returns */ @Bean @ConditionalOnProperty( @@ -174,8 +173,8 @@ public AuthenticationEntryPoint jsonJwtAuthenticationEntryPoint(final ObjectMapp } /** - * Entry point for the external API-key chain while - * {@code openelements.problem-details.enabled=false}. + * Entry point for the external API-key chain while {@code + * openelements.problem-details.enabled=false}. * * @param objectMapper the application's Jackson mapper * @return the entry point bean @@ -324,16 +323,16 @@ public SecurityFilterChain defaultFilterChain( throws Exception { http.authorizeHttpRequests( auth -> { - if (accessDeniedHandler != null) { - auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll(); - } - auth.requestMatchers("/api/health/**") - .permitAll() - .requestMatchers( - "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs", "/v3/api-docs/**") - .permitAll() - .anyRequest() - .authenticated(); + if (accessDeniedHandler != null) { + auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll(); + } + auth.requestMatchers("/api/health/**") + .permitAll() + .requestMatchers( + "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs", "/v3/api-docs/**") + .permitAll() + .anyRequest() + .authenticated(); }) .oauth2ResourceServer( oauth2 -> @@ -341,7 +340,8 @@ public SecurityFilterChain defaultFilterChain( .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())) .authenticationEntryPoint(jwtAuthenticationEntryPoint)) // The entry point stays registered through oauth2ResourceServer, as before this feature; - // only the access-denied handler is added here, so enabled=false leaves the chain untouched. + // only the access-denied handler is added here, so enabled=false leaves the chain + // untouched. .exceptionHandling( e -> { if (accessDeniedHandler != null) { diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/security/UserInformation.java b/spring-services-core/src/main/java/com/openelements/spring/base/security/UserInformation.java index 3b9f68f..a3d66e8 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/security/UserInformation.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/security/UserInformation.java @@ -16,29 +16,24 @@ * identity provider or if the {@code email} scope was not granted. *

        • {@code avatarUrl} — the {@code avatar} claim, an absolute URL pointing at the identity * provider's avatar image for the user. May be {@code null} if the claim is absent or blank. - *
        • {@code userName} — the {@code preferred_username} claim with a fallback chain - * ({@code preferred_username → email → sub → "user-"}) applied by {@code AuthService}. + *
        • {@code userName} — the {@code preferred_username} claim with a fallback chain ({@code + * preferred_username → email → sub → "user-"}) applied by {@code AuthService}. * Guaranteed non-null and non-blank for {@code AuthService}-produced records, so {@link * com.openelements.spring.base.services.user.UserEntity#getUserName()} can be populated * unconditionally on JIT login. - *
        • {@code externalId} — the stable IdP-side identifier. Mirrors {@code id} (the JWT - * {@code sub}) for IdPs that use the same value for OIDC {@code sub} and SCIM - * {@code externalId} — which covers Authentik, Okta, Entra ID, and Keycloak in default - * configurations. + *
        • {@code externalId} — the stable IdP-side identifier. Mirrors {@code id} (the JWT {@code + * sub}) for IdPs that use the same value for OIDC {@code sub} and SCIM {@code externalId} — + * which covers Authentik, Okta, Entra ID, and Keycloak in default configurations. *
        * * @param id the JWT {@code sub} claim, the stable subject identifier of the user * @param name the {@code name} claim, typically the user's display name, or {@code null} if absent * @param email the {@code email} claim, or {@code null} if not asserted by the identity provider - * @param avatarUrl an absolute URL to the identity provider's avatar image, or {@code null} if absent - * @param userName the resolved preferred username, guaranteed non-null and non-blank for - * {@code AuthService}-produced records + * @param avatarUrl an absolute URL to the identity provider's avatar image, or {@code null} if + * absent + * @param userName the resolved preferred username, guaranteed non-null and non-blank for {@code + * AuthService}-produced records * @param externalId the stable IdP-side identifier, mirroring {@code id} for common IdPs */ public record UserInformation( - String id, - String name, - String email, - String avatarUrl, - String userName, - String externalId) {} + String id, String name, String email, String avatarUrl, String userName, String externalId) {} diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/security/roles/Roles.java b/spring-services-core/src/main/java/com/openelements/spring/base/security/roles/Roles.java index 55934f2..d97dacf 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/security/roles/Roles.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/security/roles/Roles.java @@ -34,10 +34,10 @@ private Roles() {} /** * Role of a caller authenticated with an API key. Issued by {@code ApiKeyAuthenticationFilter}, - * never by the identity provider — it is the token's only authority. Because the JWT {@code roles} - * claim is mapped unfiltered, an identity-provider role literally named {@code API_KEY} would also - * surface under this name; the value therefore says which role the caller carries, not - * how the caller authenticated. + * never by the identity provider — it is the token's only authority. Because the JWT {@code + * roles} claim is mapped unfiltered, an identity-provider role literally named {@code API_KEY} + * would also surface under this name; the value therefore says which role the caller + * carries, not how the caller authenticated. */ public static final String ROLE_API_KEY = "API_KEY"; @@ -47,8 +47,8 @@ private Roles() {} * *

        Unlike {@link #ROLE_API_KEY}, this value cannot be wired to its producer: {@code * "ANONYMOUS"} is Spring Security's default anonymous authority, overridable by any consumer via - * {@code http.anonymous(a -> a.authorities(...))}. If a consumer reconfigures it, this constant no - * longer describes that application. + * {@code http.anonymous(a -> a.authorities(...))}. If a consumer reconfigures it, this constant + * no longer describes that application. */ public static final String ROLE_ANONYMOUS = "ANONYMOUS"; diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/apitoken/PrincipalDirectory.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/apitoken/PrincipalDirectory.java index 46544a8..846214a 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/apitoken/PrincipalDirectory.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/apitoken/PrincipalDirectory.java @@ -18,8 +18,8 @@ * default implementation ({@link * com.openelements.spring.base.services.user.UserEntityPrincipalDirectory}) has a contract to * implement before the full opaque-token module (spec 010) lands. Spec 010 will become the - * permanent owner of this port. Consumers who write their own implementation today should expect - * a one-line package change when 010 merges; the interface shape itself will not change. + * permanent owner of this port. Consumers who write their own implementation today should expect a + * one-line package change when 010 merges; the interface shape itself will not change. * *

        Backing stores. The default implementation is backed by {@code UserEntity} (the SCIM- * /JIT-fed local mirror). High-assurance deployments may swap in an implementation that calls the @@ -33,13 +33,11 @@ public interface PrincipalDirectory { /** * Resolves the current authorization state for a user reference. * - * @param subjectRef the IdP-side identifier stored in the token (typically the user's - * {@code externalId}, which mirrors the OIDC {@code sub} for IdPs that use the same value - * for both) + * @param subjectRef the IdP-side identifier stored in the token (typically the user's {@code + * externalId}, which mirrors the OIDC {@code sub} for IdPs that use the same value for both) * @return the resolved principal, or {@link Optional#empty()} if no such user exists */ - @NonNull - Optional resolveUser(@NonNull String subjectRef); + @NonNull Optional resolveUser(@NonNull String subjectRef); /** * The live authorization snapshot for a user at validation time. diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/apitoken/package-info.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/apitoken/package-info.java index 94fbf90..9e58224 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/apitoken/package-info.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/apitoken/package-info.java @@ -4,8 +4,8 @@ *

        This package currently contains only the {@link * com.openelements.spring.base.services.apitoken.PrincipalDirectory} port, shipped by spec 012 so * that the default implementation ({@code UserEntityPrincipalDirectory} in {@code services/user}) - * has a stable contract before spec 010 lands. When spec 010 (the full opaque-token module) - * merges, the port is preserved in place and joined by the remaining types ({@code - * ApiTokenEntity}, {@code ApiTokenService}, {@code ApiTokenIntrospector}, …). + * has a stable contract before spec 010 lands. When spec 010 (the full opaque-token module) merges, + * the port is preserved in place and joined by the remaining types ({@code ApiTokenEntity}, {@code + * ApiTokenService}, {@code ApiTokenIntrospector}, …). */ package com.openelements.spring.base.services.apitoken; diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserEntity.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserEntity.java index a79c78e..0b68408 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserEntity.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserEntity.java @@ -84,8 +84,8 @@ public UserEntity() {} * from the JWT {@code sub} claim. For interactively-provisioned users (the historical default) * this is always populated. * - * @return the subject identifier, or {@code null} for SCIM-pre-provisioned rows that have not - * yet seen an interactive login + * @return the subject identifier, or {@code null} for SCIM-pre-provisioned rows that have not yet + * seen an interactive login */ public String getSub() { return sub; @@ -103,13 +103,13 @@ public void setSub(final String sub) { /** * Returns the stable IdP-side identifier of this user. * - *

        For Authentik (and most IdPs that use the same value for OIDC {@code sub} and SCIM - * {@code externalId}), this mirrors {@link #getSub()} once the user has logged in interactively. - * Populated independently of {@code sub} when the row is created via SCIM provisioning, which - * is what makes correlation between SCIM-pre-provisioned and JIT-logged-in users possible. + *

        For Authentik (and most IdPs that use the same value for OIDC {@code sub} and SCIM {@code + * externalId}), this mirrors {@link #getSub()} once the user has logged in interactively. + * Populated independently of {@code sub} when the row is created via SCIM provisioning, which is + * what makes correlation between SCIM-pre-provisioned and JIT-logged-in users possible. * - * @return the IdP-side identifier, or {@code null} for users provisioned before the - * {@code externalId} column existed and not yet seen for an interactive login since + * @return the IdP-side identifier, or {@code null} for users provisioned before the {@code + * externalId} column existed and not yet seen for an interactive login since */ public String getExternalId() { return externalId; @@ -125,9 +125,9 @@ public void setExternalId(final String externalId) { } /** - * Returns the unique business-key handle of this user — typically the IdP's - * {@code preferred_username} claim, with a fallback chain ({@code email → sub → "user-"}) - * applied at JIT-login time to guarantee a non-null value. + * Returns the unique business-key handle of this user — typically the IdP's {@code + * preferred_username} claim, with a fallback chain ({@code email → sub → "user-"}) applied + * at JIT-login time to guarantee a non-null value. * * @return the user-name handle, never {@code null} for persisted entities */ @@ -145,9 +145,9 @@ public void setUserName(final String userName) { } /** - * Returns whether this user is active. An inactive user is rejected by every authentication - * path (JWT chain throws {@code AccessDeniedException}; opaque-token chain throws - * {@code BadOpaqueTokenException} via the {@code PrincipalDirectory} live check). + * Returns whether this user is active. An inactive user is rejected by every authentication path + * (JWT chain throws {@code AccessDeniedException}; opaque-token chain throws {@code + * BadOpaqueTokenException} via the {@code PrincipalDirectory} live check). * * @return {@code true} if the user is active, {@code false} otherwise */ @@ -165,9 +165,9 @@ public void setActive(final boolean active) { } /** - * Returns whether this user has been soft-deleted. A soft-deleted user is treated as absent by the - * SCIM surface (returned as {@code 404}) and excluded from listings, but the row is retained for - * referential integrity. + * Returns whether this user has been soft-deleted. A soft-deleted user is treated as absent by + * the SCIM surface (returned as {@code 404}) and excluded from listings, but the row is retained + * for referential integrity. * * @return {@code true} if the user has been soft-deleted, {@code false} otherwise */ diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserEntityPrincipalDirectory.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserEntityPrincipalDirectory.java index 8be5ac2..9932ca9 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserEntityPrincipalDirectory.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserEntityPrincipalDirectory.java @@ -9,8 +9,7 @@ import org.springframework.transaction.annotation.Transactional; /** - * Default {@link PrincipalDirectory} implementation, backed by the local {@link UserEntity} - * mirror. + * Default {@link PrincipalDirectory} implementation, backed by the local {@link UserEntity} mirror. * *

        Resolves a user's live authorization state from the database row for every opaque * token validation. The bridge is intentionally minimal in spec 012: @@ -25,12 +24,12 @@ * issuance, and SCIM uses {@code externalId} as the canonical IdP identifier. * * - *

        The directory deliberately does not filter inactive users out at this layer — it returns - * what it sees. The opaque-token introspector decides what to do with {@code active == false} - * (typically {@code BadOpaqueTokenException → 401 Unauthorized}). + *

        The directory deliberately does not filter inactive users out at this layer — it returns what + * it sees. The opaque-token introspector decides what to do with {@code active == false} (typically + * {@code BadOpaqueTokenException → 401 Unauthorized}). * - *

        The lookup runs in a read-only transaction so callers (the {@code OpaqueTokenIntrospector}) - * do not need their own transaction boundary. + *

        The lookup runs in a read-only transaction so callers (the {@code OpaqueTokenIntrospector}) do + * not need their own transaction boundary. */ @Component public class UserEntityPrincipalDirectory implements PrincipalDirectory { @@ -55,10 +54,6 @@ public UserEntityPrincipalDirectory(final UserRepository userRepository) { .map( user -> new ResolvedPrincipal( - user.getExternalId(), - user.isActive(), - Set.of(), - Set.of(), - user.getName())); + user.getExternalId(), user.isActive(), Set.of(), Set.of(), user.getName())); } } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserProvisioner.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserProvisioner.java index a980532..ac93a11 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserProvisioner.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserProvisioner.java @@ -15,21 +15,20 @@ * *

        For the full design rationale — why the {@code users.sub} unique index is the actual * coordinator across threads and instances, and how the three layers (DB lock, inner transaction, - * outer-tx retry) fit together — see the - * "Concurrency and first-login race recovery" - * section of this package's documentation. + * outer-tx retry) fit together — see the "Concurrency + * and first-login race recovery" section of this package's documentation. * *

        Why this is a separate bean, not a private method on {@code UserService}

        * - *

        Spring applies {@code @Transactional} via AOP proxies. A bean calling its own {@code - * @Transactional} method bypasses the proxy — the JVM resolves the call against the concrete - * class, not the proxy wrapper — so Spring never gets a chance to start an inner transaction. - * If this {@code provision(...)} method lived as a private (or even public) method on {@code + *

        Spring applies {@code @Transactional} via AOP proxies. A bean calling its own + * {@code @Transactional} method bypasses the proxy — the JVM resolves the call against the concrete + * class, not the proxy wrapper — so Spring never gets a chance to start an inner transaction. If + * this {@code provision(...)} method lived as a private (or even public) method on {@code * UserService} and were invoked through {@code this}, {@code REQUIRES_NEW} would silently degrade * into "reuse the caller's transaction", and the entire race-recovery scheme would collapse: the * constraint violation would mark the outer transaction as rollback-only, the recovery {@code - * findBySub} would fail with {@code "current transaction is aborted"}, and concurrent - * first-logins would surface 500 errors to callers. + * findBySub} would fail with {@code "current transaction is aborted"}, and concurrent first-logins + * would surface 500 errors to callers. * *

        Keeping the insert in this distinct bean guarantees that the call between {@code UserService} * and {@code UserProvisioner} goes through the {@code @Transactional} proxy, which is what makes @@ -52,8 +51,8 @@ public UserProvisioner(final UserRepository userRepository) { /** * Inserts a new {@link UserEntity} for the given {@link UserInformation} in a fresh transaction. * - *

        {@code saveAndFlush} forces the {@code INSERT} to be issued before this method returns, so - * a unique-constraint violation surfaces here as a {@link + *

        {@code saveAndFlush} forces the {@code INSERT} to be issued before this method returns, so a + * unique-constraint violation surfaces here as a {@link * org.springframework.dao.DataIntegrityViolationException} rather than at the caller's * transaction-commit time, where it would be unrecoverable. * diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserRepository.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserRepository.java index 7ae2007..e2f4beb 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserRepository.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserRepository.java @@ -31,8 +31,8 @@ public interface UserRepository extends EntityRepository { * Looks up a user by the unique business-key handle ({@code userName}). * *

        Used as the last-resort correlation step in the JIT-login flow, for the edge case where an - * IdP uses different identifiers for OIDC and SCIM (so neither {@code sub} nor {@code - * externalId} matches the pre-provisioned row). + * IdP uses different identifiers for OIDC and SCIM (so neither {@code sub} nor {@code externalId} + * matches the pre-provisioned row). * * @param userName the user-name handle * @return the matching user, or empty if no row carries this {@code userName} diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserService.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserService.java index 29d842e..e742ded 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserService.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/UserService.java @@ -33,232 +33,228 @@ @Transactional public class UserService extends AbstractDbBackedDataService { - private final Logger LOG = LoggerFactory.getLogger(UserService.class); + private final Logger LOG = LoggerFactory.getLogger(UserService.class); - private final UserRepository userRepository; + private final UserRepository userRepository; - private final AuthService authService; + private final AuthService authService; - private final UserProvisioner userProvisioner; + private final UserProvisioner userProvisioner; - /** - * Creates a new user service. - * - * @param userRepository the repository used to persist and look up users - * @param eventPublisher Spring's event publisher, used to broadcast lifecycle events - * @param authService the service used to resolve the current authenticated user - * @param userProvisioner the collaborator that inserts new users in a fresh transaction - */ - public UserService( - final UserRepository userRepository, - final ApplicationEventPublisher eventPublisher, - final AuthService authService, - final UserProvisioner userProvisioner) { - super(eventPublisher); - this.userRepository = Objects.requireNonNull(userRepository, "userRepository must not be null"); - this.authService = Objects.requireNonNull(authService, "authService must not be null"); - this.userProvisioner = - Objects.requireNonNull(userProvisioner, "userProvisioner must not be null"); - } - - /** - * Returns the managed {@link UserEntity} for the user that owns the current request. - * - *

        Resolves the local mirror through a three-tier lookup so that SCIM-pre-provisioned rows - * (with {@code externalId} or {@code userName} set but {@code sub} still {@code null}) are - * found and adopted on the first interactive login: - * - *

          - *
        1. {@code findBySub(jwt.sub)} — the historical fast path for already-known users. - *
        2. {@code findByExternalId(jwt.sub)} — picks up SCIM-pre-provisioned rows that share the - * IdP-side identifier with the JWT {@code sub}. - *
        3. {@code findByUserName(jwt.preferredUsername)} — last-resort correlation for IdPs that - * use different identifiers for OIDC and SCIM. - *
        - * - *

        If all three lookups miss, the row is created via {@link - * UserProvisioner#provision(UserInformation)} in its own {@code REQUIRES_NEW} transaction so - * that a concurrent first-login race can be caught and recovered without poisoning the outer - * transaction (see the package documentation's - * "Concurrency and first-login race recovery" - * section). - * - *

        After resolution the entity is checked for {@link UserEntity#isActive()}. A deactivated - * user causes an {@link AccessDeniedException} → HTTP {@code 403}. The check fires - * before any drift-sync writes, so a deactivated SCIM-pre-provisioned row cannot be - * accidentally bound to a {@code sub} via the JIT flow. - * - *

        Drift sync overwrites {@code name}, {@code email} and {@code avatarUrl} whenever the JWT - * claim disagrees with the persisted value. {@code sub}, {@code externalId} and {@code - * userName} are opportunistically backfilled only when currently {@code null} — they - * are stable identifiers and are not overwritten by later JWTs. - * - * @return the managed entity for the current user - * @throws IllegalStateException if no JWT is bound to the current request - * @throws AccessDeniedException if the resolved {@link UserEntity} has {@code active = false} - */ - public UserEntity getCurrentUserEntity() { - final UserInformation userInformation = - authService - .getUserInformation() - .orElseThrow( - () -> - new IllegalStateException( - "No JWT bound to current request — getCurrentUserEntity" - + " may only be called from JWT-authenticated request threads.")); + /** + * Creates a new user service. + * + * @param userRepository the repository used to persist and look up users + * @param eventPublisher Spring's event publisher, used to broadcast lifecycle events + * @param authService the service used to resolve the current authenticated user + * @param userProvisioner the collaborator that inserts new users in a fresh transaction + */ + public UserService( + final UserRepository userRepository, + final ApplicationEventPublisher eventPublisher, + final AuthService authService, + final UserProvisioner userProvisioner) { + super(eventPublisher); + this.userRepository = Objects.requireNonNull(userRepository, "userRepository must not be null"); + this.authService = Objects.requireNonNull(authService, "authService must not be null"); + this.userProvisioner = + Objects.requireNonNull(userProvisioner, "userProvisioner must not be null"); + } - final Optional existing = - userRepository - .findBySub(userInformation.id()) - .or(() -> userRepository.findByExternalId(userInformation.externalId())) - .or(() -> userRepository.findByUserName(userInformation.userName())); + /** + * Returns the managed {@link UserEntity} for the user that owns the current request. + * + *

        Resolves the local mirror through a three-tier lookup so that SCIM-pre-provisioned rows + * (with {@code externalId} or {@code userName} set but {@code sub} still {@code null}) are found + * and adopted on the first interactive login: + * + *

          + *
        1. {@code findBySub(jwt.sub)} — the historical fast path for already-known users. + *
        2. {@code findByExternalId(jwt.sub)} — picks up SCIM-pre-provisioned rows that share the + * IdP-side identifier with the JWT {@code sub}. + *
        3. {@code findByUserName(jwt.preferredUsername)} — last-resort correlation for IdPs that use + * different identifiers for OIDC and SCIM. + *
        + * + *

        If all three lookups miss, the row is created via {@link + * UserProvisioner#provision(UserInformation)} in its own {@code REQUIRES_NEW} transaction so that + * a concurrent first-login race can be caught and recovered without poisoning the outer + * transaction (see the package documentation's "Concurrency and first-login race recovery" + * section). + * + *

        After resolution the entity is checked for {@link UserEntity#isActive()}. A deactivated user + * causes an {@link AccessDeniedException} → HTTP {@code 403}. The check fires before any + * drift-sync writes, so a deactivated SCIM-pre-provisioned row cannot be accidentally bound to a + * {@code sub} via the JIT flow. + * + *

        Drift sync overwrites {@code name}, {@code email} and {@code avatarUrl} whenever the JWT + * claim disagrees with the persisted value. {@code sub}, {@code externalId} and {@code userName} + * are opportunistically backfilled only when currently {@code null} — they are stable + * identifiers and are not overwritten by later JWTs. + * + * @return the managed entity for the current user + * @throws IllegalStateException if no JWT is bound to the current request + * @throws AccessDeniedException if the resolved {@link UserEntity} has {@code active = false} + */ + public UserEntity getCurrentUserEntity() { + final UserInformation userInformation = + authService + .getUserInformation() + .orElseThrow( + () -> + new IllegalStateException( + "No JWT bound to current request — getCurrentUserEntity" + + " may only be called from JWT-authenticated request threads.")); - if (existing.isPresent()) { - final UserEntity user = existing.get(); - requireUnambiguousMatch(user, userInformation); - requireActive(user); - return syncDriftAndBackfill(user, userInformation); - } + final Optional existing = + userRepository + .findBySub(userInformation.id()) + .or(() -> userRepository.findByExternalId(userInformation.externalId())) + .or(() -> userRepository.findByUserName(userInformation.userName())); - try { - LOG.debug("First login for user {}", userInformation.id()); - final UserEntity provisioned = userProvisioner.provision(userInformation); - requireActive(provisioned); - return provisioned; - } catch (final DataIntegrityViolationException e) { - LOG.warn( - "Concurrent first-login for user {} — re-fetching the row another thread" - + " inserted.", - userInformation.id()); - final UserEntity recovered = - userRepository - .findBySub(userInformation.id()) - .orElseThrow( - () -> new IllegalStateException("Error in storing user entity", e)); - requireActive(recovered); - return recovered; - } + if (existing.isPresent()) { + final UserEntity user = existing.get(); + requireUnambiguousMatch(user, userInformation); + requireActive(user); + return syncDriftAndBackfill(user, userInformation); } - /** - * Drift-syncs the volatile claims ({@code name}, {@code email}, {@code avatarUrl}) and - * back-fills the stable identifiers ({@code sub}, {@code externalId}, {@code userName}) only - * when they are currently {@code null} on the persisted row. - * - *

        Saves the entity in one call when any field changed; otherwise the existing instance is - * returned untouched. - */ - private UserEntity syncDriftAndBackfill( - final UserEntity user, final UserInformation info) { - boolean changed = false; - - if (!Objects.equals(info.name(), user.getName())) { - user.setName(info.name()); - changed = true; - } - if (!Objects.equals(info.email(), user.getEmail())) { - user.setEmail(info.email()); - changed = true; - } - if (!Objects.equals(info.avatarUrl(), user.getAvatarUrl())) { - user.setAvatarUrl(info.avatarUrl()); - changed = true; - } + try { + LOG.debug("First login for user {}", userInformation.id()); + final UserEntity provisioned = userProvisioner.provision(userInformation); + requireActive(provisioned); + return provisioned; + } catch (final DataIntegrityViolationException e) { + LOG.warn( + "Concurrent first-login for user {} — re-fetching the row another thread" + " inserted.", + userInformation.id()); + final UserEntity recovered = + userRepository + .findBySub(userInformation.id()) + .orElseThrow(() -> new IllegalStateException("Error in storing user entity", e)); + requireActive(recovered); + return recovered; + } + } - // Stable identifiers — backfill only, never overwrite. - if (user.getSub() == null && info.id() != null) { - user.setSub(info.id()); - changed = true; - } - if (user.getExternalId() == null && info.externalId() != null) { - user.setExternalId(info.externalId()); - changed = true; - } - if (user.getUserName() == null && info.userName() != null) { - user.setUserName(info.userName()); - changed = true; - } + /** + * Drift-syncs the volatile claims ({@code name}, {@code email}, {@code avatarUrl}) and back-fills + * the stable identifiers ({@code sub}, {@code externalId}, {@code userName}) only when they are + * currently {@code null} on the persisted row. + * + *

        Saves the entity in one call when any field changed; otherwise the existing instance is + * returned untouched. + */ + private UserEntity syncDriftAndBackfill(final UserEntity user, final UserInformation info) { + boolean changed = false; - if (changed) { - LOG.debug("Updating user {}: {}", user.id(), user); - return userRepository.save(user); - } - return user; + if (!Objects.equals(info.name(), user.getName())) { + user.setName(info.name()); + changed = true; } - - private static void requireActive(final UserEntity user) { - if (!user.isActive()) { - throw new AccessDeniedException("User account is disabled"); - } + if (!Objects.equals(info.email(), user.getEmail())) { + user.setEmail(info.email()); + changed = true; } - - /** - * Guards against fallback-lookup mis-correlation. A row whose {@code sub} is already set to - * a value different from the JWT's {@code sub} cannot be the same human — even if the - * {@code externalId} or {@code userName} lookup matched. The most common trigger is two - * users sharing the same email, both falling back to {@code email} as their {@code userName} - * because the IdP omitted {@code preferred_username}. - */ - private static void requireUnambiguousMatch( - final UserEntity user, final UserInformation info) { - if (user.getSub() != null && !user.getSub().equals(info.id())) { - throw new IllegalStateException( - "Matched UserEntity " - + user.id() - + " has sub=" - + user.getSub() - + " but the request carries sub=" - + info.id() - + ". This indicates two distinct identities collided on externalId or" - + " userName — typically because the IdP omitted preferred_username and two" - + " users share the same email fallback. The IdP must assert" - + " preferred_username to disambiguate."); - } + if (!Objects.equals(info.avatarUrl(), user.getAvatarUrl())) { + user.setAvatarUrl(info.avatarUrl()); + changed = true; } - /** - * Returns the profile of the user that owns the current request. - * - *

        Provisions the local mirror on first access and refreshes the cached {@code name}, {@code - * email} and {@code avatarUrl} fields from the JWT claims if they have drifted. - * - * @return the current user's profile - * @throws IllegalStateException if no JWT is bound to the current request - */ - public UserDto getCurrentUser() { - return UserDto.fromEntity(getCurrentUserEntity()); + // Stable identifiers — backfill only, never overwrite. + if (user.getSub() == null && info.id() != null) { + user.setSub(info.id()); + changed = true; } - - @Override - protected @NonNull UserEntity createDetachedEntity() { - return new UserEntity(); + if (user.getExternalId() == null && info.externalId() != null) { + user.setExternalId(info.externalId()); + changed = true; } - - @Override - protected void preSave(@NonNull UserDto data) { - throw new IllegalStateException( - "User data should never be changed since it is based on external system"); + if (user.getUserName() == null && info.userName() != null) { + user.setUserName(info.userName()); + changed = true; } - @Override - protected void updateEntity(@NonNull UserEntity entity, @NonNull UserDto data) { - entity.setName(data.name()); - entity.setEmail(data.email()); + if (changed) { + LOG.debug("Updating user {}: {}", user.id(), user); + return userRepository.save(user); } + return user; + } - @Override - protected @NonNull UserDto toData(@NonNull UserEntity entity) { - return new UserDto( - entity.id(), - entity.getName(), - entity.getEmail(), - entity.getAvatarUrl(), - entity.getCreatedAt(), - entity.getUpdatedAt()); + private static void requireActive(final UserEntity user) { + if (!user.isActive()) { + throw new AccessDeniedException("User account is disabled"); } + } - @Override - protected @NonNull EntityRepository getRepository() { - return userRepository; + /** + * Guards against fallback-lookup mis-correlation. A row whose {@code sub} is already set to a + * value different from the JWT's {@code sub} cannot be the same human — even if the {@code + * externalId} or {@code userName} lookup matched. The most common trigger is two users sharing + * the same email, both falling back to {@code email} as their {@code userName} because the IdP + * omitted {@code preferred_username}. + */ + private static void requireUnambiguousMatch(final UserEntity user, final UserInformation info) { + if (user.getSub() != null && !user.getSub().equals(info.id())) { + throw new IllegalStateException( + "Matched UserEntity " + + user.id() + + " has sub=" + + user.getSub() + + " but the request carries sub=" + + info.id() + + ". This indicates two distinct identities collided on externalId or" + + " userName — typically because the IdP omitted preferred_username and two" + + " users share the same email fallback. The IdP must assert" + + " preferred_username to disambiguate."); } + } + + /** + * Returns the profile of the user that owns the current request. + * + *

        Provisions the local mirror on first access and refreshes the cached {@code name}, {@code + * email} and {@code avatarUrl} fields from the JWT claims if they have drifted. + * + * @return the current user's profile + * @throws IllegalStateException if no JWT is bound to the current request + */ + public UserDto getCurrentUser() { + return UserDto.fromEntity(getCurrentUserEntity()); + } + + @Override + protected @NonNull UserEntity createDetachedEntity() { + return new UserEntity(); + } + + @Override + protected void preSave(@NonNull UserDto data) { + throw new IllegalStateException( + "User data should never be changed since it is based on external system"); + } + + @Override + protected void updateEntity(@NonNull UserEntity entity, @NonNull UserDto data) { + entity.setName(data.name()); + entity.setEmail(data.email()); + } + + @Override + protected @NonNull UserDto toData(@NonNull UserEntity entity) { + return new UserDto( + entity.id(), + entity.getName(), + entity.getEmail(), + entity.getAvatarUrl(), + entity.getCreatedAt(), + entity.getUpdatedAt()); + } + + @Override + protected @NonNull EntityRepository getRepository() { + return userRepository; + } } diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/package-info.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/package-info.java index a77d094..e0a2f8e 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/user/package-info.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/user/package-info.java @@ -5,9 +5,9 @@ *

        The platform deliberately does not own credentials — authentication is handled entirely by an * external OAuth2 provider via JWT. This package persists the subset of information about a user * that the application itself needs to attach to domain data (display name, email, avatar image) - * plus the three identifiers required for SCIM 2.0 alignment: {@code sub} (OIDC subject, - * nullable to allow SCIM-pre-provisioning), {@code externalId} (stable IdP-side id), and - * {@code userName} (RFC 7643 unique business key). + * plus the three identifiers required for SCIM 2.0 alignment: {@code sub} (OIDC subject, nullable + * to allow SCIM-pre-provisioning), {@code externalId} (stable IdP-side id), and {@code userName} + * (RFC 7643 unique business key). * *

        Lifecycle

        * @@ -15,38 +15,38 @@ *
      • The {@link com.openelements.spring.base.services.user.UserEntity} for a given user is * resolved on first access by {@link * com.openelements.spring.base.services.user.UserService#getCurrentUser()} via a three-tier - * lookup: {@code findBySub → findByExternalId → findByUserName → provision}. The chain - * lets a JIT-login adopt a row that SCIM provisioned ahead of time (with {@code - * externalId} or {@code userName} but no {@code sub} yet). + * lookup: {@code findBySub → findByExternalId → findByUserName → provision}. The chain lets a + * JIT-login adopt a row that SCIM provisioned ahead of time (with {@code externalId} or + * {@code userName} but no {@code sub} yet). *
      • If the JWT's {@code name}, {@code email} or {@code avatar} claim has changed since the last * call, the local entity is drift-synced (overwrite). {@code sub}, {@code externalId} and - * {@code userName} are opportunistically backfilled only when currently - * {@code null} — they are stable identifiers and never overwritten by later JWTs. + * {@code userName} are opportunistically backfilled only when currently {@code null} + * — they are stable identifiers and never overwritten by later JWTs. *
      • The avatar URL is stored as-is and points directly at the identity provider's image * endpoint — the library never proxies, caches or downloads it. *
      • {@link com.openelements.spring.base.services.user.UserEntity#isActive()} gates every - * authentication path. A deactivated user triggers {@code AccessDeniedException} on the - * JWT chain and {@code BadOpaqueTokenException} via the {@link + * authentication path. A deactivated user triggers {@code AccessDeniedException} on the JWT + * chain and {@code BadOpaqueTokenException} via the {@link * com.openelements.spring.base.services.apitoken.PrincipalDirectory} on the opaque-token * chain. * * *

        Disambiguation guard

        * - *

        The {@code findByUserName} fallback step can mis-correlate when two distinct users share - * the same email-as-userName fallback (because the IdP omitted {@code preferred_username}). - * {@code UserService} guards against silent identity merger: if the matched row's {@code sub} - * differs from the JWT's {@code sub}, an {@link IllegalStateException} is thrown loudly with a - * remediation hint pointing at the IdP's {@code preferred_username} configuration. + *

        The {@code findByUserName} fallback step can mis-correlate when two distinct users share the + * same email-as-userName fallback (because the IdP omitted {@code preferred_username}). {@code + * UserService} guards against silent identity merger: if the matched row's {@code sub} differs from + * the JWT's {@code sub}, an {@link IllegalStateException} is thrown loudly with a remediation hint + * pointing at the IdP's {@code preferred_username} configuration. * *

        {@code PrincipalDirectory} bridge

        * *

        {@link com.openelements.spring.base.services.user.UserEntityPrincipalDirectory} adapts the * local {@code UserEntity} to the {@link - * com.openelements.spring.base.services.apitoken.PrincipalDirectory} port consumed by the - * upcoming opaque-token validation layer (spec 010). It queries by {@code externalId} and - * returns the live {@code active} flag plus the display name. Roles and groups currently come - * back empty — group/role modelling lands with the SCIM-Provider follow-up spec. + * com.openelements.spring.base.services.apitoken.PrincipalDirectory} port consumed by the upcoming + * opaque-token validation layer (spec 010). It queries by {@code externalId} and returns the live + * {@code active} flag plus the display name. Roles and groups currently come back empty — + * group/role modelling lands with the SCIM-Provider follow-up spec. * *

        Concurrency and first-login race recovery

        * @@ -54,8 +54,8 @@ * moment — typical in modern frontends that fire several authenticated API calls in parallel on * page load, and unavoidable in horizontally-scaled deployments where two instances receive the * same user's first request from a load balancer. The design must produce exactly one - * {@code UserEntity} row and let every concurrent caller receive a managed reference to it, - * without serialising the hot path of repeat logins. + * {@code UserEntity} row and let every concurrent caller receive a managed reference to it, without + * serialising the hot path of repeat logins. * *

        The mechanism in three layers

        * @@ -74,30 +74,30 @@ * suspends the caller's transaction, opens a fresh inner one, and calls {@link * org.springframework.data.jpa.repository.JpaRepository#saveAndFlush(Object)} so that any * unique-constraint violation surfaces here, inside the inner transaction. If the - * inner transaction loses the race, only it is rolled back. The caller's outer transaction - * — held by {@code UserService.getCurrentUserEntity()} — is untouched, still alive, still + * inner transaction loses the race, only it is rolled back. The caller's outer transaction — + * held by {@code UserService.getCurrentUserEntity()} — is untouched, still alive, still * commit-eligible. *
      • {@code UserService} catches the {@code DataIntegrityViolationException} and retries - * {@code findBySub}. Because the failure was scoped to the inner transaction, Spring - * does not mark the outer transaction as rollback-only, and Postgres does not put - * the outer connection into the "current transaction is aborted" state. The retry runs - * normally and finds the row that the winning concurrent {@code INSERT} just committed. + * {@code findBySub}. Because the failure was scoped to the inner transaction, Spring does + * not mark the outer transaction as rollback-only, and Postgres does not put the + * outer connection into the "current transaction is aborted" state. The retry runs normally + * and finds the row that the winning concurrent {@code INSERT} just committed. * * *

        The result: with N concurrent first-login requests for the same subject, exactly one {@code - * INSERT} commits, the other N−1 each cost one extra round-trip to the DB to read the winner's - * row. Repeat-login traffic does not pay anything for this safety — only the very first request - * for a previously-unknown subject takes the {@code REQUIRES_NEW} hop. + * INSERT} commits, the other N−1 each cost one extra round-trip to the DB to read the winner's row. + * Repeat-login traffic does not pay anything for this safety — only the very first request for a + * previously-unknown subject takes the {@code REQUIRES_NEW} hop. * *

        Why {@code UserProvisioner} must be a separate Spring bean

        * *

        Spring applies {@code @Transactional} via AOP proxies: when one bean calls another bean's - * {@code @Transactional} method, the call goes through the dynamic proxy, which is what starts - * the new transaction. A bean calling its own {@code @Transactional} method (e.g. {@code - * this.provision(...)}) bypasses the proxy entirely — the call resolves directly against the - * class instance, so Spring never gets a chance to start an inner transaction. {@code - * REQUIRES_NEW} would silently degrade into "reuse the existing transaction", defeating the - * whole isolation argument above. + * {@code @Transactional} method, the call goes through the dynamic proxy, which is what starts the + * new transaction. A bean calling its own {@code @Transactional} method (e.g. {@code + * this.provision(...)}) bypasses the proxy entirely — the call resolves directly against the class + * instance, so Spring never gets a chance to start an inner transaction. {@code REQUIRES_NEW} would + * silently degrade into "reuse the existing transaction", defeating the whole isolation argument + * above. * *

        That is why the insert lives in {@code UserProvisioner}, not as a private method on {@code * UserService}. The split is not a stylistic choice — it is what makes the {@code REQUIRES_NEW} @@ -107,10 +107,10 @@ * *

        The {@code REQUIRES_NEW} hop temporarily holds two connections per provisioning thread (one * for the suspended outer transaction, one for the inner). Under sustained first-login bursts — - * unusual in steady state, possible during a coordinated bulk-onboarding — the HikariCP pool - * needs enough headroom. The library's integration tests run with {@code - * spring.datasource.hikari.maximum-pool-size=30}; production deployments should size the pool - * with the same arithmetic in mind: {@code peak_concurrent_first_logins * 2 + steady-state - * traffic} should fit. + * unusual in steady state, possible during a coordinated bulk-onboarding — the HikariCP pool needs + * enough headroom. The library's integration tests run with {@code + * spring.datasource.hikari.maximum-pool-size=30}; production deployments should size the pool with + * the same arithmetic in mind: {@code peak_concurrent_first_logins * 2 + steady-state traffic} + * should fit. */ package com.openelements.spring.base.services.user; diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/services/webhook/data/WebhookEntity.java b/spring-services-core/src/main/java/com/openelements/spring/base/services/webhook/data/WebhookEntity.java index da4d295..0af2b0b 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/services/webhook/data/WebhookEntity.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/services/webhook/data/WebhookEntity.java @@ -71,8 +71,8 @@ public void setActive(final boolean active) { /** * Returns the HTTP status of the last delivery attempt. * - * @return the last status ({@code null} if never called, {@code 0} for a connection error, - * {@code -1} for a timeout) + * @return the last status ({@code null} if never called, {@code 0} for a connection error, {@code + * -1} for a timeout) */ public Integer getLastStatus() { return lastStatus; diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceAutoConfiguration.java b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceAutoConfiguration.java index 1bec1e3..f993709 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceAutoConfiguration.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceAutoConfiguration.java @@ -19,9 +19,9 @@ * problem details off keeps {@code traceId} in its log MDC. * *

        The filter is registered with an order of {@link - * SecurityFilterProperties#DEFAULT_FILTER_ORDER} {@code - 1} so it runs before every Spring Security - * filter chain. Without that, a {@code 401} written by an authentication entry point would be the - * one response with no trace ID. + * SecurityFilterProperties#DEFAULT_FILTER_ORDER} {@code - 1} so it runs before every Spring + * Security filter chain. Without that, a {@code 401} written by an authentication entry point would + * be the one response with no trace ID. */ @AutoConfiguration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceContext.java b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceContext.java index e3de510..1f9f7e6 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceContext.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceContext.java @@ -15,7 +15,8 @@ * stable for the rest of the request. That happens when the filter did not run: a standalone {@code * MockMvc} setup, or a servlet container that dispatches outside the filter chain. The fallback * applies the same rules as the default resolver, but it does not use an - * application-supplied {@link TraceIdResolver} bean — that one is only reachable through the filter. + * application-supplied {@link TraceIdResolver} bean — that one is only reachable through the + * filter. * *

        The MDC key is {@code traceId}; add {@code %X{traceId}} to a log pattern to see it. */ diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceContextFilter.java b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceContextFilter.java index 9759676..f371130 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceContextFilter.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceContextFilter.java @@ -12,14 +12,14 @@ /** * Publishes the request's trace ID as a request attribute and in the SLF4J {@link MDC}. * - *

        Registered with an order just ahead of Spring Security's filter chain, so a {@code 401} written - * by an authentication entry point already carries the ID, and so does every log line produced while - * the request is being authenticated. + *

        Registered with an order just ahead of Spring Security's filter chain, so a {@code 401} + * written by an authentication entry point already carries the ID, and so does every log line + * produced while the request is being authenticated. * - *

        The filter runs on {@code ERROR} dispatches as well, because that is where container errors and - * {@code sendError(...)} from a filter are rendered. It does not re-resolve there: the attribute - * survives the dispatch, so the error response reports the same ID as the request that produced it. - * The MDC, in contrast, is thread-local and is restored for the dispatch. + *

        The filter runs on {@code ERROR} dispatches as well, because that is where container errors + * and {@code sendError(...)} from a filter are rendered. It does not re-resolve there: the + * attribute survives the dispatch, so the error response reports the same ID as the request that + * produced it. The MDC, in contrast, is thread-local and is restored for the dispatch. * *

        The MDC entry is removed in a {@code finally} block. Servlet containers pool threads, so a * leaked entry would attach a stale ID to an unrelated request. diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceIdResolver.java b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceIdResolver.java index 4c5a7b3..7da1ff8 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceIdResolver.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceIdResolver.java @@ -5,15 +5,15 @@ /** * Determines the trace ID of a request. * - *

        The trace ID correlates a response with the log lines written while the request was handled. It - * appears as the {@code traceId} member of every RFC 9457 problem produced by {@code + *

        The trace ID correlates a response with the log lines written while the request was handled. + * It appears as the {@code traceId} member of every RFC 9457 problem produced by {@code * com.openelements.spring.base.problem} and in the SLF4J {@link org.slf4j.MDC} under the key {@code * traceId} for the duration of the request. * *

        The default implementation takes the trace-id field of a valid W3C {@code traceparent} header - * and generates a random one otherwise. An application replaces it by declaring its own bean of this - * type — for example to read the ID from a Micrometer {@code Tracer}, or to refuse IDs chosen by an - * untrusted client. + * and generates a random one otherwise. An application replaces it by declaring its own bean of + * this type — for example to read the ID from a Micrometer {@code Tracer}, or to refuse IDs chosen + * by an untrusted client. * *

        Implementations must return 32 lowercase hexadecimal characters that are not all * zero. That is the trace-id format of the W3C Trace Context specification, and the format diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceParentTraceIdResolver.java b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceParentTraceIdResolver.java index 17f3568..621e9ce 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceParentTraceIdResolver.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/trace/TraceParentTraceIdResolver.java @@ -29,9 +29,9 @@ * specification requires of a Level 1 implementation. * * - *

        Uppercase hexadecimal is rejected rather than lowercased: the specification mandates lowercase, - * and silently accepting another spelling would make two callers with the same logical ID produce - * two different {@code traceId} values. + *

        Uppercase hexadecimal is rejected rather than lowercased: the specification mandates + * lowercase, and silently accepting another spelling would make two callers with the same logical + * ID produce two different {@code traceId} values. * *

        When the header is absent or rejected, the ID is generated from 16 bytes of {@link * SecureRandom} and rendered as lowercase hex. The (vanishingly unlikely) all-zero draw is rejected diff --git a/spring-services-core/src/main/java/com/openelements/spring/base/trace/package-info.java b/spring-services-core/src/main/java/com/openelements/spring/base/trace/package-info.java index 76e438d..32dd9ff 100644 --- a/spring-services-core/src/main/java/com/openelements/spring/base/trace/package-info.java +++ b/spring-services-core/src/main/java/com/openelements/spring/base/trace/package-info.java @@ -1,10 +1,11 @@ /** * The trace ID of a request. * - *

        A trace ID ties a response to the log lines written while the request was handled. This package - * contributes the minimum needed for that: resolve one ID per request, publish it as a request - * attribute and in the SLF4J {@link org.slf4j.MDC} under {@code traceId}, and let anything that - * writes a response read it back through {@link com.openelements.spring.base.trace.TraceContext}. + *

        A trace ID ties a response to the log lines written while the request was handled. This + * package contributes the minimum needed for that: resolve one ID per request, publish it as a + * request attribute and in the SLF4J {@link org.slf4j.MDC} under {@code traceId}, and let anything + * that writes a response read it back through {@link + * com.openelements.spring.base.trace.TraceContext}. * *

        The ID ends up in the {@code traceId} member of every RFC 9457 problem produced by {@link * com.openelements.spring.base.problem}. The two packages are otherwise independent: the trace diff --git a/spring-services-core/src/test/java/com/example/app/Order.java b/spring-services-core/src/test/java/com/example/app/Order.java index bf2247e..5e0b338 100644 --- a/spring-services-core/src/test/java/com/example/app/Order.java +++ b/spring-services-core/src/test/java/com/example/app/Order.java @@ -10,9 +10,9 @@ /** * A consumer application's own JPA entity, deliberately placed in a package unrelated to the - * library ({@code com.example.app}) and mapped to the default schema — not - * {@code oe_spring_services}. It exists only to prove that the library's auto-configuration does - * not suppress the application's own entity scan. + * library ({@code com.example.app}) and mapped to the default schema — not {@code + * oe_spring_services}. It exists only to prove that the library's auto-configuration does not + * suppress the application's own entity scan. */ @Entity @Table(name = "orders") diff --git a/spring-services-core/src/test/java/com/example/app/StarterAutoConfigurationIntegrationTest.java b/spring-services-core/src/test/java/com/example/app/StarterAutoConfigurationIntegrationTest.java index 616089d..c77d46b 100644 --- a/spring-services-core/src/test/java/com/example/app/StarterAutoConfigurationIntegrationTest.java +++ b/spring-services-core/src/test/java/com/example/app/StarterAutoConfigurationIntegrationTest.java @@ -19,10 +19,10 @@ * Binding acceptance gate for the Spring Boot starter (spec 013). * *

        Boots {@link StarterTestApp} — a consumer application in {@code com.example.app} that declares - * no {@code @Import}, {@code @EntityScan}, or {@code @EnableJpaRepositories} — with - * only the library on the classpath. It then asserts that both the application's own - * {@link OrderRepository}/{@link Order} and the library's {@link UserRepository} and feature - * beans resolve under one persistence unit. + * no {@code @Import}, {@code @EntityScan}, or {@code @EnableJpaRepositories} — + * with only the library on the classpath. It then asserts that both the application's own + * {@link OrderRepository}/{@link Order} and the library's {@link UserRepository} and + * feature beans resolve under one persistence unit. * *

        This is the proof that {@code AutoConfigurationPackages.register} plus * {@code @AutoConfigureBefore(HibernateJpaAutoConfiguration, DataJpaRepositoriesAutoConfiguration)} @@ -42,7 +42,8 @@ class StarterAutoConfigurationIntegrationTest { @Autowired private UserService userService; @Test - @DisplayName("The application's own entity and repository are discovered and usable (default scan intact)") + @DisplayName( + "The application's own entity and repository are discovered and usable (default scan intact)") void applicationOwnPersistenceResolves() { final Order order = new Order(); order.setDescription("first order"); @@ -58,7 +59,8 @@ void applicationOwnPersistenceResolves() { } @Test - @DisplayName("The library's repositories and feature beans are wired by the starter alone (no @Import)") + @DisplayName( + "The library's repositories and feature beans are wired by the starter alone (no @Import)") void libraryPersistenceAndBeansResolve() { // The library repository is injectable... assertThat(userRepository).isNotNull(); diff --git a/spring-services-core/src/test/java/com/example/app/StarterTestApp.java b/spring-services-core/src/test/java/com/example/app/StarterTestApp.java index 741475e..12f06d9 100644 --- a/spring-services-core/src/test/java/com/example/app/StarterTestApp.java +++ b/spring-services-core/src/test/java/com/example/app/StarterTestApp.java @@ -6,13 +6,13 @@ * A minimal consumer application used to prove zero-config starter behaviour. * *

        Crucially it declares no {@code @Import(FullSpringServiceConfig.class)}, no - * {@code @EntityScan}, and no {@code @EnableJpaRepositories}, and it does not point - * {@code scanBasePackages} at the library. The default {@code @SpringBootApplication} behaviour - * registers only this package ({@code com.example.app}) via {@code @AutoConfigurationPackage}. The - * library's {@code SpringServicesCoreAutoConfiguration} must additively register - * {@code com.openelements.spring.base} so that both the application's and the library's entities and - * repositories are discovered — which is exactly what {@link StarterAutoConfigurationIntegrationTest} - * asserts. + * {@code @EntityScan}, and no {@code @EnableJpaRepositories}, and it does not point {@code + * scanBasePackages} at the library. The default {@code @SpringBootApplication} behaviour registers + * only this package ({@code com.example.app}) via {@code @AutoConfigurationPackage}. The library's + * {@code SpringServicesCoreAutoConfiguration} must additively register {@code + * com.openelements.spring.base} so that both the application's and the library's entities and + * repositories are discovered — which is exactly what {@link + * StarterAutoConfigurationIntegrationTest} asserts. */ @SpringBootApplication public class StarterTestApp {} diff --git a/spring-services-core/src/test/java/com/example/explicitapp/ExplicitImportIntegrationTest.java b/spring-services-core/src/test/java/com/example/explicitapp/ExplicitImportIntegrationTest.java index f436b1b..12271f5 100644 --- a/spring-services-core/src/test/java/com/example/explicitapp/ExplicitImportIntegrationTest.java +++ b/spring-services-core/src/test/java/com/example/explicitapp/ExplicitImportIntegrationTest.java @@ -32,7 +32,8 @@ class ExplicitImportIntegrationTest { @Autowired private UserService userService; @Test - @DisplayName("Explicit @Import(FullSpringServiceConfig) wires the library with no duplicate beans") + @DisplayName( + "Explicit @Import(FullSpringServiceConfig) wires the library with no duplicate beans") void explicitImportWiresLibrary() { assertThat(userService).isNotNull(); assertThat(userRepository).isNotNull(); diff --git a/spring-services-core/src/test/java/com/example/explicitapp/ExplicitImportTestApp.java b/spring-services-core/src/test/java/com/example/explicitapp/ExplicitImportTestApp.java index d2f5973..64090d4 100644 --- a/spring-services-core/src/test/java/com/example/explicitapp/ExplicitImportTestApp.java +++ b/spring-services-core/src/test/java/com/example/explicitapp/ExplicitImportTestApp.java @@ -10,8 +10,8 @@ /** * A consumer application that wires the library the old, explicit way: the Spring Boot - * starter ({@link SpringServicesCoreAutoConfiguration}) is excluded, and the library is brought in via - * {@code @Import(FullSpringServiceConfig.class)} plus explicit {@code @EntityScan} / + * starter ({@link SpringServicesCoreAutoConfiguration}) is excluded, and the library is brought in + * via {@code @Import(FullSpringServiceConfig.class)} plus explicit {@code @EntityScan} / * {@code @EnableJpaRepositories} over the library root. This proves the pre-starter integration * contract still works and produces no duplicate-bean errors. */ diff --git a/spring-services-core/src/test/java/com/example/problemapp/GovStackContractTest.java b/spring-services-core/src/test/java/com/example/problemapp/GovStackContractTest.java index 7c1f1ef..4dd09a2 100644 --- a/spring-services-core/src/test/java/com/example/problemapp/GovStackContractTest.java +++ b/spring-services-core/src/test/java/com/example/problemapp/GovStackContractTest.java @@ -13,7 +13,6 @@ import com.openelements.spring.base.trace.TraceAutoConfiguration; import jakarta.servlet.Filter; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.HexFormat; import java.util.List; @@ -33,7 +32,6 @@ import org.springframework.boot.webmvc.autoconfigure.error.ErrorMvcAutoConfiguration; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import tools.jackson.databind.JsonNode; @@ -146,22 +144,27 @@ void schemaProvenanceIsVerified() { /** * A negative control. A schema wired up wrongly — the {@code $ref} not resolving, the dialect not * applied, the body handed over as a string — validates everything and reports nothing, and every - * assertion in this class would then pass while proving nothing at all. These three bodies must be - * rejected, each for a different reason the GovStack schema actually states. + * assertion in this class would then pass while proving nothing at all. These three bodies must + * be rejected, each for a different reason the GovStack schema actually states. */ @Test @DisplayName("The schema rejects what it is supposed to reject") void schemaRejectsInvalidBodies() throws Exception { final String validType = TYPE_BASE + "not-found"; - assertThat(validate("Problem", JSON.readTree("{\"title\":\"x\",\"status\":404,\"traceId\":\"" + TRACE_ID + "\"}"))) + assertThat( + validate( + "Problem", + JSON.readTree("{\"title\":\"x\",\"status\":404,\"traceId\":\"" + TRACE_ID + "\"}"))) .as("a problem without 'type' must be rejected") .isNotEmpty(); assertThat( validate( "Problem", JSON.readTree( - "{\"type\":\"" + validType + "\",\"title\":\"x\",\"status\":404,\"traceId\":\"" + "{\"type\":\"" + + validType + + "\",\"title\":\"x\",\"status\":404,\"traceId\":\"" + "0".repeat(32) + "\"}"))) .as("an all-zero traceId must be rejected") @@ -170,7 +173,9 @@ void schemaRejectsInvalidBodies() throws Exception { validate( "ValidationProblem", JSON.readTree( - "{\"type\":\"" + validType + "\",\"title\":\"x\",\"status\":400,\"traceId\":\"" + "{\"type\":\"" + + validType + + "\",\"title\":\"x\",\"status\":400,\"traceId\":\"" + TRACE_ID + "\"}"))) .as("a ValidationProblem without 'errors' must be rejected") @@ -197,7 +202,9 @@ void everyErrorResponseValidates(final Scenario scenario) { final String schemaName = scenario.validationProblem() ? "ValidationProblem" : "Problem"; assertThat(validate(schemaName, body)) - .as("%s must satisfy the GovStack %s schema; body was %s", scenario.name(), schemaName, body) + .as( + "%s must satisfy the GovStack %s schema; body was %s", + scenario.name(), schemaName, body) .isEmpty(); }); } @@ -231,8 +238,8 @@ void noErrorResponseCarriesAForbiddenMember(final Scenario scenario) { } /** - * Guide §11.3: the trace ID of the response is the trace-id of the request's effective - * {@code traceparent}. Asserted on every scenario, because a writer that forgot to read {@link + * Guide §11.3: the trace ID of the response is the trace-id of the request's effective {@code + * traceparent}. Asserted on every scenario, because a writer that forgot to read {@link * com.openelements.spring.base.trace.TraceContext} would still emit a syntactically valid ID. */ @ParameterizedTest(name = "[{index}] {0}") @@ -272,12 +279,15 @@ static List scenarios() { new Scenario("bad-gateway", () -> get("/api/test/bad-gateway"), false), new Scenario("internal-error", () -> get("/api/test/boom"), false), new Scenario("problem-exception", () -> get("/api/test/problem"), false), - new Scenario("problem-without-detail", () -> get("/api/test/problem-without-detail"), false), - new Scenario("problem-with-extension", () -> get("/api/test/problem-with-extension"), false), + new Scenario( + "problem-without-detail", () -> get("/api/test/problem-without-detail"), false), + new Scenario( + "problem-with-extension", () -> get("/api/test/problem-with-extension"), false), new Scenario("problem-enum", () -> get("/api/test/problem-enum"), false), new Scenario("problem-5xx", () -> get("/api/test/problem-5xx"), false), new Scenario("http-418", () -> get("/api/test/status/418"), false), - new Scenario("invalid-parameter", () -> get("/api/test/param").param("size", "5000"), false), + new Scenario( + "invalid-parameter", () -> get("/api/test/param").param("size", "5000"), false), new Scenario( "invalid-parameter-path-and-header", () -> get("/api/test/path-and-header/0").header("X-Page", "0"), @@ -358,12 +368,14 @@ private static MockMvc mockMvc(final WebApplicationContext context) { * * @param name a readable name, used in failure messages * @param request builds the request that triggers the error - * @param validationProblem whether the response must satisfy {@code ValidationProblem} rather than - * {@code Problem} — true exactly for body-validation failures, which carry {@code errors} + * @param validationProblem whether the response must satisfy {@code ValidationProblem} rather + * than {@code Problem} — true exactly for body-validation failures, which carry {@code + * errors} */ record Scenario( String name, - java.util.function.Supplier + java.util.function.Supplier< + org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder> request, boolean validationProblem) { diff --git a/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsChainIntegrationTest.java b/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsChainIntegrationTest.java index 1834a0b..d5bf7e5 100644 --- a/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsChainIntegrationTest.java +++ b/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsChainIntegrationTest.java @@ -20,9 +20,9 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Primary; @@ -35,9 +35,9 @@ import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; +import org.testcontainers.junit.jupiter.Testcontainers; /** * Problem details through the library's real security filter chains. @@ -72,7 +72,10 @@ */ @SpringBootTest(classes = StarterTestApp.class) @AutoConfigureMockMvc -@Import({PostgresTestConfiguration.class, ProblemDetailsChainIntegrationTest.TestSecurityBeans.class}) +@Import({ + PostgresTestConfiguration.class, + ProblemDetailsChainIntegrationTest.TestSecurityBeans.class +}) @Testcontainers @ActiveProfiles("testcontainers") class ProblemDetailsChainIntegrationTest { @@ -125,8 +128,8 @@ void invalidApiKeyIsAProblem() throws Exception { } /** - * The external chain denies every write method declaratively. Before this feature the response was - * Spring Security's empty {@code 403}; now it carries a problem written by {@code + * The external chain denies every write method declaratively. Before this feature the response + * was Spring Security's empty {@code 403}; now it carries a problem written by {@code * ProblemAccessDeniedHandler}. */ @Test @@ -153,14 +156,15 @@ void methodSecurityDenialIsAProblem() throws Exception { .andExpect(content().contentType(PROBLEM_JSON)) .andExpect(jsonPath("$.type").value(BASE + "forbidden")) .andExpect(jsonPath("$.status").value(403)); - } + } /** * The deactivation gate is the one {@code 403} that originates in the library's own service layer * rather than in a Spring Security rule: {@code UserService.getCurrentUserEntity()} throws {@code - * AccessDeniedException} for a row with {@code active = false}. It reaches the client only because - * the exception is left to propagate to {@code ExceptionTranslationFilter} instead of being mapped - * in an {@code @ExceptionHandler} — so this is also the end-to-end proof of that decision. + * AccessDeniedException} for a row with {@code active = false}. It reaches the client only + * because the exception is left to propagate to {@code ExceptionTranslationFilter} instead of + * being mapped in an {@code @ExceptionHandler} — so this is also the end-to-end proof of that + * decision. */ @Test @DisplayName("[chain] A deactivated account is a 403 problem naming the reason") @@ -202,8 +206,8 @@ void applicationExceptionBehindTheChainIsAProblem() throws Exception { /** * The trace filter is registered with an order below {@code - * SecurityFilterProperties.DEFAULT_FILTER_ORDER} so that it has already run when an entry point writes a - * {@code 401}. Nothing but a request through the real chain can prove that. + * SecurityFilterProperties.DEFAULT_FILTER_ORDER} so that it has already run when an entry point + * writes a {@code 401}. Nothing but a request through the real chain can prove that. */ @Test @DisplayName("[chain] A 401 carries the trace ID of the incoming traceparent") @@ -227,10 +231,10 @@ void traceIdIsAvailableForForbidden() throws Exception { } /** - * Creates a real API key through {@link ApiKeyDataService#create(ApiKeyCreateDto)} so the external - * chain exercises the production hash-and-lookup path. {@code create(...)} resolves the current - * user from a JWT, so a JWT authentication is bound to the context for the duration of the call - * and cleared afterwards. + * Creates a real API key through {@link ApiKeyDataService#create(ApiKeyCreateDto)} so the + * external chain exercises the production hash-and-lookup path. {@code create(...)} resolves the + * current user from a JWT, so a JWT authentication is bound to the context for the duration of + * the call and cleared afterwards. */ private String createApiKey() { final Jwt jwt = diff --git a/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsDisabledWebTest.java b/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsDisabledWebTest.java index 2871b3e..6ac3c73 100644 --- a/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsDisabledWebTest.java +++ b/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsDisabledWebTest.java @@ -37,8 +37,8 @@ * *

        That turning the feature off is a complete rollback, not a partial one. An application that * cannot migrate its clients sets one property, and the library has to stop contributing error - * handling altogether: no factory, no advice, no catch-all resolver, no error controller — and Spring - * Boot's {@code BasicErrorController} back in its place. + * handling altogether: no factory, no advice, no catch-all resolver, no error controller — and + * Spring Boot's {@code BasicErrorController} back in its place. * *

        A half-disabled feature is the dangerous outcome here. If, say, the catch-all resolver kept * running, an application would get Boot's format for some errors and RFC 9457 for others, with no @@ -50,9 +50,9 @@ * *

        How it is tested

        * - *

        The same {@link WebApplicationContextRunner} set-up as {@link ProblemDetailsWebTest}, including - * {@link ProblemDetailsAutoConfiguration}: the property, not the absence of the auto-configuration, - * has to do the disabling. + *

        The same {@link WebApplicationContextRunner} set-up as {@link ProblemDetailsWebTest}, + * including {@link ProblemDetailsAutoConfiguration}: the property, not the absence of the + * auto-configuration, has to do the disabling. */ @DisplayName("Problem details disabled") class ProblemDetailsDisabledWebTest { diff --git a/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsWebTest.java b/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsWebTest.java index 2752540..bcf3b3b 100644 --- a/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsWebTest.java +++ b/spring-services-core/src/test/java/com/example/problemapp/ProblemDetailsWebTest.java @@ -71,11 +71,12 @@ *

        How it is tested

        * *

        A {@link WebApplicationContextRunner} with the real auto-configurations, driven through {@link - * MockMvc}. No database and no Testcontainers: nothing here needs persistence, and a web slice keeps - * the feedback loop short enough that every scenario can have its own case. + * MockMvc}. No database and no Testcontainers: nothing here needs persistence, and a web slice + * keeps the feedback loop short enough that every scenario can have its own case. * *

        Mock-Audit. No mocks. The controllers, the {@code @Validated} service and the - * application advices are real beans; the only test doubles are Spring's own MockMvc infrastructure. + * application advices are real beans; the only test doubles are Spring's own MockMvc + * infrastructure. */ @DisplayName("Problem details over HTTP") class ProblemDetailsWebTest { @@ -117,21 +118,20 @@ private void run(final WebApplicationContextRunner custom, final MvcAssertion as /** * Builds the {@link MockMvc} with the library's trace filter in front of the servlet. * - *

        MockMvc runs only the filters it is given; a {@code FilterRegistrationBean} in the context is - * invisible to it. Without this the trace ID would still reach the response body — {@code + *

        MockMvc runs only the filters it is given; a {@code FilterRegistrationBean} in the context + * is invisible to it. Without this the trace ID would still reach the response body — {@code * TraceContext} resolves one on first read — but the MDC would never be populated, and the * assertions about log correlation would pass against a set-up that does not resemble production. */ private static MockMvc mockMvc(final WebApplicationContext context) { final jakarta.servlet.Filter traceFilter = - context - .getBean("traceContextFilterRegistration", FilterRegistrationBean.class) - .getFilter(); + context.getBean("traceContextFilterRegistration", FilterRegistrationBean.class).getFilter(); return MockMvcBuilders.webAppContextSetup(context).addFilters(traceFilter).build(); } /** Performs a request and returns the parsed problem, asserting the content type on the way. */ - private static JsonNode problem(final MockMvc mvc, final org.springframework.test.web.servlet.RequestBuilder request) + private static JsonNode problem( + final MockMvc mvc, final org.springframework.test.web.servlet.RequestBuilder request) throws Exception { final var result = mvc.perform(request).andExpect(content().contentType(PROBLEM_JSON)).andReturn(); @@ -194,7 +194,8 @@ void instanceCanBeSwitchedOff() { void problemsAreJsonEvenForBrowsers() { run( mvc -> - mvc.perform(get("/api/test/fail").header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE)) + mvc.perform( + get("/api/test/fail").header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE)) .andExpect(status().isNotFound()) .andExpect(content().contentType(PROBLEM_JSON)) .andExpect(jsonPath("$.type").value(BASE + "not-found"))); @@ -263,7 +264,10 @@ void typedProblemWithoutAHandler() { @Test @DisplayName("Without a detail the member is absent") void problemWithoutDetail() { - run(mvc -> assertThat(problem(mvc, get("/api/test/problem-without-detail")).has("detail")).isFalse()); + run( + mvc -> + assertThat(problem(mvc, get("/api/test/problem-without-detail")).has("detail")) + .isFalse()); } @Test @@ -271,7 +275,10 @@ void problemWithoutDetail() { void extensionMembers() { run( mvc -> - assertThat(problem(mvc, get("/api/test/problem-with-extension")).path("existingId").asString()) + assertThat( + problem(mvc, get("/api/test/problem-with-extension")) + .path("existingId") + .asString()) .isEqualTo("42")); } @@ -296,9 +303,9 @@ void applicationEnumAsProblemType() { } /** - * A {@code 503} is an operational event. If it were logged at {@code DEBUG} like a client error, - * an outage would leave no trace in a production log — and the trace ID in the MDC is what ties - * the client's report to that entry. + * A {@code 503} is an operational event. If it were logged at {@code DEBUG} like a client + * error, an outage would leave no trace in a production log — and the trace ID in the MDC is + * what ties the client's report to that entry. */ @Test @DisplayName("A 5xx problem is logged at ERROR with the response's traceId in the MDC") @@ -360,9 +367,10 @@ void bodyErrorsCarryPointers() { final var pointers = body.path("errors").findValuesAsString("pointer"); assertThat(pointers) - .contains("/address/street", "/address/postal_code", "/items/0/name", "/labels/a~1b~0c"); - assertThat(body.path("errors")).allSatisfy(entry -> - assertThat(entry.path("message").asString()).isNotBlank()); + .contains( + "/address/street", "/address/postal_code", "/items/0/name", "/labels/a~1b~0c"); + assertThat(body.path("errors")) + .allSatisfy(entry -> assertThat(entry.path("message").asString()).isNotBlank()); }); } @@ -563,7 +571,8 @@ void wrongMethodKeepsAllow() { mvc -> { mvc.perform(delete("/api/test/only-get")) .andExpect(status().isMethodNotAllowed()) - .andExpect(header().string(HttpHeaders.ALLOW, org.hamcrest.Matchers.containsString("GET"))) + .andExpect( + header().string(HttpHeaders.ALLOW, org.hamcrest.Matchers.containsString("GET"))) .andExpect(content().contentType(PROBLEM_JSON)) .andExpect(jsonPath("$.type").value(BASE + "method-not-allowed")); }); @@ -575,9 +584,7 @@ void unsupportedMediaType() { run( mvc -> mvc.perform( - post("/api/test/body") - .contentType(MediaType.TEXT_PLAIN) - .content("not json")) + post("/api/test/body").contentType(MediaType.TEXT_PLAIN).content("not json")) .andExpect(status().isUnsupportedMediaType()) .andExpect(content().contentType(PROBLEM_JSON)) .andExpect(jsonPath("$.type").value(BASE + "unsupported-media-type"))); @@ -744,9 +751,9 @@ ProblemDetail handle(final IllegalStateException e, final HttpServletRequest req } /** - * An advice that takes over a mapping the library's own advice also handles. Both sit at - * {@code LOWEST_PRECEDENCE} by default, so the application has to declare an {@code @Order} — - * which is exactly what the documentation tells it to do. + * An advice that takes over a mapping the library's own advice also handles. Both sit at {@code + * LOWEST_PRECEDENCE} by default, so the application has to declare an {@code @Order} — which is + * exactly what the documentation tells it to do. */ @Configuration(proxyBeanMethods = false) static class OrderedValidationAdvice { diff --git a/spring-services-core/src/test/java/com/example/problemapp/ProblemErrorDispatchIntegrationTest.java b/spring-services-core/src/test/java/com/example/problemapp/ProblemErrorDispatchIntegrationTest.java index 2dba8e9..249e500 100644 --- a/spring-services-core/src/test/java/com/example/problemapp/ProblemErrorDispatchIntegrationTest.java +++ b/spring-services-core/src/test/java/com/example/problemapp/ProblemErrorDispatchIntegrationTest.java @@ -39,8 +39,8 @@ * *

        What is tested

        * - *

        The container's {@code ERROR} dispatch — the one error path {@code MockMvc} does not perform at - * all, and therefore the one that no other test in this repository can reach: + *

        The container's {@code ERROR} dispatch — the one error path {@code MockMvc} does not perform + * at all, and therefore the one that no other test in this repository can reach: * *

          *
        • A {@code sendError(...)} from a filter becomes a problem of that status, and in @@ -60,14 +60,19 @@ *

          How it is tested

          * *

          A real Tomcat on a random port, with the library's production filter chains, driven through - * {@link TestRestTemplate}. The database comes from the shared Postgres Testcontainer because {@link - * StarterTestApp} is a JPA application. + * {@link TestRestTemplate}. The database comes from the shared Postgres Testcontainer because + * {@link StarterTestApp} is a JPA application. * *

          Mock-Audit. No mocks. The rate-limit filter and the extra security chain are real beans * registered for the test. */ -@SpringBootTest(classes = StarterTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@Import({PostgresTestConfiguration.class, ProblemErrorDispatchIntegrationTest.ErrorDispatchBeans.class}) +@SpringBootTest( + classes = StarterTestApp.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Import({ + PostgresTestConfiguration.class, + ProblemErrorDispatchIntegrationTest.ErrorDispatchBeans.class +}) @Testcontainers @ActiveProfiles("testcontainers") @AutoConfigureTestRestTemplate @@ -105,17 +110,16 @@ void sendErrorFromAFilterBecomesAProblem() throws Exception { @Test @DisplayName("[container] instance on an error dispatch is the original path, not /error") void instanceOnAnErrorDispatchIsTheOriginalPath() throws Exception { - final JsonNode body = - problem(restTemplate.getForEntity("/api/test/limited", String.class)); + final JsonNode body = problem(restTemplate.getForEntity("/api/test/limited", String.class)); assertThat(body.path("instance").asString()).isEqualTo("/api/test/limited"); } /** * The ALTCHA module's challenge chain has exactly this shape: a {@code securityMatcher}, one - * {@code permitAll} rule and {@code denyAll} for everything else, with no access-denied handler of - * its own. Spring Security's default handler then calls {@code sendError(403)}, and only the error - * dispatch can turn that into a problem. + * {@code permitAll} rule and {@code denyAll} for everything else, with no access-denied handler + * of its own. Spring Security's default handler then calls {@code sendError(403)}, and only the + * error dispatch can turn that into a problem. */ @Test @DisplayName("[container] A denyAll chain without its own handler still yields a 403 problem") @@ -143,8 +147,8 @@ static class ErrorDispatchBeans { /** * Rejects one path with {@code sendError(429)}, the way a rate limiter would. Ordered ahead of - * Spring Security so the request never reaches a chain — which is exactly the situation in which - * the default chain used to answer {@code 401} instead. + * Spring Security so the request never reaches a chain — which is exactly the situation in + * which the default chain used to answer {@code 401} instead. */ @Bean FilterRegistrationBean rateLimitFilter() { @@ -161,7 +165,8 @@ SecurityFilterChain publicFormChain(final HttpSecurity http) throws Exception { http.securityMatcher("/api/public-form/**") .authorizeHttpRequests( auth -> - auth.requestMatchers(org.springframework.http.HttpMethod.GET, "/api/public-form/**") + auth.requestMatchers( + org.springframework.http.HttpMethod.GET, "/api/public-form/**") .permitAll() .anyRequest() .denyAll()) diff --git a/spring-services-core/src/test/java/com/example/problemapp/ProblemTestBodies.java b/spring-services-core/src/test/java/com/example/problemapp/ProblemTestBodies.java index da8f6d1..5ae0545 100644 --- a/spring-services-core/src/test/java/com/example/problemapp/ProblemTestBodies.java +++ b/spring-services-core/src/test/java/com/example/problemapp/ProblemTestBodies.java @@ -22,9 +22,7 @@ private ProblemTestBodies() { /** The body root of the validation endpoint. */ record Order( - @Valid Address address, - @Valid List items, - Map labels) {} + @Valid Address address, @Valid List items, Map labels) {} /** Nested object with one field renamed by {@code @JsonProperty}. */ record Address( diff --git a/spring-services-core/src/test/java/com/example/problemapp/ProblemTestController.java b/spring-services-core/src/test/java/com/example/problemapp/ProblemTestController.java index f2ee586..333344c 100644 --- a/spring-services-core/src/test/java/com/example/problemapp/ProblemTestController.java +++ b/spring-services-core/src/test/java/com/example/problemapp/ProblemTestController.java @@ -147,7 +147,9 @@ String onlyGet() { return "ok"; } - /** Calls a {@code @Validated} service with an argument it builds itself — a server-side defect. */ + /** + * Calls a {@code @Validated} service with an argument it builds itself — a server-side defect. + */ @GetMapping("/api/test/service-violation") String serviceViolation() { service.process(5000); diff --git a/spring-services-core/src/test/java/com/example/problemapp/ProblemTestService.java b/spring-services-core/src/test/java/com/example/problemapp/ProblemTestService.java index fee80eb..31aeef8 100644 --- a/spring-services-core/src/test/java/com/example/problemapp/ProblemTestService.java +++ b/spring-services-core/src/test/java/com/example/problemapp/ProblemTestService.java @@ -6,9 +6,9 @@ /** * A {@code @Validated} service, standing in for a bean deeper down the call stack. * - *

          A {@code ConstraintViolationException} raised here means the application called its own service - * with an argument it built wrong. That is a server-side defect, not a client error — the test for - * {@code /api/test/service-violation} pins that it becomes a {@code 500}. + *

          A {@code ConstraintViolationException} raised here means the application called its own + * service with an argument it built wrong. That is a server-side defect, not a client error — the + * test for {@code /api/test/service-violation} pins that it becomes a {@code 500}. */ @Validated public class ProblemTestService { diff --git a/spring-services-core/src/test/java/com/example/rolesapp/CallerRoleLookupChainIntegrationTest.java b/spring-services-core/src/test/java/com/example/rolesapp/CallerRoleLookupChainIntegrationTest.java index 764bcaa..7db7a5c 100644 --- a/spring-services-core/src/test/java/com/example/rolesapp/CallerRoleLookupChainIntegrationTest.java +++ b/spring-services-core/src/test/java/com/example/rolesapp/CallerRoleLookupChainIntegrationTest.java @@ -18,9 +18,9 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Primary; @@ -32,9 +32,9 @@ import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; +import org.testcontainers.junit.jupiter.Testcontainers; /** * Filter-chain acceptance gate for {@link AuthService#getRoles()} (spec 017). @@ -62,7 +62,10 @@ */ @SpringBootTest(classes = StarterTestApp.class) @AutoConfigureMockMvc -@Import({PostgresTestConfiguration.class, CallerRoleLookupChainIntegrationTest.TestSecurityBeans.class}) +@Import({ + PostgresTestConfiguration.class, + CallerRoleLookupChainIntegrationTest.TestSecurityBeans.class +}) @Testcontainers @ActiveProfiles("testcontainers") class CallerRoleLookupChainIntegrationTest { @@ -87,7 +90,8 @@ void anonymousRequestArrivesAsAnonymous() throws Exception { @DisplayName("[chain] A JWT roles claim arrives prefix-mapped and stripped, without SCOPE_*") void jwtRolesArrivePrefixMappedAndStripped() throws Exception { mockMvc - .perform(get("/api/protected/roles").header(HttpHeaders.AUTHORIZATION, bearer(TOKEN_WITH_ROLES))) + .perform( + get("/api/protected/roles").header(HttpHeaders.AUTHORIZATION, bearer(TOKEN_WITH_ROLES))) .andExpect(status().isOk()) .andExpect(jsonPath("$", containsInAnyOrder("IT-ADMIN", "EMPLOYEE"))); } @@ -97,7 +101,8 @@ void jwtRolesArrivePrefixMappedAndStripped() throws Exception { void jwtWithoutRolesArrivesEmpty() throws Exception { mockMvc .perform( - get("/api/protected/roles").header(HttpHeaders.AUTHORIZATION, bearer(TOKEN_WITHOUT_ROLES))) + get("/api/protected/roles") + .header(HttpHeaders.AUTHORIZATION, bearer(TOKEN_WITHOUT_ROLES))) .andExpect(status().isOk()) .andExpect(jsonPath("$", emptyIterable())); } @@ -120,7 +125,8 @@ void apiKeyRequestArrivesAsApiKey() throws Exception { * the body's shape moved. */ @Test - @DisplayName("[chain] An unauthenticated request to a protected path is rejected with 401 + WWW-Authenticate: Bearer") + @DisplayName( + "[chain] An unauthenticated request to a protected path is rejected with 401 + WWW-Authenticate: Bearer") void unauthenticatedProtectedRequestIsRejectedWith401() throws Exception { mockMvc .perform(get("/api/protected/roles")) @@ -138,10 +144,11 @@ private static String bearer(final String token) { } /** - * Creates a real API key through {@link ApiKeyDataService#create(ApiKeyCreateDto)} so the external - * chain exercises the production hash-and-lookup path. {@code create(...)} resolves the current - * user from a JWT, so a JWT authentication is bound to the context for the duration of the call and - * cleared afterwards — this happens on the test thread, independent of the MockMvc filter chain. + * Creates a real API key through {@link ApiKeyDataService#create(ApiKeyCreateDto)} so the + * external chain exercises the production hash-and-lookup path. {@code create(...)} resolves the + * current user from a JWT, so a JWT authentication is bound to the context for the duration of + * the call and cleared afterwards — this happens on the test thread, independent of the MockMvc + * filter chain. */ private String createApiKey() { final Jwt jwt = @@ -162,10 +169,11 @@ private String createApiKey() { } /** - * Test-scoped beans: a {@code @Primary} {@link JwtDecoder} that decodes the two fixture tokens into - * hand-built {@link Jwt}s (the profile's stub decoder throws on use), and a controller reporting - * {@code getRoles()} on one endpoint per production chain. Declared as a {@code @TestConfiguration} - * so the application's component scan never picks it up; it is only active when {@code @Import}ed. + * Test-scoped beans: a {@code @Primary} {@link JwtDecoder} that decodes the two fixture tokens + * into hand-built {@link Jwt}s (the profile's stub decoder throws on use), and a controller + * reporting {@code getRoles()} on one endpoint per production chain. Declared as a + * {@code @TestConfiguration} so the application's component scan never picks it up; it is only + * active when {@code @Import}ed. */ @TestConfiguration(proxyBeanMethods = false) static class TestSecurityBeans { diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/SpringServicesCoreAutoConfigurationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/SpringServicesCoreAutoConfigurationTest.java index a0ec620..c304902 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/SpringServicesCoreAutoConfigurationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/SpringServicesCoreAutoConfigurationTest.java @@ -14,11 +14,12 @@ * *

          Verifies the {@code @ConditionalOnClass(EntityManagerFactory.class)} guard: in an application * without JPA on the classpath the starter must stay inert rather than fail trying to configure - * persistence. Driven by an {@link ApplicationContextRunner} with a {@link FilteredClassLoader} that - * hides {@link EntityManagerFactory}, so no database is involved. + * persistence. Driven by an {@link ApplicationContextRunner} with a {@link FilteredClassLoader} + * that hides {@link EntityManagerFactory}, so no database is involved. * *

          The positive case (the auto-configuration activating and wiring the full platform when JPA is - * present) is covered end-to-end by {@code com.example.app.StarterAutoConfigurationIntegrationTest}. + * present) is covered end-to-end by {@code + * com.example.app.StarterAutoConfigurationIntegrationTest}. */ @DisplayName("SpringServicesCoreAutoConfiguration — activation guard") class SpringServicesCoreAutoConfigurationTest { @@ -28,7 +29,8 @@ class SpringServicesCoreAutoConfigurationTest { .withConfiguration(AutoConfigurations.of(SpringServicesCoreAutoConfiguration.class)); @Test - @DisplayName("Backs off (does not activate) when EntityManagerFactory is absent from the classpath") + @DisplayName( + "Backs off (does not activate) when EntityManagerFactory is absent from the classpath") void backsOffWithoutJpa() { contextRunner .withClassLoader(new FilteredClassLoader(EntityManagerFactory.class)) diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/data/AbstractDbBackedDataServicePublishEventsTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/data/AbstractDbBackedDataServicePublishEventsTest.java index 51dc25b..f7e5da9 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/data/AbstractDbBackedDataServicePublishEventsTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/data/AbstractDbBackedDataServicePublishEventsTest.java @@ -40,13 +40,13 @@ * pseudo-persistence, so {@code updateEntity} mutates the instance the previous state was taken * from, exactly like a JPA persistence context). * - *

          An anonymous {@code FakeService extends AbstractDbBackedDataService} stands in for any - * real subclass so the test does not couple to a domain entity. The flag itself is the unit - * under test, not the surrounding template-method machinery. + *

          An anonymous {@code FakeService extends AbstractDbBackedDataService} stands in for any real + * subclass so the test does not couple to a domain entity. The flag itself is the unit under test, + * not the surrounding template-method machinery. * - *

          Mock-Audit. Both mocks are justified: the publisher mock is the assertion target; - * the repository mock substitutes for a JPA layer that would require Spring + Testcontainers - * to use for real, which would dwarf the focused scope of the test. + *

          Mock-Audit. Both mocks are justified: the publisher mock is the assertion target; the + * repository mock substitutes for a JPA layer that would require Spring + Testcontainers to use for + * real, which would dwarf the focused scope of the test. */ @DisplayName("AbstractDbBackedDataService publishEvents flag") class AbstractDbBackedDataServicePublishEventsTest { @@ -134,8 +134,7 @@ void shouldPublishPreviousAndCurrentStateOnUpdate() { } @Test - @DisplayName( - "An update that changes nothing publishes no event but still returns the saved DTO.") + @DisplayName("An update that changes nothing publishes no event but still returns the saved DTO.") void shouldNotPublishOnNoOpUpdate() { // GIVEN final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/data/DbHealthServiceIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/data/DbHealthServiceIntegrationTest.java index 23bed27..187472e 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/data/DbHealthServiceIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/data/DbHealthServiceIntegrationTest.java @@ -21,21 +21,21 @@ *

          Three things the unit test cannot prove: * *

            - *
          • The validation query is accepted by a real PostgreSQL and the service reports - * {@code true} — a mocked {@link java.sql.Statement} would happily "execute" invalid SQL. + *
          • The validation query is accepted by a real PostgreSQL and the service reports {@code true} + * — a mocked {@link java.sql.Statement} would happily "execute" invalid SQL. *
          • The service is injectable as a bean the library registers itself (via {@link DataConfig}), * without the application declaring it. - *
          • Repeated calls stay {@code true}, which would fail if the check leaked pooled - * connections instead of closing them. + *
          • Repeated calls stay {@code true}, which would fail if the check leaked pooled connections + * instead of closing them. *
          * *

          How it is tested

          * - *

          {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * starts a real Postgres via Testcontainers and provides the {@link DataSource} the injected - * {@link DbHealthService} probes. The unreachable case is deliberately not reproduced here — - * stopping the container would make the test slow and order-dependent for the other tests - * sharing it; those branches are covered by {@link DbHealthServiceTest}. + *

          {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} starts + * a real Postgres via Testcontainers and provides the {@link DataSource} the injected {@link + * DbHealthService} probes. The unreachable case is deliberately not reproduced here — stopping the + * container would make the test slow and order-dependent for the other tests sharing it; those + * branches are covered by {@link DbHealthServiceTest}. * *

          Mock-Audit. Zero mocks. Both the service and the data source are real beans, and the * database is a real Postgres in a container — the whole point of the test is that the round-trip diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/data/DbHealthServiceTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/data/DbHealthServiceTest.java index e2571ff..b4cad45 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/data/DbHealthServiceTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/data/DbHealthServiceTest.java @@ -26,15 +26,14 @@ * *

            *
          • A successfully executed validation query yields {@code true}, and both the borrowed - * connection and the statement are closed again (they are opened in a - * try-with-resources, so a leak here would exhaust the pool under probe traffic). - *
          • The statement executed is exactly {@code SELECT 1} — the query is part of the contract - * with the database, not an implementation detail, because it must stay table-free and - * lock-free. + * connection and the statement are closed again (they are opened in a try-with-resources, so + * a leak here would exhaust the pool under probe traffic). + *
          • The statement executed is exactly {@code SELECT 1} — the query is part of the contract with + * the database, not an implementation detail, because it must stay table-free and lock-free. *
          • Every failure mode maps to {@code false} instead of an exception: connection acquisition - * failing, statement creation failing, query execution failing, and a - * {@link RuntimeException} from the pool (a Hikari connection-acquisition timeout surfaces - * as one, so catching only {@link SQLException} would let it escape). + * failing, statement creation failing, query execution failing, and a {@link + * RuntimeException} from the pool (a Hikari connection-acquisition timeout surfaces as one, + * so catching only {@link SQLException} would let it escape). *
          • The constructor rejects a {@code null} data source. *
          * @@ -45,10 +44,9 @@ * especially the failure branches, which cannot be provoked reliably against a running database. * {@link DbHealthServiceIntegrationTest} covers the happy path against a real PostgreSQL. * - *

          Mock-Audit. Three mocks, all unavoidable: {@link Connection} and {@link Statement} - * are JDBC SPI interfaces with dozens of methods each, so hand-written stubs would be far more - * code than the tests themselves, and the failure cases require making those methods throw on - * demand. + *

          Mock-Audit. Three mocks, all unavoidable: {@link Connection} and {@link Statement} are + * JDBC SPI interfaces with dozens of methods each, so hand-written stubs would be far more code + * than the tests themselves, and the failure cases require making those methods throw on demand. */ @DisplayName("DbHealthService Tests") class DbHealthServiceTest { diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/data/EntitySchemaConventionTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/data/EntitySchemaConventionTest.java index 5c69458..8bbd32c 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/data/EntitySchemaConventionTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/data/EntitySchemaConventionTest.java @@ -78,8 +78,8 @@ private static List> scanLibraryEntities() { /** * The convention applies to the library's shipped entities only. Test-fixture entities - * (compiled into {@code target/test-classes}) live under the same base package but are deliberately - * schema-less, so they are filtered out by code-source location. + * (compiled into {@code target/test-classes}) live under the same base package but are + * deliberately schema-less, so they are filtered out by code-source location. */ private static boolean isProductionClass(final Class type) { final var codeSource = type.getProtectionDomain().getCodeSource(); @@ -90,11 +90,13 @@ private static boolean isProductionClass(final Class type) { } @Test - @DisplayName("The classpath scan finds exactly the seven known library entities (no vacuous pass)") + @DisplayName( + "The classpath scan finds exactly the seven known library entities (no vacuous pass)") void scanFindsAllSevenEntities() { final List> entities = scanLibraryEntities(); - assertThat(entities).extracting(Class::getSimpleName) + assertThat(entities) + .extracting(Class::getSimpleName) .containsExactlyInAnyOrderElementsOf(EXPECTED_ENTITY_SIMPLE_NAMES); } @@ -103,9 +105,7 @@ void scanFindsAllSevenEntities() { void everyEntityIsMappedToTheDedicatedSchema() { for (final Class entity : scanLibraryEntities()) { final Table table = entity.getAnnotation(Table.class); - assertThat(table) - .as("%s must carry a @Table annotation", entity.getName()) - .isNotNull(); + assertThat(table).as("%s must carry a @Table annotation", entity.getName()).isNotNull(); assertThat(table.schema()) .as("%s must map to the dedicated schema", entity.getName()) .isEqualTo(DbSchema.NAME); @@ -116,7 +116,8 @@ void everyEntityIsMappedToTheDedicatedSchema() { @DisplayName("No library entity maps a JPA association to a type outside the library package") void noLibraryEntityAssociatesToANonLibraryType() { for (final Class entity : scanLibraryEntities()) { - for (Class type = entity; type != null && type != Object.class; + for (Class type = entity; + type != null && type != Object.class; type = type.getSuperclass()) { for (final Field field : type.getDeclaredFields()) { if (!isJpaAssociation(field)) { diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/data/image/util/HeicSupportCheckTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/data/image/util/HeicSupportCheckTest.java index 6f36a06..f59a2da 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/data/image/util/HeicSupportCheckTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/data/image/util/HeicSupportCheckTest.java @@ -17,26 +17,25 @@ * *

          What is tested

          * - *

          The library decides whether HEIC/HEIF image decoding is available at runtime by inspecting - * the registered {@link ImageIO} format readers and attempting a probe-decode of a bundled - * sample. The eight scenarios verify the full decision tree: no reader registered, registered - * but probe-decode succeeds, returns null, throws {@link IOException}, throws {@link - * RuntimeException}, throws {@link UnsatisfiedLinkError} (missing native lib), case-insensitive - * reader-name match, and the bundled probe resource is present on the classpath. A final test - * asserts the production environment without TwelveMonkeys/NightMonkeys dependencies returns - * {@code false} consistently. + *

          The library decides whether HEIC/HEIF image decoding is available at runtime by inspecting the + * registered {@link ImageIO} format readers and attempting a probe-decode of a bundled sample. The + * eight scenarios verify the full decision tree: no reader registered, registered but probe-decode + * succeeds, returns null, throws {@link IOException}, throws {@link RuntimeException}, throws + * {@link UnsatisfiedLinkError} (missing native lib), case-insensitive reader-name match, and the + * bundled probe resource is present on the classpath. A final test asserts the production + * environment without TwelveMonkeys/NightMonkeys dependencies returns {@code false} consistently. * *

          How it is tested

          * *

          Pure JUnit 5 with Mockito's {@link org.mockito.MockedStatic} — {@link ImageIO} is a static - * facade with no instance to inject, so static-mocking is the only way to substitute its - * behaviour without a heavier integration setup. The mock is scoped tightly to each test via + * facade with no instance to inject, so static-mocking is the only way to substitute its behaviour + * without a heavier integration setup. The mock is scoped tightly to each test via * try-with-resources so leakage between cases is impossible. * *

          Mock-Audit. {@code MockedStatic} is the only mock and it is unavoidable — * {@link ImageIO} has no instance, no SPI seam, and registering a fake reader globally would - * pollute the JVM for the rest of the test session. The probe-resource test deliberately uses - * the real classpath without mocks to catch packaging regressions. + * pollute the JVM for the rest of the test session. The probe-resource test deliberately uses the + * real classpath without mocks to catch packaging regressions. */ @DisplayName("HeicSupportCheck") class HeicSupportCheckTest { diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/data/image/util/ImageUtilitiesTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/data/image/util/ImageUtilitiesTest.java index 7889abc..b6c0509 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/data/image/util/ImageUtilitiesTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/data/image/util/ImageUtilitiesTest.java @@ -30,14 +30,14 @@ * *

          How it is tested

          * - *

          Pure JUnit 5, no Spring, no Mockito. The tests build real JPEG/PNG byte arrays via - * {@link ImageIO} in static helper methods (the {@code createJpeg / createPng} factories at - * the top of the file), then feed them through {@code ImageUtilities}. No mocks at all — - * {@link ImageUtilities} has no external collaborators; it is pure-function image processing - * against {@code byte[]} input and output. + *

          Pure JUnit 5, no Spring, no Mockito. The tests build real JPEG/PNG byte arrays via {@link + * ImageIO} in static helper methods (the {@code createJpeg / createPng} factories at the top of the + * file), then feed them through {@code ImageUtilities}. No mocks at all — {@link ImageUtilities} + * has no external collaborators; it is pure-function image processing against {@code byte[]} input + * and output. * - *

          Mock-Audit. Zero mocks. The unit under test is intentionally a leaf utility, so - * real fixtures (in-memory image bytes) are both faster and more honest than any mock would be. + *

          Mock-Audit. Zero mocks. The unit under test is intentionally a leaf utility, so real + * fixtures (in-memory image bytes) are both faster and more honest than any mock would be. */ @DisplayName("ImageUtilities") class ImageUtilitiesTest { diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/events/GenericDataEventTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/events/GenericDataEventTest.java index 42b2fd4..bc923e7 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/events/GenericDataEventTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/events/GenericDataEventTest.java @@ -17,10 +17,10 @@ *

          What is tested

          * *

          The events are tiny value carriers. The contract: each event preserves its source object - * (returnable via {@code getSource()} and {@code getData()}), derives the event's DTO type from - * the source's runtime class, exposes the source's id via {@code entityId()}, and rejects null - * sources at construction time. The {@code ExplicitTypeTest} nested class is a regression guard - * for the type-derivation behaviour, redundant on the happy path but reads as documentation. + * (returnable via {@code getSource()} and {@code getData()}), derives the event's DTO type from the + * source's runtime class, exposes the source's id via {@code entityId()}, and rejects null sources + * at construction time. The {@code ExplicitTypeTest} nested class is a regression guard for the + * type-derivation behaviour, redundant on the happy path but reads as documentation. * *

          How it is tested

          * @@ -121,7 +121,8 @@ void shouldCarryPreviousState() { } @Test - @DisplayName("A previous state equal to the current state is accepted — no-op filtering is not the event's job.") + @DisplayName( + "A previous state equal to the current state is accepted — no-op filtering is not the event's job.") void shouldAcceptEqualPreviousState() { // GIVEN final UUID id = UUID.randomUUID(); @@ -220,7 +221,8 @@ void shouldStoreSourceAndDeriveType() { class ExplicitTypeTest { @Test - @DisplayName("getType() returns the concrete source class — documents the type-derivation contract.") + @DisplayName( + "getType() returns the concrete source class — documents the type-derivation contract.") void shouldUseExplicitTypeWhenProvided() { // GIVEN final TestData data = new TestData(UUID.randomUUID(), "typed"); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/events/TypedEventListenerTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/events/TypedEventListenerTest.java index 70a02aa..91eda5d 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/events/TypedEventListenerTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/events/TypedEventListenerTest.java @@ -20,8 +20,8 @@ *

          What is tested

          * *

          Generic type erasure hides the DTO type of an event instance. Without {@link - * GenericDataEvent#getResolvableType()}, Spring treats the unresolvable type parameter as a wildcard - * and invokes a listener for {@code OnObjectUpdate} with an {@code + * GenericDataEvent#getResolvableType()}, Spring treats the unresolvable type parameter as a + * wildcard and invokes a listener for {@code OnObjectUpdate} with an {@code * OnObjectUpdate} too. These tests pin the corrected dispatch. * *

          How it is tested

          diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoAutoConfigurationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoAutoConfigurationTest.java index 6a2bc64..a055d67 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoAutoConfigurationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoAutoConfigurationTest.java @@ -23,9 +23,9 @@ * Context-level tests for {@link ApplicationInfoAutoConfiguration}. * *

          Covers the three properties that motivated a dedicated, JPA-independent auto-configuration: - * the service is available with no {@link EntityManagerFactory} on the classpath (and the JPA-guarded - * {@link SpringServicesCoreAutoConfiguration} stays inert), an application can substitute its own - * service, and a malformed SBOM on the classpath does not prevent startup. + * the service is available with no {@link EntityManagerFactory} on the classpath (and the + * JPA-guarded {@link SpringServicesCoreAutoConfiguration} stays inert), an application can + * substitute its own service, and a malformed SBOM on the classpath does not prevent startup. * *

          Driven by {@link ApplicationContextRunner}; the no-JPA case uses a {@link FilteredClassLoader} * so no database is involved. diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoServiceTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoServiceTest.java index e3f8693..c4c2976 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoServiceTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoServiceTest.java @@ -148,8 +148,7 @@ void readsGitProperties() { @Test @DisplayName("Git info falls back to build.commit when git.properties is absent.") void fallsBackToBuildCommit() { - final BuildProperties build = - buildProperties(Map.of("commit", "a1b2c3d4e5f6a7b8c9d0")); + final BuildProperties build = buildProperties(Map.of("commit", "a1b2c3d4e5f6a7b8c9d0")); final GitInfo info = service(build, null, new DefaultResourceLoader(), sbomAt(NO_SBOM_LOCATION)) @@ -269,7 +268,8 @@ void blankAbbrevFallsBackToDerivedShortId() { } @Test - @DisplayName("A valid build.commit.time is parsed into commitTime on the build.commit fallback.") + @DisplayName( + "A valid build.commit.time is parsed into commitTime on the build.commit fallback.") void buildCommitTimeIsParsed() { final BuildProperties build = buildProperties( @@ -285,7 +285,8 @@ void buildCommitTimeIsParsed() { } @Test - @DisplayName("An unparseable build.commit.time degrades to a null commitTime, not an exception.") + @DisplayName( + "An unparseable build.commit.time degrades to a null commitTime, not an exception.") void unparseableBuildCommitTimeIsNull() { final BuildProperties build = buildProperties(Map.of("commit", "a1b2c3d4e5f6a7b8c9d0", "commit.time", "not-a-date")); @@ -410,8 +411,7 @@ void collectionsAreImmutable() { @Test @DisplayName("Repeated calls return the same cached instances; the resource is read once.") void cachesResults() { - final CountingResourceLoader loader = - new CountingResourceLoader(new DefaultResourceLoader()); + final CountingResourceLoader loader = new CountingResourceLoader(new DefaultResourceLoader()); final ApplicationInfoService service = service(null, null, loader, sbomAt("classpath:sbom/valid.cdx.json")); @@ -504,7 +504,9 @@ public boolean exists() { } } - /** {@link ResourceLoader} that fails if used — proves a disabled SBOM never touches the loader. */ + /** + * {@link ResourceLoader} that fails if used — proves a disabled SBOM never touches the loader. + */ private static final class ThrowingResourceLoader implements ResourceLoader { @Override diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoTest.java index a18b7bd..bf058f6 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/info/ApplicationInfoTest.java @@ -12,8 +12,8 @@ * *

          What is tested

          * - *

          The {@link ApplicationInfo#empty()} factory returns an all-{@code null} instance (the value the - * service uses when the build produced no metadata), and — as a compile-time-plus-reflection + *

          The {@link ApplicationInfo#empty()} factory returns an all-{@code null} instance (the value + * the service uses when the build produced no metadata), and — as a compile-time-plus-reflection * guarantee — the record exposes no build-timestamp component, per design decision D3: a build time * would be a fixed reproducible-build constant, not an answer to "when was this deployed?". * @@ -38,7 +38,9 @@ void emptyIsAllNull() { @Test @DisplayName("The record exposes no build-timestamp component.") void noBuildTimestampComponent() { - assertThat(Arrays.stream(ApplicationInfo.class.getRecordComponents()).map(RecordComponent::getName)) + assertThat( + Arrays.stream(ApplicationInfo.class.getRecordComponents()) + .map(RecordComponent::getName)) .doesNotContain("buildTime", "time", "timestamp", "buildTimestamp"); } diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/info/CycloneDxReaderTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/info/CycloneDxReaderTest.java index 3f4065f..97670b2 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/info/CycloneDxReaderTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/info/CycloneDxReaderTest.java @@ -17,8 +17,8 @@ * *

          What is tested

          * - *

          Happy-path summarisation, the three CycloneDX license encodings and their precedence, and every - * degrade-to-empty path (missing resource, malformed JSON, non-CycloneDX document). Also the + *

          Happy-path summarisation, the three CycloneDX license encodings and their precedence, and + * every degrade-to-empty path (missing resource, malformed JSON, non-CycloneDX document). Also the * forward-compatibility guarantee: a document from a newer spec version with unknown fields still * yields its components. * @@ -44,15 +44,15 @@ private static Resource fixture(final String name) { class Summarisation { @Test - @DisplayName("A valid CycloneDX 1.6 document is summarised (format, version, serial, count, application).") + @DisplayName( + "A valid CycloneDX 1.6 document is summarised (format, version, serial, count, application).") void summarisesValidDocument() { final SbomDocument document = reader.read(fixture("valid.cdx.json")).orElseThrow(); final SbomSummary summary = document.summary(); assertThat(summary.bomFormat()).isEqualTo("CycloneDX"); assertThat(summary.specVersion()).isEqualTo("1.6"); - assertThat(summary.serialNumber()) - .isEqualTo("urn:uuid:12345678-1234-1234-1234-123456789abc"); + assertThat(summary.serialNumber()).isEqualTo("urn:uuid:12345678-1234-1234-1234-123456789abc"); assertThat(summary.componentCount()).isEqualTo(3); assertThat(summary.application()).isNotNull(); assertThat(summary.application().name()).isEqualTo("open-crm-backend"); @@ -73,7 +73,8 @@ void summaryHasNoTimestamp() { } @Test - @DisplayName("The full component list carries group, name, version, type and purl for each entry.") + @DisplayName( + "The full component list carries group, name, version, type and purl for each entry.") void fullComponentListIsParsed() { final SbomDocument document = reader.read(fixture("valid.cdx.json")).orElseThrow(); @@ -106,7 +107,8 @@ void noMetadataParses() { } @Test - @DisplayName("Unknown fields from a newer spec version are ignored; all components are returned.") + @DisplayName( + "Unknown fields from a newer spec version are ignored; all components are returned.") void unknownFieldsAreIgnored() { final SbomDocument document = reader.read(fixture("future-version.cdx.json")).orElseThrow(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/info/ReactorSbomFixtureTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/info/ReactorSbomFixtureTest.java index 3cd6ec5..18f0cb4 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/info/ReactorSbomFixtureTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/info/ReactorSbomFixtureTest.java @@ -11,9 +11,9 @@ * output ({@code sbom/reactor.cdx.json}), checked in per design decision D8. * *

          A hand-written fixture only proves the parser handles what its author imagined. A real - * generated SBOM is what surfaces a CycloneDX format change: when this test breaks after a plugin or - * format upgrade, that is the moment someone must look at {@link CycloneDxReader}. The fixture is - * regenerated deliberately with {@code mvn -pl spring-services-core + * generated SBOM is what surfaces a CycloneDX format change: when this test breaks after a plugin + * or format upgrade, that is the moment someone must look at {@link CycloneDxReader}. The fixture + * is regenerated deliberately with {@code mvn -pl spring-services-core * org.cyclonedx:cyclonedx-maven-plugin:makeBom} (or {@code -Pfull-build}). * *

          Mock-Audit. Zero mocks — a real SBOM read from the classpath. @@ -22,7 +22,8 @@ class ReactorSbomFixtureTest { @Test - @DisplayName("The real reactor SBOM parses: components present, a Spring Boot purl, every name non-null.") + @DisplayName( + "The real reactor SBOM parses: components present, a Spring Boot purl, every name non-null.") void realReactorSbomParses() { final SbomDocument document = new CycloneDxReader().read(new ClassPathResource("sbom/reactor.cdx.json")).orElseThrow(); @@ -30,7 +31,8 @@ void realReactorSbomParses() { assertThat(document.summary().bomFormat()).isEqualTo("CycloneDX"); assertThat(document.summary().componentCount()).isPositive(); assertThat(document.components()).isNotEmpty(); - assertThat(document.components()).allSatisfy(component -> assertThat(component.name()).isNotNull()); + assertThat(document.components()) + .allSatisfy(component -> assertThat(component.name()).isNotNull()); assertThat(document.components()) .anySatisfy( component -> diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/migration/SchemaMigrationSqlIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/migration/SchemaMigrationSqlIntegrationTest.java index 1aeb07e..3c91c93 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/migration/SchemaMigrationSqlIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/migration/SchemaMigrationSqlIntegrationTest.java @@ -20,11 +20,11 @@ * {@code public}-schema tables into {@code oe_spring_services} with data, indexes, and foreign keys * intact. * - *

          The test deliberately does not use the JPA entities (which now hard-map to the - * dedicated schema). It hand-creates the seven library tables in {@code public} — the pre-upgrade - * layout — seeds rows including an {@code audit_log → users} foreign key, then executes the exact - * {@code CREATE SCHEMA} + {@code ALTER TABLE … SET SCHEMA} statements from the upgrade doc and - * asserts the result. + *

          The test deliberately does not use the JPA entities (which now hard-map to + * the dedicated schema). It hand-creates the seven library tables in {@code public} — the + * pre-upgrade layout — seeds rows including an {@code audit_log → users} foreign key, then executes + * the exact {@code CREATE SCHEMA} + {@code ALTER TABLE … SET SCHEMA} statements from the upgrade + * doc and asserts the result. */ @Testcontainers class SchemaMigrationSqlIntegrationTest { @@ -34,8 +34,7 @@ class SchemaMigrationSqlIntegrationTest { }; @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer("postgres:16-alpine"); + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:16-alpine"); private JdbcTemplate jdbc; @@ -74,8 +73,7 @@ void migrationMovesTablesWithData() { assertThat(count(DbSchema.NAME + ".users")).isEqualTo(1); assertThat(count(DbSchema.NAME + ".audit_log")).isEqualTo(1); assertThat( - jdbc.queryForObject( - "SELECT user_id FROM " + DbSchema.NAME + ".audit_log", UUID.class)) + jdbc.queryForObject("SELECT user_id FROM " + DbSchema.NAME + ".audit_log", UUID.class)) .isEqualTo(userId); } diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/BodyErrorsTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/BodyErrorsTest.java index 764f490..3ac170c 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/BodyErrorsTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/BodyErrorsTest.java @@ -7,7 +7,6 @@ import org.junit.jupiter.api.Test; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; -import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; /** @@ -18,16 +17,16 @@ * *

          The branch Bean Validation never reaches: a failure reported by a plain Spring {@link * org.springframework.validation.Validator}, which carries no {@code ConstraintViolation} to unwrap - * and therefore no property path to resolve through Jackson. The JSON names of the request cannot be - * recovered there, so the field expression is converted structurally instead. + * and therefore no property path to resolve through Jackson. The JSON names of the request cannot + * be recovered there, so the field expression is converted structurally instead. * *

          That fallback is invisible in every other test in this package — they all drive Hibernate * Validator, which always attaches a violation — and it is exactly the kind of branch that rots * unnoticed until an application registers its own validator and starts receiving entries with no * {@code pointer} at all. * - *

          Also pinned here: {@code pointer} comes before {@code message} in every entry, so two responses - * for the same failure are byte-identical. + *

          Also pinned here: {@code pointer} comes before {@code message} in every entry, so two + * responses for the same failure are byte-identical. * *

          How it is tested

          * @@ -40,8 +39,7 @@ class BodyErrorsTest { private final BodyErrors bodyErrors = new BodyErrors(new JsonPointers(new JsonMapper())); private static Errors rejecting(final String field, final String message) { - final BeanPropertyBindingResult result = - new BeanPropertyBindingResult(new Order(), "order"); + final BeanPropertyBindingResult result = new BeanPropertyBindingResult(new Order(), "order"); if (field == null) { result.reject("order.invalid", message); } else { diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/DefaultProblemFactoryTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/DefaultProblemFactoryTest.java index eef55d6..a32b561 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/DefaultProblemFactoryTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/DefaultProblemFactoryTest.java @@ -66,8 +66,7 @@ void mandatoryMembersArePresent() { assertThat(problem.getTitle()).isEqualTo("Unauthorized"); assertThat(problem.getStatus()).isEqualTo(401); assertThat(problem.getDetail()).isEqualTo("Invalid API key"); - assertThat(problem.getProperties()) - .containsEntry("traceId", TraceContext.traceId(request)); + assertThat(problem.getProperties()).containsEntry("traceId", TraceContext.traceId(request)); } @Test diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/JsonPointersTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/JsonPointersTest.java index 6d8a8ce..2300e76 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/JsonPointersTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/JsonPointersTest.java @@ -33,9 +33,9 @@ * *
            *
          • {@code @JsonProperty} renames a field; - *
          • a configured {@link tools.jackson.databind.PropertyNamingStrategies} renames every - * field — the normal case for a snake_case API, and the one where a naive pointer is wrong for - * every single error; + *
          • a configured {@link tools.jackson.databind.PropertyNamingStrategies} renames every field — + * the normal case for a snake_case API, and the one where a naive pointer is wrong for every + * single error; *
          • list indexes and map keys become pointer segments; *
          • a map key containing {@code /} or {@code ~} has to be escaped per RFC 6901 §3, or the * pointer silently addresses a different location; @@ -115,9 +115,7 @@ void jsonPropertyRenamesTheSegment() { @DisplayName("A configured naming strategy renames every segment.") void namingStrategyRenamesEverySegment() { final ObjectMapper snakeCase = - JsonMapper.builder() - .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) - .build(); + JsonMapper.builder().propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE).build(); final Snake snake = new Snake(""); assertThat(pointersFor(snake, new JsonPointers(snakeCase))).containsExactly("/postal_code"); @@ -128,7 +126,9 @@ void namingStrategyRenamesEverySegment() { void listIndexBecomesASegment() { final Order order = new Order( - new Address("Main Street", "12345"), List.of(new Item("much too long a name")), Map.of()); + new Address("Main Street", "12345"), + List.of(new Item("much too long a name")), + Map.of()); assertThat(pointersFor(order)).containsExactly("/items/0/name"); } diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ParameterMessagesTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ParameterMessagesTest.java index b889072..9fe9c8c 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ParameterMessagesTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ParameterMessagesTest.java @@ -42,7 +42,8 @@ class ParameterMessagesTest { private static MethodParameter parameterAt(final int index) throws NoSuchMethodException { final Method method = - Fixtures.class.getDeclaredMethod("endpoint", int.class, long.class, int.class, String.class); + Fixtures.class.getDeclaredMethod( + "endpoint", int.class, long.class, int.class, String.class); final MethodParameter parameter = new MethodParameter(method, index); parameter.initParameterNameDiscovery( new org.springframework.core.DefaultParameterNameDiscoverer()); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemDetailsAutoConfigurationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemDetailsAutoConfigurationTest.java index 5e076d9..5701a21 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemDetailsAutoConfigurationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemDetailsAutoConfigurationTest.java @@ -6,15 +6,15 @@ import com.openelements.spring.base.trace.TraceIdResolver; import jakarta.servlet.http.HttpServletRequest; import java.util.List; +import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.jspecify.annotations.Nullable; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.http.converter.autoconfigure.HttpMessageConvertersAutoConfiguration; import org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration; import org.springframework.boot.webmvc.autoconfigure.error.ErrorMvcAutoConfiguration; -import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.webmvc.error.ErrorController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -36,24 +36,25 @@ *
              *
            • Spring Boot's own beans back off. {@code BasicErrorController} and Boot's {@code * ProblemDetailsExceptionHandler} are both {@code @ConditionalOnMissingBean}, so the library - * wins only because its auto-configuration is declared {@code before} Boot's. If that ordering - * were ever dropped the application would still start — it would just answer some errors in - * Boot's format and some in ours, which is the kind of split nobody notices until a client - * does. - *
            • The catch-all resolver sits directly after {@code ExceptionHandlerExceptionResolver}. - * One position too early and it shadows every application {@code @ExceptionHandler}; one - * position too late and {@code @ResponseStatus} exceptions never reach it. The test asserts - * the index in the real resolver chain. + * wins only because its auto-configuration is declared {@code before} Boot's. If that + * ordering were ever dropped the application would still start — it would just answer some + * errors in Boot's format and some in ours, which is the kind of split nobody notices until a + * client does. + *
            • The catch-all resolver sits directly after {@code + * ExceptionHandlerExceptionResolver}. One position too early and it shadows every + * application {@code @ExceptionHandler}; one position too late and {@code @ResponseStatus} + * exceptions never reach it. The test asserts the index in the real resolver chain. *
            • {@code enabled=false} registers nothing at all and gives Boot's controller back. *
            • An application bean replaces the library's, for the factory, the MVC advice and the * trace resolver. - *
            • An invalid {@code type-base} fails the context rather than producing broken type URIs. + *
            • An invalid {@code type-base} fails the context rather than producing broken type + * URIs. *
            * *

            How it is tested

            * - *

            {@link WebApplicationContextRunner} with the real auto-configurations, including Boot's, so the - * conditions are evaluated exactly as they are at runtime. No mocks. + *

            {@link WebApplicationContextRunner} with the real auto-configurations, including Boot's, so + * the conditions are evaluated exactly as they are at runtime. No mocks. */ @DisplayName("ProblemDetailsAutoConfiguration") class ProblemDetailsAutoConfigurationTest { @@ -117,8 +118,8 @@ void springBootsOwnBeansBackOff() { * Spring MVC decides whether a bean is a request handler from the type the bean factory reports, * which for a {@code @Bean} method is its declared return type. Declaring {@link ErrorController} * there leaves {@code /error} unmapped while every other signal looks healthy — the context - * starts, the bean exists, Boot's controller backs off — and every container error answers - * {@code 404} instead of its real status. This pins the declared type. + * starts, the bean exists, Boot's controller backs off — and every container error answers {@code + * 404} instead of its real status. This pins the declared type. */ @Test @DisplayName("The error controller is registered under its concrete type, so /error is mapped.") @@ -130,13 +131,13 @@ void errorControllerIsRegisteredUnderItsConcreteType() { } @Test - @DisplayName("The catch-all resolver is inserted directly after ExceptionHandlerExceptionResolver.") + @DisplayName( + "The catch-all resolver is inserted directly after ExceptionHandlerExceptionResolver.") void catchAllResolverSitsAfterTheAdviceResolver() { runner.run( context -> { final List chain = resolverChain(context); - final int adviceResolver = - indexOf(chain, ExceptionHandlerExceptionResolver.class); + final int adviceResolver = indexOf(chain, ExceptionHandlerExceptionResolver.class); final int catchAll = indexOf(chain, ProblemHandlerExceptionResolver.class); assertThat(adviceResolver).as("advice resolver must be present").isNotNegative(); @@ -251,7 +252,8 @@ private static int indexOf( return -1; } - // --- application-supplied beans ----------------------------------------------------------------- + // --- application-supplied beans + // ----------------------------------------------------------------- /** * Supplies the {@code DispatcherServletPath} that {@code ErrorMvcAutoConfiguration} needs to map diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemErrorControllerTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemErrorControllerTest.java index e43644f..efd9b87 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemErrorControllerTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemErrorControllerTest.java @@ -59,7 +59,8 @@ private MockHttpServletRequest errorDispatch(final Integer status, final String return request; } - private JsonNode render(final MockHttpServletRequest request, final MockHttpServletResponse response) + private JsonNode render( + final MockHttpServletRequest request, final MockHttpServletResponse response) throws Exception { controller.handleError(request, response); assertThat(response.getContentType()).isEqualTo("application/problem+json"); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemExceptionTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemExceptionTest.java index 8a9dd98..d88d91c 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemExceptionTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemExceptionTest.java @@ -117,8 +117,8 @@ void propertiesAreCopiedUnmodifiableAndOrdered() { final ProblemException exception = new ProblemException(TYPE, "detail", source); source.put("d", 4); - assertThat(exception.properties()).containsExactly( - Map.entry("b", 2), Map.entry("a", 1), Map.entry("c", 3)); + assertThat(exception.properties()) + .containsExactly(Map.entry("b", 2), Map.entry("a", 1), Map.entry("c", 3)); assertThatThrownBy(() -> exception.properties().put("e", 5)) .isInstanceOf(UnsupportedOperationException.class); } diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemHandlerExceptionResolverTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemHandlerExceptionResolverTest.java index 35863e3..92c6c12 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemHandlerExceptionResolverTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemHandlerExceptionResolverTest.java @@ -50,8 +50,8 @@ *

            How it is tested

            * *

            Plain JUnit 5. The resolver is driven directly with {@link MockHttpServletRequest} and {@link - * MockHttpServletResponse}, and the written JSON is parsed back — so the assertions are about what a - * client receives, not about an intermediate object. + * MockHttpServletResponse}, and the written JSON is parsed back — so the assertions are about what + * a client receives, not about an intermediate object. * *

            The constraint violations come from a real {@link Validator} executing a real method, because * the controller-boundary check reads the violation's root bean and its executable node; a @@ -102,7 +102,8 @@ void problemExceptionKeepsItsType() throws Exception { final JsonNode body = resolve( - new ProblemException(type, "Record already exists", java.util.Map.of("existingId", "42")), + new ProblemException( + type, "Record already exists", java.util.Map.of("existingId", "42")), null); assertThat(body.path("type").asString()).isEqualTo(BASE + "duplicate-record"); @@ -138,7 +139,8 @@ void responseStatusExceptionIsHonoured() throws Exception { void badGatewayIsHonoured() throws Exception { final JsonNode body = resolve( - new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Translation API call failed"), null); + new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Translation API call failed"), + null); assertThat(body.path("status").asInt()).isEqualTo(502); assertThat(body.path("type").asString()).isEqualTo(BASE + "bad-gateway"); @@ -148,8 +150,7 @@ void badGatewayIsHonoured() throws Exception { @Test @DisplayName("A status Spring cannot name keeps its own code and gets the http- type.") void unknownStatusKeepsItsCode() throws Exception { - final JsonNode body = - resolve(new ResponseStatusException(HttpStatusCode.valueOf(418)), null); + final JsonNode body = resolve(new ResponseStatusException(HttpStatusCode.valueOf(418)), null); assertThat(body.path("status").asInt()).isEqualTo(418); assertThat(body.path("type").asString()).isEqualTo(BASE + "http-418"); @@ -188,8 +189,7 @@ void controllerBoundaryViolationIsABadRequest() throws Exception { final JsonNode body = resolve( - new ConstraintViolationException(violations), - new HandlerMethod(controller, method)); + new ConstraintViolationException(violations), new HandlerMethod(controller, method)); assertThat(body.path("status").asInt()).isEqualTo(400); assertThat(body.path("type").asString()).isEqualTo(BASE + "invalid-parameter"); @@ -212,7 +212,8 @@ void serviceLayerViolationIsAServerError() throws Exception { final JsonNode body = resolve( new ConstraintViolationException(violations), - new HandlerMethod(controller, TestController.class.getDeclaredMethod("list", int.class))); + new HandlerMethod( + controller, TestController.class.getDeclaredMethod("list", int.class))); assertThat(body.path("status").asInt()).isEqualTo(500); assertThat(body.path("type").asString()).isEqualTo(BASE + "internal-error"); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemResponseWriterTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemResponseWriterTest.java index 4753988..47ba243 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemResponseWriterTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemResponseWriterTest.java @@ -85,7 +85,9 @@ void nullArgumentsRejected() { assertThatThrownBy(() -> writer.write(new MockHttpServletResponse(), null)) .isInstanceOf(NullPointerException.class); assertThatThrownBy( - () -> writer.write(null, ProblemDetail.forStatus(org.springframework.http.HttpStatus.NOT_FOUND))) + () -> + writer.write( + null, ProblemDetail.forStatus(org.springframework.http.HttpStatus.NOT_FOUND))) .isInstanceOf(NullPointerException.class); } } diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemSecurityHandlersTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemSecurityHandlersTest.java index db00e52..fb186ad 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemSecurityHandlersTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/ProblemSecurityHandlersTest.java @@ -37,8 +37,8 @@ * *

            How it is tested

            * - *

            Plain JUnit 5 with Spring's servlet-API test doubles, parsing the written JSON. No mocks and no - * Spring context — both handlers take only a factory and a writer. + *

            Plain JUnit 5 with Spring's servlet-API test doubles, parsing the written JSON. No mocks and + * no Spring context — both handlers take only a factory and a writer. */ @DisplayName("Problem security handlers") class ProblemSecurityHandlersTest { @@ -103,8 +103,7 @@ void missingJwt() throws Exception { @Test @DisplayName("Null constructor arguments are rejected.") void nullArgumentsRejected() { - assertThatThrownBy( - () -> new ProblemAuthenticationEntryPoint(null, responseWriter, "Bearer")) + assertThatThrownBy(() -> new ProblemAuthenticationEntryPoint(null, responseWriter, "Bearer")) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> new ProblemAuthenticationEntryPoint(problemFactory, null, "Bearer")) .isInstanceOf(NullPointerException.class); @@ -139,7 +138,8 @@ void deactivatedAccount() throws Exception { } @Test - @DisplayName("No WWW-Authenticate header is set on a 403 — the caller is already authenticated.") + @DisplayName( + "No WWW-Authenticate header is set on a 403 — the caller is already authenticated.") void noChallengeOnForbidden() throws Exception { final var handler = new ProblemAccessDeniedHandler(problemFactory, responseWriter); final var response = new MockHttpServletResponse(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/problem/StandardProblemTypeTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/problem/StandardProblemTypeTest.java index ab62354..cdc96b7 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/problem/StandardProblemTypeTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/problem/StandardProblemTypeTest.java @@ -19,17 +19,17 @@ *

            Three things, in order of how badly they would hurt if they broke: * *

              - *
            1. The slugs are frozen. {@link #slugsAreFrozen} spells out the slug of every constant a - * client is likely to branch on. These strings are published contract — a consumer compares + *
            2. The slugs are frozen. {@link #slugsAreFrozen} spells out the slug of every constant + * a client is likely to branch on. These strings are published contract — a consumer compares * {@code type} URIs — so the test exists to make a rename a deliberate act with a failing * build, not a silent break. It also pins the two slugs that would have changed under us when * Spring Framework 6 renamed {@code PAYLOAD_TOO_LARGE} and {@code UNPROCESSABLE_ENTITY}. - *
            3. {@link StandardProblemType#forStatus(int)} resolves to the status-named constant, not - * to one of the four cause-describing types that share a status with it. If {@code - * forStatus(400)} ever returned {@code validation-failed}, every plain {@code 400} would claim - * a body-validation failure and promise an {@code errors} array it does not have. - *
            4. Every constant satisfies {@link ProblemType#validate}, so a typo in a new constant is - * a build failure rather than an unparseable {@code type} URI in production. + *
            5. {@link StandardProblemType#forStatus(int)} resolves to the status-named constant, + * not to one of the four cause-describing types that share a status with it. If {@code + * forStatus(400)} ever returned {@code validation-failed}, every plain {@code 400} would + * claim a body-validation failure and promise an {@code errors} array it does not have. + *
            6. Every constant satisfies {@link ProblemType#validate}, so a typo in a new constant + * is a build failure rather than an unparseable {@code type} URI in production. *
            * *

            How it is tested

            @@ -124,13 +124,16 @@ void everyConstantIsValid(final StandardProblemType type) { @DisplayName("No two constants share a slug.") void slugsAreUnique() { final long distinct = - Arrays.stream(StandardProblemType.values()).map(StandardProblemType::slug).distinct().count(); + Arrays.stream(StandardProblemType.values()) + .map(StandardProblemType::slug) + .distinct() + .count(); assertThat(distinct).isEqualTo(StandardProblemType.values().length); } /** - * Only {@code 400} may be claimed by more than one constant — by {@code bad-request} and the three - * cause-describing types. Any other duplicated status would make {@link + * Only {@code 400} may be claimed by more than one constant — by {@code bad-request} and the + * three cause-describing types. Any other duplicated status would make {@link * StandardProblemType#forStatus(int)} depend on declaration order. */ @Test diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/AuthServiceTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/AuthServiceTest.java index d0c5f84..97a682e 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/AuthServiceTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/AuthServiceTest.java @@ -35,30 +35,30 @@ *

            Three concerns are verified: * *

              - *
            1. Accessors against the SecurityContext. {@code getAuthentication()} returns the - * bound {@link org.springframework.security.core.Authentication} or fails fast with - * {@link IllegalStateException} when none is present; {@code getPrincipalObject()} and - * {@code getPrincipalJwt()} narrow to the expected principal type or reject mismatches. - *
            2. JWT claim extraction into {@link UserInformation}. The {@code preferred_username - * → email → sub} fallback chain for {@code userName}, the {@code picture}-to-{@code - * avatarUrl} mapping with blank-claim normalisation to {@code null}, and the - * {@code externalId == sub} identity that downstream code relies on. - *
            3. Non-JWT principals. {@code getUserInformation()} returns - * {@link java.util.Optional#empty()} for {@link ApiKeyEntity} and {@link String} principals - * rather than throwing — this lets {@code UserService} treat API-key requests as - * "no JWT bound" without special-casing. + *
            4. Accessors against the SecurityContext. {@code getAuthentication()} returns the bound + * {@link org.springframework.security.core.Authentication} or fails fast with {@link + * IllegalStateException} when none is present; {@code getPrincipalObject()} and {@code + * getPrincipalJwt()} narrow to the expected principal type or reject mismatches. + *
            5. JWT claim extraction into {@link UserInformation}. The {@code preferred_username → + * email → sub} fallback chain for {@code userName}, the {@code picture}-to-{@code avatarUrl} + * mapping with blank-claim normalisation to {@code null}, and the {@code externalId == sub} + * identity that downstream code relies on. + *
            6. Non-JWT principals. {@code getUserInformation()} returns {@link + * java.util.Optional#empty()} for {@link ApiKeyEntity} and {@link String} principals rather + * than throwing — this lets {@code UserService} treat API-key requests as "no JWT bound" + * without special-casing. *
            * *

            How it is tested

            * - *

            Pure JUnit 5 unit tests. A real {@link AuthService} is constructed; the - * {@link SecurityContextHolder} is populated per-test with a {@link TestingAuthenticationToken} - * carrying the principal under test, then cleared in {@code @AfterEach} so context state does - * not leak between tests. + *

            Pure JUnit 5 unit tests. A real {@link AuthService} is constructed; the {@link + * SecurityContextHolder} is populated per-test with a {@link TestingAuthenticationToken} carrying + * the principal under test, then cleared in {@code @AfterEach} so context state does not leak + * between tests. * *

            Mock-Audit. Zero mocks. Real {@link Jwt} instances are built via {@code - * Jwt.withTokenValue(...)} and a real {@link TestingAuthenticationToken} carries them through - * the real {@link SecurityContextHolder} — the production code path is exercised verbatim. + * Jwt.withTokenValue(...)} and a real {@link TestingAuthenticationToken} carries them through the + * real {@link SecurityContextHolder} — the production code path is exercised verbatim. */ @DisplayName("AuthService") class AuthServiceTest { @@ -75,7 +75,8 @@ void clearSecurityContext() { class GetAuthenticationTest { @Test - @DisplayName("getAuthentication() returns the Authentication bound to the SecurityContextHolder.") + @DisplayName( + "getAuthentication() returns the Authentication bound to the SecurityContextHolder.") void shouldReturnAuthenticationWhenPresent() { // GIVEN final TestingAuthenticationToken auth = new TestingAuthenticationToken("user", "pass"); @@ -86,7 +87,8 @@ void shouldReturnAuthenticationWhenPresent() { } @Test - @DisplayName("getAuthentication() fails fast with IllegalStateException when no Authentication is bound.") + @DisplayName( + "getAuthentication() fails fast with IllegalStateException when no Authentication is bound.") void shouldThrowWhenNoAuthentication() { // GIVEN SecurityContextHolder.clearContext(); @@ -145,7 +147,8 @@ void shouldReturnJwtWhenPrincipalIsJwt() { } @Test - @DisplayName("getPrincipalJwt() throws IllegalStateException when the principal is not a JWT — caller must not assume JWT semantics.") + @DisplayName( + "getPrincipalJwt() throws IllegalStateException when the principal is not a JWT — caller must not assume JWT semantics.") void shouldThrowWhenPrincipalIsNotJwt() { // GIVEN final TestingAuthenticationToken auth = @@ -164,7 +167,8 @@ void shouldThrowWhenPrincipalIsNotJwt() { class GetUserInformationTest { @Test - @DisplayName("All standard OIDC claims (sub, name, email, picture, preferred_username) flow into UserInformation fields.") + @DisplayName( + "All standard OIDC claims (sub, name, email, picture, preferred_username) flow into UserInformation fields.") void shouldExtractUserInformationFromJwt() { // GIVEN final Jwt jwt = @@ -219,11 +223,12 @@ void userNameFallsBackToEmailWhenPreferredUsernameMissing() { /** * Documents tier three of the {@code userName} fallback chain: service-account tokens - * frequently carry neither {@code preferred_username} nor {@code email}, so the final - * fallback is the JWT subject itself — guaranteeing a non-blank handle for every principal. + * frequently carry neither {@code preferred_username} nor {@code email}, so the final fallback + * is the JWT subject itself — guaranteeing a non-blank handle for every principal. */ @Test - @DisplayName("Missing preferred_username and email fall back to sub — tier three, the last resort.") + @DisplayName( + "Missing preferred_username and email fall back to sub — tier three, the last resort.") void userNameFallsBackToSubWhenPreferredUsernameAndEmailMissing() { final Jwt jwt = Jwt.withTokenValue("token") @@ -242,12 +247,13 @@ void userNameFallsBackToSubWhenPreferredUsernameAndEmailMissing() { } /** - * A whitespace-only {@code preferred_username} is treated as missing — otherwise a single - * space would be persisted as the canonical handle. Normalising blanks to "absent" forces - * the fallback to the next tier. + * A whitespace-only {@code preferred_username} is treated as missing — otherwise a single space + * would be persisted as the canonical handle. Normalising blanks to "absent" forces the + * fallback to the next tier. */ @Test - @DisplayName("A blank (whitespace-only) preferred_username is treated as missing and falls back to email.") + @DisplayName( + "A blank (whitespace-only) preferred_username is treated as missing and falls back to email.") void userNameFallsBackToEmailWhenPreferredUsernameIsBlank() { final Jwt jwt = Jwt.withTokenValue("token") @@ -267,12 +273,13 @@ void userNameFallsBackToEmailWhenPreferredUsernameIsBlank() { } /** - * Pins the {@code externalId == sub == id} invariant. {@code UserService} relies on this to - * use the JWT subject as the SCIM-side external identifier when issuing the second-tier - * lookup; a divergence would break SCIM-pre-provisioned row adoption. + * Pins the {@code externalId == sub == id} invariant. {@code UserService} relies on this to use + * the JWT subject as the SCIM-side external identifier when issuing the second-tier lookup; a + * divergence would break SCIM-pre-provisioned row adoption. */ @Test - @DisplayName("externalId mirrors the JWT subject — same value flows into both UserInformation.id and externalId.") + @DisplayName( + "externalId mirrors the JWT subject — same value flows into both UserInformation.id and externalId.") void externalIdMirrorsSubject() { final Jwt jwt = Jwt.withTokenValue("token") @@ -314,12 +321,13 @@ void shouldReturnNullAvatarUrlWhenAvatarClaimMissing() { } /** - * Symmetric to the blank-{@code preferred_username} normalisation: a whitespace-only - * {@code picture} claim is treated as absent, so {@code avatarUrl} is {@code null} rather - * than a string of spaces — saves a JPA drift-sync flap on next login. + * Symmetric to the blank-{@code preferred_username} normalisation: a whitespace-only {@code + * picture} claim is treated as absent, so {@code avatarUrl} is {@code null} rather than a + * string of spaces — saves a JPA drift-sync flap on next login. */ @Test - @DisplayName("A blank (whitespace-only) picture claim normalises to a null avatarUrl, not a string of spaces.") + @DisplayName( + "A blank (whitespace-only) picture claim normalises to a null avatarUrl, not a string of spaces.") void shouldReturnNullAvatarUrlWhenAvatarClaimIsBlank() { // GIVEN final Jwt jwt = @@ -341,7 +349,8 @@ void shouldReturnNullAvatarUrlWhenAvatarClaimIsBlank() { } @Test - @DisplayName("A blank JWT subject throws IllegalStateException — sub is the one claim that must never be empty.") + @DisplayName( + "A blank JWT subject throws IllegalStateException — sub is the one claim that must never be empty.") void shouldThrowWhenSubjectIsBlank() { // GIVEN final Jwt jwt = @@ -361,12 +370,13 @@ void shouldThrowWhenSubjectIsBlank() { } /** - * Key contract: API-key principals carry no JWT claims, so {@code getUserInformation()} - * returns {@code Optional.empty()} rather than throwing. This lets {@code UserService} - * treat API-key requests as "no JWT bound" without special-casing the principal type. + * Key contract: API-key principals carry no JWT claims, so {@code getUserInformation()} returns + * {@code Optional.empty()} rather than throwing. This lets {@code UserService} treat API-key + * requests as "no JWT bound" without special-casing the principal type. */ @Test - @DisplayName("getUserInformation() returns Optional.empty() when the principal is an ApiKeyEntity — no JWT claims to extract.") + @DisplayName( + "getUserInformation() returns Optional.empty() when the principal is an ApiKeyEntity — no JWT claims to extract.") void shouldReturnEmptyForApiKeyPrincipal() { // GIVEN final ApiKeyEntity entity = new ApiKeyEntity(); @@ -387,7 +397,8 @@ void shouldReturnEmptyForApiKeyPrincipal() { } @Test - @DisplayName("getUserInformation() returns Optional.empty() when the principal is a bare String (e.g. anonymous, test stubs).") + @DisplayName( + "getUserInformation() returns Optional.empty() when the principal is a bare String (e.g. anonymous, test stubs).") void shouldReturnEmptyForStringPrincipal() { // GIVEN final TestingAuthenticationToken auth = @@ -407,7 +418,8 @@ void shouldReturnEmptyForStringPrincipal() { class GetPrincipalTest { @Test - @DisplayName("getPrincipal() returns an AuthenticatedPrincipal whose name is the JWT subject when the principal is a Jwt.") + @DisplayName( + "getPrincipal() returns an AuthenticatedPrincipal whose name is the JWT subject when the principal is a Jwt.") void shouldReturnAuthenticatedPrincipalForJwt() { // GIVEN final Jwt jwt = @@ -428,7 +440,8 @@ void shouldReturnAuthenticatedPrincipalForJwt() { } @Test - @DisplayName("getPrincipal() wraps a String principal into an AuthenticatedPrincipal whose name is the string itself.") + @DisplayName( + "getPrincipal() wraps a String principal into an AuthenticatedPrincipal whose name is the string itself.") void shouldReturnAuthenticatedPrincipalForStringPrincipal() { // GIVEN final TestingAuthenticationToken auth = new TestingAuthenticationToken("string-user", "pass"); @@ -442,7 +455,8 @@ void shouldReturnAuthenticatedPrincipalForStringPrincipal() { } @Test - @DisplayName("getPrincipal() passes through an existing AuthenticatedPrincipal without re-wrapping.") + @DisplayName( + "getPrincipal() passes through an existing AuthenticatedPrincipal without re-wrapping.") void shouldReturnAuthenticatedPrincipalDirectly() { // GIVEN final AuthenticatedPrincipal directPrincipal = () -> "direct-name"; @@ -543,9 +557,7 @@ void anonymousCallerHoldsAnonymousRole() { SecurityContextHolder.getContext() .setAuthentication( new AnonymousAuthenticationToken( - "key", - "anonymousUser", - List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")))); + "key", "anonymousUser", List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")))); final Set roles = authService.getRoles(); @@ -555,7 +567,8 @@ void anonymousCallerHoldsAnonymousRole() { } @Test - @DisplayName("An authenticated caller with no authorities yields an empty set — distinct from anonymous.") + @DisplayName( + "An authenticated caller with no authorities yields an empty set — distinct from anonymous.") void authenticatedCallerWithNoAuthoritiesYieldsEmptySet() { bindAuthorities(List.of()); @@ -689,7 +702,8 @@ void comparisonIsCaseSensitive() { } @Test - @DisplayName("The returned set is unmodifiable and repeated calls are unaffected by mutation attempts.") + @DisplayName( + "The returned set is unmodifiable and repeated calls are unaffected by mutation attempts.") void returnedSetIsUnmodifiable() { bindAuthorityStrings("ROLE_EMPLOYEE"); @@ -702,7 +716,8 @@ void returnedSetIsUnmodifiable() { } @Test - @DisplayName("Asking whether the caller holds the null role fails fast with NullPointerException.") + @DisplayName( + "Asking whether the caller holds the null role fails fast with NullPointerException.") void containsNullFailsFast() { bindAuthorityStrings("ROLE_EMPLOYEE"); @@ -712,7 +727,8 @@ void containsNullFailsFast() { } @Test - @DisplayName("Two calls within the same request return equal sets that can be held as a snapshot.") + @DisplayName( + "Two calls within the same request return equal sets that can be held as a snapshot.") void twoCallsReturnEqualSets() { bindAuthorityStrings("ROLE_IT-ADMIN", "ROLE_EMPLOYEE"); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/JsonAuthenticationEntryPointTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/JsonAuthenticationEntryPointTest.java index 4279a38..024f406 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/JsonAuthenticationEntryPointTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/JsonAuthenticationEntryPointTest.java @@ -15,23 +15,23 @@ import tools.jackson.databind.json.JsonMapper; /** - * Unit tests for {@link JsonAuthenticationEntryPoint} — the entry point that turns Spring - * Security {@link org.springframework.security.core.AuthenticationException}s into the uniform - * {@code 401 Unauthorized} JSON body used by both filter chains (JWT and external API-key). + * Unit tests for {@link JsonAuthenticationEntryPoint} — the entry point that turns Spring Security + * {@link org.springframework.security.core.AuthenticationException}s into the uniform {@code 401 + * Unauthorized} JSON body used by both filter chains (JWT and external API-key). * *

            What is tested

            * *

            Two production wirings — Bearer and {@code ApiKey realm="external"} — and the constructor * null-guards. For each wiring the test verifies HTTP status {@code 401}, {@code Content-Type: - * application/json}, the {@code WWW-Authenticate} header per RFC 7235 §3.1, and the JSON body - * shape {@code { "status": 401, "error": "Unauthorized", "message": "" }}. + * application/json}, the {@code WWW-Authenticate} header per RFC 7235 §3.1, and the JSON body shape + * {@code { "status": 401, "error": "Unauthorized", "message": "" }}. * *

            How it is tested

            * - *

            Plain JUnit 5, no Spring context, no Mockito. Spring's {@link MockHttpServletRequest} / - * {@link MockHttpServletResponse} provide the servlet-API plumbing without spinning up a real - * container. The body is parsed back with Jackson and asserted field-by-field via {@code - * JsonNode} — the test does not rely on string equality of the JSON output. + *

            Plain JUnit 5, no Spring context, no Mockito. Spring's {@link MockHttpServletRequest} / {@link + * MockHttpServletResponse} provide the servlet-API plumbing without spinning up a real container. + * The body is parsed back with Jackson and asserted field-by-field via {@code JsonNode} — the test + * does not rely on string equality of the JSON output. * *

            Mock-Audit. Zero mocks. {@link MockHttpServletRequest} and {@link * MockHttpServletResponse} are Spring's official servlet stubs, not Mockito mocks; the {@link @@ -91,7 +91,8 @@ void shouldRejectNullObjectMapper() { } @Test - @DisplayName("Constructor rejects a null WWW-Authenticate scheme value with NullPointerException.") + @DisplayName( + "Constructor rejects a null WWW-Authenticate scheme value with NullPointerException.") void shouldRejectNullScheme() { assertThatThrownBy(() -> new JsonAuthenticationEntryPoint(objectMapper, null)) .isInstanceOf(NullPointerException.class); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/SecurityConfigRoleTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/SecurityConfigRoleTest.java index 5a4329e..e9c8c54 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/SecurityConfigRoleTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/SecurityConfigRoleTest.java @@ -20,24 +20,24 @@ *

            What is tested

            * *

            The mapping from a JWT's {@code roles} claim onto Spring Security {@code GrantedAuthority} - * objects: each entry in the claim becomes a {@code ROLE_} authority, the claim's absence - * or emptiness yields no role authorities, and the default scope-to-authority conversion - * ({@code SCOPE_}) is preserved alongside the role mapping. These properties are what - * {@code @PreAuthorize("hasRole('ADMIN')")} and {@code hasAuthority('SCOPE_openid')} depend on, - * so any drift here silently widens or breaks authorization. + * objects: each entry in the claim becomes a {@code ROLE_} authority, the claim's absence or + * emptiness yields no role authorities, and the default scope-to-authority conversion ({@code + * SCOPE_}) is preserved alongside the role mapping. These properties are what + * {@code @PreAuthorize("hasRole('ADMIN')")} and {@code hasAuthority('SCOPE_openid')} depend on, so + * any drift here silently widens or breaks authorization. * *

            How it is tested

            * - *

            Pure JUnit 5 unit tests, no Spring context. The {@link JwtAuthenticationConverter} is - * pulled directly off a real {@link SecurityConfig} instance and exercised against - * hand-constructed {@link Jwt} instances built via {@code Jwt.withTokenValue(...)} — the - * production converter is invoked verbatim. + *

            Pure JUnit 5 unit tests, no Spring context. The {@link JwtAuthenticationConverter} is pulled + * directly off a real {@link SecurityConfig} instance and exercised against hand-constructed {@link + * Jwt} instances built via {@code Jwt.withTokenValue(...)} — the production converter is invoked + * verbatim. * - *

            Mock-Audit. One mock: {@link ApiKeyDataService} is mocked because the - * {@link SecurityConfig} constructor requires it but the role-mapping path under test never - * touches it. A real {@code ApiKeyDataService} would pull in a {@code JpaRepository} and a - * datasource for no added coverage. The mock has no stubbed methods — it serves only as a - * non-null constructor argument. + *

            Mock-Audit. One mock: {@link ApiKeyDataService} is mocked because the {@link + * SecurityConfig} constructor requires it but the role-mapping path under test never touches it. A + * real {@code ApiKeyDataService} would pull in a {@code JpaRepository} and a datasource for no + * added coverage. The mock has no stubbed methods — it serves only as a non-null constructor + * argument. */ @DisplayName("SecurityConfig JWT Role Mapping") class SecurityConfigRoleTest { @@ -73,7 +73,8 @@ void singleRoleMapped() { * roles} claim containing {@code IT-ADMIN} still yields exactly {@code ROLE_IT-ADMIN}. */ @Test - @DisplayName("The JWT converter builds authorities from the prefix constant — IT-ADMIN yields the identical ROLE_IT-ADMIN.") + @DisplayName( + "The JWT converter builds authorities from the prefix constant — IT-ADMIN yields the identical ROLE_IT-ADMIN.") void rolesClaimMappedViaPrefixConstant() { final var auth = jwtAuthenticationConverter.convert(buildJwt(List.of("IT-ADMIN"))); final Set authorities = authorityStrings(auth.getAuthorities()); @@ -89,7 +90,8 @@ void multipleRolesMapped() { } @Test - @DisplayName("A JWT without a roles claim produces zero ROLE_ authorities — no default role is granted.") + @DisplayName( + "A JWT without a roles claim produces zero ROLE_ authorities — no default role is granted.") void missingRolesClaimNoAuthorities() { final var auth = jwtAuthenticationConverter.convert(buildJwt(null)); final Set authorities = authorityStrings(auth.getAuthorities()); @@ -97,7 +99,8 @@ void missingRolesClaimNoAuthorities() { } @Test - @DisplayName("An empty roles array produces zero ROLE_ authorities — empty array is treated like a missing claim.") + @DisplayName( + "An empty roles array produces zero ROLE_ authorities — empty array is treated like a missing claim.") void emptyRolesNoAuthorities() { final var auth = jwtAuthenticationConverter.convert(buildJwt(List.of())); final Set authorities = authorityStrings(auth.getAuthorities()); @@ -105,14 +108,15 @@ void emptyRolesNoAuthorities() { } /** - * The custom role-mapping does not replace the default {@code scope}-based authority - * extraction — both run, so a JWT with {@code scope="openid profile"} and {@code roles=[ADMIN]} - * yields {@code SCOPE_openid}, {@code SCOPE_profile}, and {@code ROLE_ADMIN} side-by-side. - * Pins this so that switching to a role-only converter would break {@code hasAuthority('SCOPE_*')} - * checks elsewhere. + * The custom role-mapping does not replace the default {@code scope}-based authority extraction — + * both run, so a JWT with {@code scope="openid profile"} and {@code roles=[ADMIN]} yields {@code + * SCOPE_openid}, {@code SCOPE_profile}, and {@code ROLE_ADMIN} side-by-side. Pins this so that + * switching to a role-only converter would break {@code hasAuthority('SCOPE_*')} checks + * elsewhere. */ @Test - @DisplayName("Scope-based authorities (SCOPE_*) and role-based authorities (ROLE_*) coexist on the same JWT.") + @DisplayName( + "Scope-based authorities (SCOPE_*) and role-based authorities (ROLE_*) coexist on the same JWT.") void scopeAuthoritiesPreserved() { final Jwt jwt = Jwt.withTokenValue("mock-token") diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/apikey/ApiKeyAuthenticationFilterTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/apikey/ApiKeyAuthenticationFilterTest.java index 6a11e73..093f2b6 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/apikey/ApiKeyAuthenticationFilterTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/apikey/ApiKeyAuthenticationFilterTest.java @@ -27,57 +27,55 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.context.SecurityContextHolder; import tools.jackson.databind.JsonNode; -import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; /** - * Unit tests for {@link ApiKeyAuthenticationFilter} — the Spring Security filter that - * authenticates external requests via the {@code X-API-Key} header. + * Unit tests for {@link ApiKeyAuthenticationFilter} — the Spring Security filter that authenticates + * external requests via the {@code X-API-Key} header. * *

            What is tested

            * *

            Three filter behaviours are verified: * *

              - *
            1. Header-driven activation. Requests without an {@code X-API-Key} header pass - * straight to the next filter without touching {@link ApiKeyDataService} and leave the - * {@link SecurityContextHolder} untouched — the filter must never block JWT-authenticated - * traffic. - *
            2. Invalid key rejection. A presented but unrecognised key produces a uniform JSON - * 401 body via {@link JsonAuthenticationEntryPoint} with a {@code WWW-Authenticate} header, - * and the filter chain is short-circuited before the controller runs. + *
            3. Header-driven activation. Requests without an {@code X-API-Key} header pass straight + * to the next filter without touching {@link ApiKeyDataService} and leave the {@link + * SecurityContextHolder} untouched — the filter must never block JWT-authenticated traffic. + *
            4. Invalid key rejection. A presented but unrecognised key produces a uniform JSON 401 + * body via {@link JsonAuthenticationEntryPoint} with a {@code WWW-Authenticate} header, and + * the filter chain is short-circuited before the controller runs. *
            5. Valid key authentication. A recognised key installs an {@link ApiKeyEntity} as the - * principal with the {@code ROLE_API_KEY} authority and lets the request proceed — - * regardless of HTTP method (GET, HEAD, OPTIONS, POST). Method-level enforcement is - * deliberately a separate concern handled by {@code @PreAuthorize}. + * principal with the {@code ROLE_API_KEY} authority and lets the request proceed — regardless + * of HTTP method (GET, HEAD, OPTIONS, POST). Method-level enforcement is deliberately a + * separate concern handled by {@code @PreAuthorize}. *
            * - *

            Constructor null-rejection is also pinned: both collaborators must be non-null at - * construction so a misconfigured Spring context fails fast. + *

            Constructor null-rejection is also pinned: both collaborators must be non-null at construction + * so a misconfigured Spring context fails fast. * *

            How it is tested

            * - *

            Pure JUnit 5 unit tests, no Spring context. {@link MockHttpServletRequest} and - * {@link MockHttpServletResponse} drive the filter directly via {@code doFilterInternal}; the - * {@link SecurityContextHolder} is reset in {@code @AfterEach}. + *

            Pure JUnit 5 unit tests, no Spring context. {@link MockHttpServletRequest} and {@link + * MockHttpServletResponse} drive the filter directly via {@code doFilterInternal}; the {@link + * SecurityContextHolder} is reset in {@code @AfterEach}. * *

            Mock-Audit. Two mocks: * *

              *
            • {@link ApiKeyDataService} — mocked so we can stub {@code authenticate(...)} to return * {@code Optional.empty()} or {@code Optional.of(entity)} on demand. A real service would - * require a {@code JpaRepository}, a datasource, and seeded rows for every permutation; - * the filter under test only cares about the return value of {@code authenticate(...)}, - * so mocking is the right granularity. + * require a {@code JpaRepository}, a datasource, and seeded rows for every permutation; the + * filter under test only cares about the return value of {@code authenticate(...)}, so + * mocking is the right granularity. *
            • {@link FilterChain} — mocked because the filter's job is to call (or not call) - * {@code doFilter(...)} on the next link in the chain; the assertions are - * {@code verify(filterChain).doFilter(...)} and {@code verify(filterChain, never())...}, - * which is exactly what a mock is for. A real chain would require wiring a downstream - * servlet, which adds no coverage. + * {@code doFilter(...)} on the next link in the chain; the assertions are {@code + * verify(filterChain).doFilter(...)} and {@code verify(filterChain, never())...}, which is + * exactly what a mock is for. A real chain would require wiring a downstream servlet, which + * adds no coverage. *
            * - *

            The {@link JsonAuthenticationEntryPoint} is constructed for real (no mock) so the actual - * JSON shape and the {@code WWW-Authenticate} header value are pinned by the test. + *

            The {@link JsonAuthenticationEntryPoint} is constructed for real (no mock) so the actual JSON + * shape and the {@code WWW-Authenticate} header value are pinned by the test. */ @DisplayName("ApiKeyAuthenticationFilter") class ApiKeyAuthenticationFilterTest { @@ -109,7 +107,8 @@ private static ApiKeyEntity createValidEntity() { class NoApiKeyHeaderTest { @Test - @DisplayName("Without an X-API-Key header the filter passes through silently — ApiKeyDataService is never called and the SecurityContext is untouched.") + @DisplayName( + "Without an X-API-Key header the filter passes through silently — ApiKeyDataService is never called and the SecurityContext is untouched.") void shouldPassThroughToNextFilter() throws ServletException, IOException { // GIVEN final MockHttpServletRequest request = @@ -131,14 +130,15 @@ void shouldPassThroughToNextFilter() throws ServletException, IOException { class InvalidApiKeyTest { /** - * Pins the rejected-key response shape: status 401, content-type {@code application/json}, - * a {@code WWW-Authenticate: ApiKey realm="external"} header, and a JSON body with - * {@code status}, {@code error}, and {@code message} fields. The filter chain is short- - * circuited — {@code doFilter} is never invoked. External clients depend on this exact - * shape; widening it (e.g. plain text) would break their error handlers. + * Pins the rejected-key response shape: status 401, content-type {@code application/json}, a + * {@code WWW-Authenticate: ApiKey realm="external"} header, and a JSON body with {@code + * status}, {@code error}, and {@code message} fields. The filter chain is short- circuited — + * {@code doFilter} is never invoked. External clients depend on this exact shape; widening it + * (e.g. plain text) would break their error handlers. */ @Test - @DisplayName("An unrecognised X-API-Key produces a 401 JSON body with a WWW-Authenticate header and short-circuits the filter chain.") + @DisplayName( + "An unrecognised X-API-Key produces a 401 JSON body with a WWW-Authenticate header and short-circuits the filter chain.") void shouldReturn401WithUniformJsonBody() throws ServletException, IOException { // GIVEN final MockHttpServletRequest request = @@ -168,7 +168,8 @@ void shouldReturn401WithUniformJsonBody() throws ServletException, IOException { class ValidApiKeyTest { @Test - @DisplayName("A valid X-API-Key on a GET request installs the ApiKeyEntity as the SecurityContext principal and lets the chain proceed.") + @DisplayName( + "A valid X-API-Key on a GET request installs the ApiKeyEntity as the SecurityContext principal and lets the chain proceed.") void shouldAuthenticateForGetRequest() throws ServletException, IOException { // GIVEN final ApiKeyEntity entity = createValidEntity(); @@ -191,7 +192,8 @@ void shouldAuthenticateForGetRequest() throws ServletException, IOException { } @Test - @DisplayName("A valid X-API-Key on a HEAD request authenticates and proceeds — HEAD is a read-only method.") + @DisplayName( + "A valid X-API-Key on a HEAD request authenticates and proceeds — HEAD is a read-only method.") void shouldAuthenticateForHeadRequest() throws ServletException, IOException { // GIVEN final ApiKeyEntity entity = createValidEntity(); @@ -210,7 +212,8 @@ void shouldAuthenticateForHeadRequest() throws ServletException, IOException { } @Test - @DisplayName("A valid X-API-Key on an OPTIONS request authenticates and proceeds — CORS preflight is accepted.") + @DisplayName( + "A valid X-API-Key on an OPTIONS request authenticates and proceeds — CORS preflight is accepted.") void shouldAuthenticateForOptionsRequest() throws ServletException, IOException { // GIVEN final ApiKeyEntity entity = createValidEntity(); @@ -230,12 +233,13 @@ void shouldAuthenticateForOptionsRequest() throws ServletException, IOException /** * The filter authenticates POST requests too — it does not police HTTP methods. Method-level - * authorization is the chain's job (e.g. {@code @PreAuthorize} or a request matcher) so a - * 403 for a forbidden write surface comes from later in the chain, not from this filter. - * Pins the separation of concerns. + * authorization is the chain's job (e.g. {@code @PreAuthorize} or a request matcher) so a 403 + * for a forbidden write surface comes from later in the chain, not from this filter. Pins the + * separation of concerns. */ @Test - @DisplayName("A valid X-API-Key on a POST request authenticates without enforcing the method — chain decides write access.") + @DisplayName( + "A valid X-API-Key on a POST request authenticates without enforcing the method — chain decides write access.") void shouldAuthenticatePostRequestWithoutEnforcingMethod() throws ServletException, IOException { // GIVEN @@ -259,7 +263,8 @@ void shouldAuthenticatePostRequestWithoutEnforcingMethod() } @Test - @DisplayName("An authenticated API-key request carries the ROLE_API_KEY GrantedAuthority — distinguishable from JWT principals.") + @DisplayName( + "An authenticated API-key request carries the ROLE_API_KEY GrantedAuthority — distinguishable from JWT principals.") void shouldHaveApiKeyRole() throws ServletException, IOException { // GIVEN final ApiKeyEntity entity = createValidEntity(); @@ -279,14 +284,16 @@ void shouldHaveApiKeyRole() throws ServletException, IOException { } @Test - @DisplayName("Constructor rejects a null ApiKeyDataService with NullPointerException — misconfigured context fails fast.") + @DisplayName( + "Constructor rejects a null ApiKeyDataService with NullPointerException — misconfigured context fails fast.") void shouldRejectNullApiKeyService() { assertThatThrownBy(() -> new ApiKeyAuthenticationFilter(null, entryPoint)) .isInstanceOf(NullPointerException.class); } @Test - @DisplayName("Constructor rejects a null JsonAuthenticationEntryPoint with NullPointerException — misconfigured context fails fast.") + @DisplayName( + "Constructor rejects a null JsonAuthenticationEntryPoint with NullPointerException — misconfigured context fails fast.") void shouldRejectNullEntryPoint() { assertThatThrownBy(() -> new ApiKeyAuthenticationFilter(apiKeyService, null)) .isInstanceOf(NullPointerException.class); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/roles/RolesTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/roles/RolesTest.java index 4b9b6c5..60e00ee 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/roles/RolesTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/roles/RolesTest.java @@ -31,15 +31,15 @@ * *

            Pure JUnit 5 unit tests, no Spring context, no mocks. The constants are asserted by literal * equality; the constructor visibility and reflection behaviour are checked via {@code - * java.lang.reflect.Constructor}. No collaborator exists for {@code Roles}, so there is nothing - * to mock and nothing to stub. + * java.lang.reflect.Constructor}. No collaborator exists for {@code Roles}, so there is nothing to + * mock and nothing to stub. */ class RolesTest { /** - * Asserts each {@code ROLE_*} constant resolves to its documented literal value — guards - * against accidental renames that would break consumer-side {@code hasRole(...)} checks and - * IdP-side claim mappings. + * Asserts each {@code ROLE_*} constant resolves to its documented literal value — guards against + * accidental renames that would break consumer-side {@code hasRole(...)} checks and IdP-side + * claim mappings. */ @Test @DisplayName("All Roles.ROLE_* constants resolve to their documented literal string values.") @@ -54,10 +54,10 @@ void constantValuesAreStable() { } /** - * Pins the three constants added in spec 017: the authority prefix (the single home of the - * {@code "ROLE_"} literal, which the library's own authority producers now reference) and the two - * mechanism-marker role names the library issues at runtime. A silent rename here would desync the - * prefix from Spring Security, or break the {@code API_KEY}/{@code ANONYMOUS} names consumers + * Pins the three constants added in spec 017: the authority prefix (the single home of the {@code + * "ROLE_"} literal, which the library's own authority producers now reference) and the two + * mechanism-marker role names the library issues at runtime. A silent rename here would desync + * the prefix from Spring Security, or break the {@code API_KEY}/{@code ANONYMOUS} names consumers * compare against. */ @Test @@ -74,7 +74,8 @@ void authorityPrefixAndMechanismMarkerValuesAreStable() { * Static analysers (SpotBugs, PMD) raise a finding if a constants holder is instantiable. */ @Test - @DisplayName("Roles declares a private no-arg constructor so static analysers accept it as a utility class.") + @DisplayName( + "Roles declares a private no-arg constructor so static analysers accept it as a utility class.") void constructorIsPrivate() throws NoSuchMethodException { final Constructor constructor = Roles.class.getDeclaredConstructor(); assertTrue( @@ -83,12 +84,13 @@ void constructorIsPrivate() throws NoSuchMethodException { } /** - * Confirms ordinary reflection cannot instantiate {@code Roles} — {@code newInstance()} - * without {@code setAccessible(true)} throws {@link IllegalAccessException}. Documents that - * the private constructor is real protection against casual misuse. + * Confirms ordinary reflection cannot instantiate {@code Roles} — {@code newInstance()} without + * {@code setAccessible(true)} throws {@link IllegalAccessException}. Documents that the private + * constructor is real protection against casual misuse. */ @Test - @DisplayName("Reflective newInstance() on Roles throws IllegalAccessException without setAccessible(true).") + @DisplayName( + "Reflective newInstance() on Roles throws IllegalAccessException without setAccessible(true).") void reflectiveInstantiationRequiresSetAccessible() throws NoSuchMethodException { final Constructor constructor = Roles.class.getDeclaredConstructor(); assertThrows(IllegalAccessException.class, constructor::newInstance); @@ -97,11 +99,12 @@ void reflectiveInstantiationRequiresSetAccessible() throws NoSuchMethodException /** * Documents the boundary of the private-constructor lock: with {@code setAccessible(true)} a * caller can instantiate {@code Roles} — Java reflection can always bypass access - * modifiers. The lock is a hygiene marker for static analysis, not a runtime security - * guarantee. This test exists so future readers do not misinterpret the lock as enforced. + * modifiers. The lock is a hygiene marker for static analysis, not a runtime security guarantee. + * This test exists so future readers do not misinterpret the lock as enforced. */ @Test - @DisplayName("setAccessible(true) still bypasses the private constructor — the lock is hygiene, not security.") + @DisplayName( + "setAccessible(true) still bypasses the private constructor — the lock is hygiene, not security.") void reflectiveInstantiationStillPossibleWithSetAccessible() throws NoSuchMethodException, InstantiationException, diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserDtoTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserDtoTest.java index a479c3b..e93cc03 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserDtoTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserDtoTest.java @@ -15,25 +15,25 @@ * *

            The straight-through copy of {@code id}, {@code name}, {@code email}, and {@code avatarUrl} * from {@link UserEntity} to {@link UserDto}, including the nullable contract for the optional - * fields — a {@code UserEntity} with no email and no avatar URL must produce a {@code UserDto} - * with {@code null} for both, not a default string. This is the boundary that controllers and - * SCIM provisioners cross when serialising users to JSON, so a silent change here would alter - * the wire format. + * fields — a {@code UserEntity} with no email and no avatar URL must produce a {@code UserDto} with + * {@code null} for both, not a default string. This is the boundary that controllers and SCIM + * provisioners cross when serialising users to JSON, so a silent change here would alter the wire + * format. * *

            How it is tested

            * - *

            Pure JUnit 5 unit tests. Real {@link UserEntity} instances are populated via their setters - * and passed straight to {@code UserDto.fromEntity(...)}; the resulting DTO is asserted - * field-by-field. + *

            Pure JUnit 5 unit tests. Real {@link UserEntity} instances are populated via their setters and + * passed straight to {@code UserDto.fromEntity(...)}; the resulting DTO is asserted field-by-field. * - *

            Mock-Audit. Zero mocks. The mapper is a pure function over POJOs — there is nothing - * to mock and nothing to stub. + *

            Mock-Audit. Zero mocks. The mapper is a pure function over POJOs — there is nothing to + * mock and nothing to stub. */ @DisplayName("UserDto") class UserDtoTest { @Test - @DisplayName("fromEntity(...) copies id, name, email and avatarUrl from a fully populated UserEntity onto the UserDto.") + @DisplayName( + "fromEntity(...) copies id, name, email and avatarUrl from a fully populated UserEntity onto the UserDto.") void shouldConvertFromEntityWithAvatarUrl() { // GIVEN final UUID id = UUID.randomUUID(); @@ -55,7 +55,8 @@ void shouldConvertFromEntityWithAvatarUrl() { } @Test - @DisplayName("A UserEntity with null email and null avatarUrl produces a UserDto with null for both — no defaults are invented.") + @DisplayName( + "A UserEntity with null email and null avatarUrl produces a UserDto with null for both — no defaults are invented.") void shouldConvertFromEntityWithoutAvatarUrl() { // GIVEN final UserEntity entity = new UserEntity(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserEntityPrincipalDirectoryTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserEntityPrincipalDirectoryTest.java index 7e78039..60de797 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserEntityPrincipalDirectoryTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserEntityPrincipalDirectoryTest.java @@ -24,9 +24,9 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Integration tests for {@link UserEntityPrincipalDirectory} — the bridge between - * {@link PrincipalDirectory} (spec 010's port, temporarily owned by 012) and the - * {@link UserEntity} data model. + * Integration tests for {@link UserEntityPrincipalDirectory} — the bridge between {@link + * PrincipalDirectory} (spec 010's port, temporarily owned by 012) and the {@link UserEntity} data + * model. * *

            What is tested

            * @@ -34,11 +34,11 @@ * *
              *
            1. Lookup is by {@code externalId}, never by {@code sub}. A row whose {@code sub} - * happens to equal the queried value but whose {@code externalId} does not must - * not resolve — the directory is a SCIM-side resolver, not a JWT-side one. - *
            2. Inactive users are returned, not filtered. The directory exposes the {@code - * active} flag verbatim and lets the introspector layer decide whether to allow the - * request. Filtering here would silently mask deactivations from the audit trail. + * happens to equal the queried value but whose {@code externalId} does not must not + * resolve — the directory is a SCIM-side resolver, not a JWT-side one. + *
            3. Inactive users are returned, not filtered. The directory exposes the {@code active} + * flag verbatim and lets the introspector layer decide whether to allow the request. + * Filtering here would silently mask deactivations from the audit trail. *
            4. Unknown subjects return {@link Optional#empty()} rather than throwing, so callers * can use a plain {@code Optional} flow. *
            5. Null subject reference is rejected with NPE — fail-fast on misuse. @@ -46,14 +46,14 @@ * *

              How it is tested

              * - *

              {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * starts Postgres via Testcontainers. The full JPA stack is in play — {@link UserRepository} - * and {@link UserEntityPrincipalDirectory} are real beans driven against a real database, so - * the lookup-by-column behaviour is exercised verbatim. {@code @BeforeEach} clears all rows - * except {@link SystemUser#ID} to keep each test isolated. + *

              {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} starts + * Postgres via Testcontainers. The full JPA stack is in play — {@link UserRepository} and {@link + * UserEntityPrincipalDirectory} are real beans driven against a real database, so the + * lookup-by-column behaviour is exercised verbatim. {@code @BeforeEach} clears all rows except + * {@link SystemUser#ID} to keep each test isolated. * - *

              Mock-Audit. Zero mocks. Every collaborator (repository, directory, database) is - * real — the test asserts the contract end-to-end. + *

              Mock-Audit. Zero mocks. Every collaborator (repository, directory, database) is real — + * the test asserts the contract end-to-end. */ @SpringBootTest(classes = TestApplication.class) @Import(PostgresTestConfiguration.class) @@ -101,7 +101,8 @@ private UserEntity persist( } @Test - @DisplayName("resolveUser(externalId) returns a ResolvedPrincipal carrying subjectRef, displayName, active=true, and empty roles/groups.") + @DisplayName( + "resolveUser(externalId) returns a ResolvedPrincipal carrying subjectRef, displayName, active=true, and empty roles/groups.") void resolvesActiveUserByExternalId() { persist("sub-alice", "alice-ext", "alice", "Alice"); @@ -117,12 +118,13 @@ void resolvesActiveUserByExternalId() { } /** - * The directory deliberately does not filter inactive users — it surfaces the {@code active} - * flag verbatim and lets the introspector layer decide whether the request proceeds. - * Filtering here would mask deactivations from logs and audit trails. + * The directory deliberately does not filter inactive users — it surfaces the {@code active} flag + * verbatim and lets the introspector layer decide whether the request proceeds. Filtering here + * would mask deactivations from logs and audit trails. */ @Test - @DisplayName("resolveUser(...) returns the row for inactive users with active=false — filtering is the introspector's job, not the directory's.") + @DisplayName( + "resolveUser(...) returns the row for inactive users with active=false — filtering is the introspector's job, not the directory's.") void resolvesInactiveUserAsInactive() { persist("sub-bob", "bob-ext", "bob", "Bob", false); @@ -134,7 +136,8 @@ void resolvesInactiveUserAsInactive() { } @Test - @DisplayName("resolveUser(...) returns Optional.empty() for an unknown externalId rather than throwing.") + @DisplayName( + "resolveUser(...) returns Optional.empty() for an unknown externalId rather than throwing.") void returnsEmptyForUnknownExternalId() { persist("sub-known", "known-ext", "known", "Known"); @@ -142,14 +145,14 @@ void returnsEmptyForUnknownExternalId() { } /** - * Critical contract: a query whose value matches a row's {@code sub} but not its - * {@code externalId} must miss. Some IdPs use different identifiers on the OIDC side (sub) - * and the SCIM side (externalId); the directory is a SCIM-facing resolver, so it must use - * the SCIM identifier exclusively. A regression here would silently cross-pollinate the - * two identifier spaces. + * Critical contract: a query whose value matches a row's {@code sub} but not its {@code + * externalId} must miss. Some IdPs use different identifiers on the OIDC side (sub) and the SCIM + * side (externalId); the directory is a SCIM-facing resolver, so it must use the SCIM identifier + * exclusively. A regression here would silently cross-pollinate the two identifier spaces. */ @Test - @DisplayName("Lookup matches on externalId only — a row whose sub equals the queried value but whose externalId does not must NOT resolve.") + @DisplayName( + "Lookup matches on externalId only — a row whose sub equals the queried value but whose externalId does not must NOT resolve.") void lookupIsByExternalIdNotBySub() { // User has distinct sub and externalId — common for IdPs that use different identifiers. persist("S1", "X1", "user-s1-x1", "S1 user"); @@ -161,9 +164,9 @@ void lookupIsByExternalIdNotBySub() { } @Test - @DisplayName("resolveUser(null) throws NullPointerException — fail fast on caller misuse rather than issuing a null-keyed query.") + @DisplayName( + "resolveUser(null) throws NullPointerException — fail fast on caller misuse rather than issuing a null-keyed query.") void rejectsNullSubjectRef() { - assertThatThrownBy(() -> directory.resolveUser(null)) - .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> directory.resolveUser(null)).isInstanceOf(NullPointerException.class); } } diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserRepositorySchemaTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserRepositorySchemaTest.java index d53139f..adda496 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserRepositorySchemaTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserRepositorySchemaTest.java @@ -30,32 +30,31 @@ *

              Five categories of schema contract are pinned against Postgres: * *

                - *
              1. Finder methods. {@code findByExternalId} and {@code findByUserName} return - * {@code Optional.of(row)} on hit and {@code Optional.empty()} on miss — the JPA derived - * query methods must actually be wired through. - *
              2. Unique indexes on {@code external_id} and {@code user_name}. A duplicate insert - * on either column raises {@link DataIntegrityViolationException}, surfaced from - * Postgres's unique-index violation. {@code UserService}'s race-recovery path depends on - * these violations being thrown. - *
              3. {@code sub} unique constraint is unchanged. Spec 012 relaxed the column to - * nullable but kept its uniqueness — two rows sharing a non-null {@code sub} must still - * collide. - *
              4. Nullable {@code sub} and {@code external_id}. Multiple rows with {@code null} - * on either column must coexist — SCIM-pre-provisioned rows have no {@code sub} yet, and - * legacy rows may have no {@code external_id}. - *
              5. {@code user_name NOT NULL} plus {@code active} default. Every row must have a - * {@code user_name} (no fallback at the schema level); {@code active} defaults to - * {@code true} and round-trips through {@code false} cleanly. + *
              6. Finder methods. {@code findByExternalId} and {@code findByUserName} return {@code + * Optional.of(row)} on hit and {@code Optional.empty()} on miss — the JPA derived query + * methods must actually be wired through. + *
              7. Unique indexes on {@code external_id} and {@code user_name}. A duplicate insert on + * either column raises {@link DataIntegrityViolationException}, surfaced from Postgres's + * unique-index violation. {@code UserService}'s race-recovery path depends on these + * violations being thrown. + *
              8. {@code sub} unique constraint is unchanged. Spec 012 relaxed the column to nullable + * but kept its uniqueness — two rows sharing a non-null {@code sub} must still collide. + *
              9. Nullable {@code sub} and {@code external_id}. Multiple rows with {@code null} on + * either column must coexist — SCIM-pre-provisioned rows have no {@code sub} yet, and legacy + * rows may have no {@code external_id}. + *
              10. {@code user_name NOT NULL} plus {@code active} default. Every row must have a {@code + * user_name} (no fallback at the schema level); {@code active} defaults to {@code true} and + * round-trips through {@code false} cleanly. *
              * *

              How it is tested

              * - *

              {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * starts Postgres via Testcontainers. Real {@link UserRepository} is autowired and exercised - * through {@code saveAndFlush} — the {@code Flush} part is what makes the unique-index - * violations surface synchronously inside the test method (without it, the exception would be - * deferred to commit time and would not be assertable here). {@code @BeforeEach} clears all - * rows except {@link SystemUser#ID}. + *

              {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} starts + * Postgres via Testcontainers. Real {@link UserRepository} is autowired and exercised through + * {@code saveAndFlush} — the {@code Flush} part is what makes the unique-index violations surface + * synchronously inside the test method (without it, the exception would be deferred to commit time + * and would not be assertable here). {@code @BeforeEach} clears all rows except {@link + * SystemUser#ID}. * *

              Mock-Audit. Zero mocks. The whole point of a schema test is to verify the actual * Postgres DDL behaves as expected — any mock would defeat the purpose. @@ -128,12 +127,13 @@ void findByUserNameReturnsEmptyForUnknownHandle() { } /** - * Pins the unique index on {@code external_id}: a second insert with the same value raises - * {@link DataIntegrityViolationException} on flush. {@code UserService}'s race-recovery path - * relies on this exception being thrown synchronously. + * Pins the unique index on {@code external_id}: a second insert with the same value raises {@link + * DataIntegrityViolationException} on flush. {@code UserService}'s race-recovery path relies on + * this exception being thrown synchronously. */ @Test - @DisplayName("A duplicate external_id raises DataIntegrityViolationException on flush — unique index is enforced by Postgres.") + @DisplayName( + "A duplicate external_id raises DataIntegrityViolationException on flush — unique index is enforced by Postgres.") void externalIdUniqueConstraintIsEnforced() { userRepository.saveAndFlush(buildUser("sub-1", "id-1", "user-1", "U1")); @@ -143,13 +143,14 @@ void externalIdUniqueConstraintIsEnforced() { } /** - * Documents that the unique index on {@code external_id} does not apply to {@code - * NULL} values — multiple rows without a SCIM identifier must coexist. Postgres treats {@code - * NULL} as distinct from {@code NULL} for unique-index purposes, which is the desired - * behaviour here (legacy rows have no external_id yet). + * Documents that the unique index on {@code external_id} does not apply to {@code NULL} + * values — multiple rows without a SCIM identifier must coexist. Postgres treats {@code NULL} as + * distinct from {@code NULL} for unique-index purposes, which is the desired behaviour here + * (legacy rows have no external_id yet). */ @Test - @DisplayName("Multiple rows with null external_id coexist — the unique index treats NULLs as distinct (Postgres default).") + @DisplayName( + "Multiple rows with null external_id coexist — the unique index treats NULLs as distinct (Postgres default).") void twoUsersWithNullExternalIdCoexist() { userRepository.saveAndFlush(buildUser("sub-x", null, "user-x", "X")); userRepository.saveAndFlush(buildUser("sub-y", null, "user-y", "Y")); @@ -161,25 +162,24 @@ void twoUsersWithNullExternalIdCoexist() { } @Test - @DisplayName("Saving a row with a null user_name fails — the column is NOT NULL at the schema level.") + @DisplayName( + "Saving a row with a null user_name fails — the column is NOT NULL at the schema level.") void userNameNotNullConstraintIsEnforced() { final UserEntity user = new UserEntity(); user.setSub("sub-no-username"); user.setName("No Username"); // userName intentionally not set - assertThatThrownBy(() -> userRepository.saveAndFlush(user)) - .isInstanceOf(Exception.class); + assertThatThrownBy(() -> userRepository.saveAndFlush(user)).isInstanceOf(Exception.class); } @Test - @DisplayName("A duplicate user_name raises DataIntegrityViolationException — the column carries a unique index.") + @DisplayName( + "A duplicate user_name raises DataIntegrityViolationException — the column carries a unique index.") void userNameUniqueConstraintIsEnforced() { userRepository.saveAndFlush(buildUser("sub-a1", "ext-a1", "shared-handle", "A1")); assertThatThrownBy( - () -> - userRepository.saveAndFlush( - buildUser("sub-a2", "ext-a2", "shared-handle", "A2"))) + () -> userRepository.saveAndFlush(buildUser("sub-a2", "ext-a2", "shared-handle", "A2"))) .isInstanceOf(DataIntegrityViolationException.class); } @@ -188,24 +188,24 @@ void userNameUniqueConstraintIsEnforced() { * against accidentally widening the column to allow duplicates as part of the same migration. */ @Test - @DisplayName("A duplicate non-null sub still raises DataIntegrityViolationException — spec 012 kept the unique constraint.") + @DisplayName( + "A duplicate non-null sub still raises DataIntegrityViolationException — spec 012 kept the unique constraint.") void subUniqueConstraintIsUnchanged() { userRepository.saveAndFlush(buildUser("shared-sub", "ext-c1", "user-c1", "C1")); assertThatThrownBy( - () -> - userRepository.saveAndFlush( - buildUser("shared-sub", "ext-c2", "user-c2", "C2"))) + () -> userRepository.saveAndFlush(buildUser("shared-sub", "ext-c2", "user-c2", "C2"))) .isInstanceOf(DataIntegrityViolationException.class); } /** - * Symmetric to the null-{@code external_id} case: SCIM-pre-provisioned rows have no - * {@code sub} yet, so multiple null-{@code sub} rows must coexist. Pins the desired Postgres - * behaviour that {@code NULL} is distinct from {@code NULL} for the unique index. + * Symmetric to the null-{@code external_id} case: SCIM-pre-provisioned rows have no {@code sub} + * yet, so multiple null-{@code sub} rows must coexist. Pins the desired Postgres behaviour that + * {@code NULL} is distinct from {@code NULL} for the unique index. */ @Test - @DisplayName("Multiple rows with null sub coexist — SCIM-pre-provisioned rows have no sub yet, and the unique index treats NULLs as distinct.") + @DisplayName( + "Multiple rows with null sub coexist — SCIM-pre-provisioned rows have no sub yet, and the unique index treats NULLs as distinct.") void twoUsersWithNullSubCoexist() { // sub is now nullable — SCIM-pre-provisioned rows have no sub yet. userRepository.saveAndFlush(buildUser(null, "ext-no-sub-1", "user-ns1", "NS1")); @@ -227,7 +227,8 @@ void activeDefaultsToTrueOnFreshEntity() { } @Test - @DisplayName("The active flag round-trips through false and back to true — toggling persists and reloads correctly.") + @DisplayName( + "The active flag round-trips through false and back to true — toggling persists and reloads correctly.") void activeCanBeFlippedToFalseAndBack() { final UserEntity persisted = userRepository.saveAndFlush(buildUser("sub-flip", "ext-flip", "user-flip", "F")); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceActiveGateIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceActiveGateIntegrationTest.java index bf0f32a..fb191a4 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceActiveGateIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceActiveGateIntegrationTest.java @@ -19,11 +19,11 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.context.annotation.Import; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.access.AccessDeniedException; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.testcontainers.junit.jupiter.Testcontainers; /** @@ -34,26 +34,26 @@ *

              What is tested

              * *

              The active-gate contract end-to-end: an existing user whose {@code active} flag has been - * flipped to {@code false} must be denied on the next interactive login; a subsequent - * reactivation must restore access against the very same row (same id). A SCIM-pre-provisioned - * row that is created inactive must not be JIT-bootstrapped — the {@code sub} column stays - * {@code null} after the denial, so an attacker who knows the {@code externalId} cannot silently - * claim a deactivated row. Newly JIT-created users start out active. And the disambiguation - * guard for the email-as-userName fallback path is verified: two distinct JWT subjects that fall - * back to the same email-as-userName collide on the unique constraint instead of being merged. + * flipped to {@code false} must be denied on the next interactive login; a subsequent reactivation + * must restore access against the very same row (same id). A SCIM-pre-provisioned row that is + * created inactive must not be JIT-bootstrapped — the {@code sub} column stays {@code null} after + * the denial, so an attacker who knows the {@code externalId} cannot silently claim a deactivated + * row. Newly JIT-created users start out active. And the disambiguation guard for the + * email-as-userName fallback path is verified: two distinct JWT subjects that fall back to the same + * email-as-userName collide on the unique constraint instead of being merged. * *

              How it is tested

              * - *

              {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * spins up a real Postgres via Testcontainers. Each test runs in the application's normal - * transactional configuration — entities are flushed and reloaded across transactions so the - * assertions reflect what is durably in the database, not just the session cache. + *

              {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} spins + * up a real Postgres via Testcontainers. Each test runs in the application's normal transactional + * configuration — entities are flushed and reloaded across transactions so the assertions reflect + * what is durably in the database, not just the session cache. * - *

              Mock-Audit. A single {@code @MockitoBean AuthService} is the only mock. The real - * {@code AuthService} would require a Spring Security {@code SecurityContextHolder} populated by - * the filter chain, which these tests deliberately bypass to drive {@code getCurrentUserEntity()} - * directly. The {@code UserService}, {@link UserRepository}, and {@code UserProvisioner} under - * test are all real beans backed by real Postgres — no other mocks are introduced. + *

              Mock-Audit. A single {@code @MockitoBean AuthService} is the only mock. The real {@code + * AuthService} would require a Spring Security {@code SecurityContextHolder} populated by the + * filter chain, which these tests deliberately bypass to drive {@code getCurrentUserEntity()} + * directly. The {@code UserService}, {@link UserRepository}, and {@code UserProvisioner} under test + * are all real beans backed by real Postgres — no other mocks are introduced. */ @SpringBootTest(classes = TestApplication.class) @Import(PostgresTestConfiguration.class) @@ -85,7 +85,8 @@ void cleanUsers() { private void stubAuth(final String sub) { when(authService.getUserInformation()) .thenReturn( - Optional.of(new UserInformation(sub, "User " + sub, sub + "@example.com", null, sub, sub))); + Optional.of( + new UserInformation(sub, "User " + sub, sub + "@example.com", null, sub, sub))); } @Test @@ -125,9 +126,9 @@ void reactivationRestoresAccess() { /** * Verifies, at the Postgres layer, the same safety property the unit test asserts in isolation: * an inactive SCIM-pre-provisioned row matched by {@code externalId} must reject the login - * before the JIT back-fill writes the JWT {@code sub} onto it. The row is reloaded - * after the denial and {@code sub} is asserted still {@code null} — proving an attacker who - * knows the {@code externalId} cannot silently claim a deactivated row by attempting a login. + * before the JIT back-fill writes the JWT {@code sub} onto it. The row is reloaded after + * the denial and {@code sub} is asserted still {@code null} — proving an attacker who knows the + * {@code externalId} cannot silently claim a deactivated row by attempting a login. */ @Test @DisplayName( @@ -157,7 +158,8 @@ void scimPreProvisionedInactiveUserCannotJitBootstrap() { } @Test - @DisplayName("A user provisioned through the JIT path on first login is always created with active=true.") + @DisplayName( + "A user provisioned through the JIT path on first login is always created with active=true.") void newUserCreatedByJitIsAlwaysActive() { stubAuth("fresh-int"); final UserEntity user = userService.getCurrentUserEntity(); @@ -165,13 +167,13 @@ void newUserCreatedByJitIsAlwaysActive() { } /** - * Pins the disambiguation guard: when two distinct JWT subjects both fall back to email as - * their {@code preferred_username} (the IdP did not assert one), the second login must collide - * on the {@code user_name} unique constraint rather than be silently merged into the first - * user's row. The exact thrown type is either {@link IllegalStateException} (recovery path - * after a {@code DataIntegrityViolationException} fails to re-fetch by {@code sub}) or the - * raw {@code DataIntegrityViolationException} — both are accepted because the load-bearing - * property is "did not merge", not the wrapping. + * Pins the disambiguation guard: when two distinct JWT subjects both fall back to email as their + * {@code preferred_username} (the IdP did not assert one), the second login must collide on the + * {@code user_name} unique constraint rather than be silently merged into the first user's row. + * The exact thrown type is either {@link IllegalStateException} (recovery path after a {@code + * DataIntegrityViolationException} fails to re-fetch by {@code sub}) or the raw {@code + * DataIntegrityViolationException} — both are accepted because the load-bearing property is "did + * not merge", not the wrapping. */ @Test @DisplayName( diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceConcurrencyTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceConcurrencyTest.java index 0a97cd2..acc5984 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceConcurrencyTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceConcurrencyTest.java @@ -31,10 +31,10 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.context.annotation.Import; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.testcontainers.junit.jupiter.Testcontainers; /** @@ -50,42 +50,42 @@ *

            6. Same-{@code sub} race recovery. Ten simultaneous first-logins for the identical * {@code sub} must produce exactly one row; the nine losing inserts must be caught and * transparently recovered into a re-fetch. This exercises the {@link UserProvisioner}'s - * {@code REQUIRES_NEW} + {@code saveAndFlush} contract and the catch-and-refetch logic - * in {@code UserService}. - *
            7. Different-{@code sub} non-blocking. Ten simultaneous first-logins for ten - * distinct {@code sub} values must not serialise on a JVM monitor — confirmed by - * comparing wall-clock against a single-threaded baseline. Guards against re-introduction - * of {@code synchronized} (the pre-spec-011 anti-pattern). - *
            8. Drift sync atomicity. An existing user whose {@code name}, {@code email} and - * {@code avatarUrl} all changed at once must be flushed in a single save — Postgres-level + * {@code REQUIRES_NEW} + {@code saveAndFlush} contract and the catch-and-refetch logic in + * {@code UserService}. + *
            9. Different-{@code sub} non-blocking. Ten simultaneous first-logins for ten distinct + * {@code sub} values must not serialise on a JVM monitor — confirmed by comparing wall-clock + * against a single-threaded baseline. Guards against re-introduction of {@code synchronized} + * (the pre-spec-011 anti-pattern). + *
            10. Drift sync atomicity. An existing user whose {@code name}, {@code email} and {@code + * avatarUrl} all changed at once must be flushed in a single save — Postgres-level * confirmation of the unit-test claim. *
            * *

            How it is tested

            * - *

            {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * spins up a real Postgres via Testcontainers. The integration footprint is intentional: the - * race-recovery contract depends on Postgres's unique-index locking behaviour, which no - * in-memory database faithfully reproduces. + *

            {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} spins + * up a real Postgres via Testcontainers. The integration footprint is intentional: the + * race-recovery contract depends on Postgres's unique-index locking behaviour, which no in-memory + * database faithfully reproduces. * *

            Mock surface and justification. {@link * com.openelements.spring.base.security.AuthService} is the single {@code @MockitoBean} — it would - * otherwise require a Spring Security {@code SecurityContextHolder} populated by the filter - * chain, which the tests deliberately bypass to drive {@code getCurrentUserEntity()} directly - * on background threads. Per-thread {@code UserInformation} dispatch is implemented with a + * otherwise require a Spring Security {@code SecurityContextHolder} populated by the filter chain, + * which the tests deliberately bypass to drive {@code getCurrentUserEntity()} directly on + * background threads. Per-thread {@code UserInformation} dispatch is implemented with a * thread-local {@link java.util.concurrent.ConcurrentHashMap} consulted from the Mockito {@code - * thenAnswer} lambda. The repository, {@link UserService}, and {@link UserProvisioner} are - * real beans backed by real Postgres — no mocking of the components under test. + * thenAnswer} lambda. The repository, {@link UserService}, and {@link UserProvisioner} are real + * beans backed by real Postgres — no mocking of the components under test. * - *

            The HikariCP pool is sized to 30 in {@code application-testcontainers.properties} so that - * 10 concurrent {@code REQUIRES_NEW} provisioning attempts (2 connections per thread = - * suspended outer + active inner) do not deadlock the pool. + *

            The HikariCP pool is sized to 30 in {@code application-testcontainers.properties} so that 10 + * concurrent {@code REQUIRES_NEW} provisioning attempts (2 connections per thread = suspended outer + * + active inner) do not deadlock the pool. * *

            Load-independent. The different-{@code sub} non-blocking test no longer compares - * wall-clock times. It proves concurrency directly with a {@link CyclicBarrier} that can only - * trip when every thread is inside {@code getCurrentUserEntity()} at once, so it passes or fails - * on the actual concurrency property regardless of CI load. The only timeouts are correctness - * guards against serialisation, not performance thresholds. + * wall-clock times. It proves concurrency directly with a {@link CyclicBarrier} that can only trip + * when every thread is inside {@code getCurrentUserEntity()} at once, so it passes or fails on the + * actual concurrency property regardless of CI load. The only timeouts are correctness guards + * against serialisation, not performance thresholds. */ @SpringBootTest(classes = TestApplication.class) @Import(PostgresTestConfiguration.class) @@ -115,12 +115,12 @@ void cleanUserRowsExceptSystem() { } /** - * Spawns 10 threads that simultaneously call {@code getCurrentUserEntity()} with the same - * JWT {@code sub}. All ten threads are held on a {@link java.util.concurrent.CountDownLatch} - * to maximise the race window. Postgres's unique index serialises the inserts; nine attempts - * fail with {@code DataIntegrityViolationException}; {@code UserService} catches and re-fetches. - * The assertion is twofold: every thread observes the same {@code UserEntity.id}, and the - * database holds exactly one row for the shared {@code sub}. + * Spawns 10 threads that simultaneously call {@code getCurrentUserEntity()} with the same JWT + * {@code sub}. All ten threads are held on a {@link java.util.concurrent.CountDownLatch} to + * maximise the race window. Postgres's unique index serialises the inserts; nine attempts fail + * with {@code DataIntegrityViolationException}; {@code UserService} catches and re-fetches. The + * assertion is twofold: every thread observes the same {@code UserEntity.id}, and the database + * holds exactly one row for the shared {@code sub}. */ @Test @DisplayName( @@ -130,8 +130,7 @@ void cleanUserRowsExceptSystem() { void concurrentFirstLoginsForSameSubProduceOneRow() throws Exception { final String sharedSub = "auth0|concurrent-same"; final UserInformation info = - new UserInformation( - sharedSub, "Same User", "same@example.com", null, sharedSub, sharedSub); + new UserInformation(sharedSub, "Same User", "same@example.com", null, sharedSub, sharedSub); when(authService.getUserInformation()).thenReturn(Optional.of(info)); final int threadCount = 10; @@ -154,9 +153,7 @@ void concurrentFirstLoginsForSameSubProduceOneRow() throws Exception { observedIds.add(f.get(30, TimeUnit.SECONDS)); } - assertThat(observedIds) - .as("all threads must observe the same UserEntity.id") - .hasSize(1); + assertThat(observedIds).as("all threads must observe the same UserEntity.id").hasSize(1); final long persistedRowsForSub = userRepository.findAll().stream().filter(u -> sharedSub.equals(u.getSub())).count(); @@ -181,14 +178,14 @@ void concurrentFirstLoginsForSameSubProduceOneRow() throws Exception { *

          • If the method is not serialised (the correct state), all threads enter * concurrently, all reach the barrier, it trips immediately, and each proceeds to create * its own row. - *
          • If the method were {@code synchronized} again, only one thread could be inside at a - * time; the other nine would block on the monitor and never reach the barrier, so the - * barrier would time out — surfacing as a {@link java.util.concurrent.TimeoutException} - * and failing the test. + *
          • If the method were {@code synchronized} again, only one thread could be inside at a time; + * the other nine would block on the monitor and never reach the barrier, so the barrier + * would time out — surfacing as a {@link java.util.concurrent.TimeoutException} and failing + * the test. *
          * - *

          The only timeouts involved are correctness guards against a deadlock-like serialisation, - * not performance ratios, so the test is immune to CI load — it passes or fails on the actual + *

          The only timeouts involved are correctness guards against a deadlock-like serialisation, not + * performance ratios, so the test is immune to CI load — it passes or fails on the actual * concurrency property, deterministically. * *

          Per-thread {@code UserInformation} is dispatched via a {@link ConcurrentHashMap} keyed by @@ -264,8 +261,7 @@ void driftSyncIsTransactional() { final String sub = "auth0|drift-tx"; when(authService.getUserInformation()) .thenReturn( - Optional.of( - new UserInformation(sub, "Original", "orig@example.com", null, sub, sub))); + Optional.of(new UserInformation(sub, "Original", "orig@example.com", null, sub, sub))); final UserEntity created = userService.getCurrentUserEntity(); assertThat(created.getName()).isEqualTo("Original"); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceTest.java index 835cb98..8926f87 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/security/user/UserServiceTest.java @@ -27,33 +27,31 @@ *

          The decision logic inside {@code UserService.getCurrentUserEntity()} and {@code * getCurrentUser()}: the three-tier lookup chain ({@code findBySub → findByExternalId → * findByUserName → provision}), the drift-sync of mutable claims ({@code name}, {@code email}, - * {@code avatarUrl}), the back-fill of stable identifiers ({@code sub}, {@code externalId}, - * {@code userName}), the active-gate, and the disambiguation guard that prevents two users - * sharing the same email-as-userName fallback from being silently merged. End-to-end - * persistence (race recovery, real Postgres constraints) is covered by sibling integration - * tests — see {@link UserServiceConcurrencyTest} and {@link - * UserServiceActiveGateIntegrationTest}. + * {@code avatarUrl}), the back-fill of stable identifiers ({@code sub}, {@code externalId}, {@code + * userName}), the active-gate, and the disambiguation guard that prevents two users sharing the + * same email-as-userName fallback from being silently merged. End-to-end persistence (race + * recovery, real Postgres constraints) is covered by sibling integration tests — see {@link + * UserServiceConcurrencyTest} and {@link UserServiceActiveGateIntegrationTest}. * *

          How it is tested

          * - *

          Plain JUnit 5 with Mockito, no Spring context. The four collaborators of {@link - * UserService} — {@link UserRepository}, {@link - * org.springframework.context.ApplicationEventPublisher}, {@link + *

          Plain JUnit 5 with Mockito, no Spring context. The four collaborators of {@link UserService} — + * {@link UserRepository}, {@link org.springframework.context.ApplicationEventPublisher}, {@link * com.openelements.spring.base.security.AuthService}, {@link UserProvisioner} — are mocked. * - *

          Why mocks here are justified. {@code UserService} is a coordination layer; its job - * is to invoke its collaborators in the right sequence with the right arguments. The interesting + *

          Why mocks here are justified. {@code UserService} is a coordination layer; its job is + * to invoke its collaborators in the right sequence with the right arguments. The interesting * behaviour lives in the orchestration, not in the collaborators. Three of the four mocks have * trivial substitutes only at integration level: * *

            *
          • {@code UserRepository}: stubbing {@code findBy*(...)} return values is what lets us - * exhaustively test all paths of the three-tier lookup without spinning up Postgres for - * every permutation. + * exhaustively test all paths of the three-tier lookup without spinning up Postgres for every + * permutation. *
          • {@code AuthService}: real {@code AuthService} reads from a {@link * org.springframework.security.core.context.SecurityContextHolder} populated by the filter - * chain. Reconstructing that here would require Spring Security context plumbing for no - * added coverage — the integration test covers the contract. + * chain. Reconstructing that here would require Spring Security context plumbing for no added + * coverage — the integration test covers the contract. *
          • {@code UserProvisioner}: real {@code UserProvisioner} requires a JPA transaction with * {@code REQUIRES_NEW}. Mocking lets us assert "provision was called" without persistence * side-effects. @@ -62,9 +60,9 @@ *
          * *

          No mock has {@code Answer}-driven behaviour beyond simple {@code thenReturn} stubs and a - * single {@code thenAnswer(inv -> entityFrom(arg))} for the provisioner — there is no broad - * surface where mocks would hide bugs. The race-recovery and Postgres-constraint behaviour that - * mocks cannot legitimately exercise is verified by the Testcontainers tests. + * single {@code thenAnswer(inv -> entityFrom(arg))} for the provisioner — there is no broad surface + * where mocks would hide bugs. The race-recovery and Postgres-constraint behaviour that mocks + * cannot legitimately exercise is verified by the Testcontainers tests. */ @DisplayName("UserService") class UserServiceTest { @@ -106,8 +104,8 @@ private UserEntity entityFrom(final UserInformation info) { } /** - * Documents that {@link UserService} fail-fasts on missing collaborators — a misconfigured - * Spring context surfaces immediately, not on first request. + * Documents that {@link UserService} fail-fasts on missing collaborators — a misconfigured Spring + * context surfaces immediately, not on first request. */ @Test @DisplayName( @@ -147,7 +145,8 @@ void shouldCreateNewUserWhenNotExists() { } @Test - @DisplayName("getCurrentUser() returns the existing row without saving when the JWT claims match.") + @DisplayName( + "getCurrentUser() returns the existing row without saving when the JWT claims match.") void shouldReturnExistingUserWithoutSaving() { // GIVEN setupAuth("auth0|existing", "Same Name", "same@example.com", null); @@ -319,7 +318,8 @@ void shouldCreateUserWithoutAvatarUrlWhenClaimMissing() { class GetCurrentUserEntityTest { @Test - @DisplayName("getCurrentUserEntity() returns the managed JPA entity (not a DTO copy) for re-use in associations.") + @DisplayName( + "getCurrentUserEntity() returns the managed JPA entity (not a DTO copy) for re-use in associations.") void shouldReturnEntityForExistingUser() { // GIVEN setupAuth("auth0|entity-existing", "Same Name", "same@example.com", null); @@ -361,7 +361,8 @@ void shouldProvisionNewUserOnFirstCall() { } @Test - @DisplayName("A drifted name claim flows through to the managed entity returned by getCurrentUserEntity().") + @DisplayName( + "A drifted name claim flows through to the managed entity returned by getCurrentUserEntity().") void shouldUpdateDriftedJwtClaims() { // GIVEN — JWT now carries a different name than the DB row setupAuth("auth0|entity-drift", "New Name", "same@example.com", null); @@ -399,9 +400,10 @@ void shouldThrowWhenNoJwtBoundToRequest() { class TieredLookupTest { /** - * Verifies the short-circuit semantics of {@link java.util.Optional#or(java.util.function.Supplier)} - * in the lookup chain: once {@code findBySub} matches, {@code findByExternalId} and - * {@code findByUserName} are never queried — confirmed by Mockito's {@code verify(never())}. + * Verifies the short-circuit semantics of {@link + * java.util.Optional#or(java.util.function.Supplier)} in the lookup chain: once {@code + * findBySub} matches, {@code findByExternalId} and {@code findByUserName} are never queried — + * confirmed by Mockito's {@code verify(never())}. */ @Test @DisplayName( @@ -419,9 +421,9 @@ void findBySubTakesPrecedenceOverExternalIdAndUserName() { } /** - * Simulates the canonical SCIM-pre-provisioned row (no {@code sub}, {@code externalId} set) - * and verifies that the JIT login adopts the row — writes {@code sub} onto it via the - * back-fill path and saves once. + * Simulates the canonical SCIM-pre-provisioned row (no {@code sub}, {@code externalId} set) and + * verifies that the JIT login adopts the row — writes {@code sub} onto it via the back-fill + * path and saves once. */ @Test @DisplayName( @@ -450,9 +452,9 @@ void findByExternalIdIsUsedWhenSubMisses() { /** * Exercises the third lookup tier: row exists only under {@code userName}. Asserts that the - * adoption back-fills both {@code sub} and {@code externalId} in a single save — - * the lookup is documented as "last resort, addresses IdPs that use different identifiers - * for OIDC and SCIM." + * adoption back-fills both {@code sub} and {@code externalId} in a single save — the + * lookup is documented as "last resort, addresses IdPs that use different identifiers for OIDC + * and SCIM." */ @Test @DisplayName( @@ -549,8 +551,8 @@ void driftSyncWritesAllChangedFieldsInOneSave() { /** * Pins the back-fill-only rule for stable identifiers: even if the JWT's {@code - * preferred_username} differs from the persisted {@code userName}, the local value wins. - * Stable IdP-side identifiers must not flip mid-session. + * preferred_username} differs from the persisted {@code userName}, the local value wins. Stable + * IdP-side identifiers must not flip mid-session. */ @Test @DisplayName( @@ -558,8 +560,7 @@ void driftSyncWritesAllChangedFieldsInOneSave() { void existingUserNameIsNotOverwrittenByJwtClaim() { // userName is a stable identifier — once set, never overwritten by a later JWT. setupAuth("S", "Same Name", "same@example.com", null); - final UserEntity row = - createExistingUser("S", "Same Name", "same@example.com", null); + final UserEntity row = createExistingUser("S", "Same Name", "same@example.com", null); row.setUserName("old-username"); // explicitly different from JWT preferred_username when(userRepository.findBySub("S")).thenReturn(Optional.of(row)); @@ -585,8 +586,7 @@ void inactiveUserOnExistingRowThrowsAccessDenied() { when(userRepository.findBySub("inactive-sub")).thenReturn(Optional.of(row)); assertThatThrownBy(() -> userService.getCurrentUserEntity()) - .isInstanceOf( - org.springframework.security.access.AccessDeniedException.class) + .isInstanceOf(org.springframework.security.access.AccessDeniedException.class) .hasMessageContaining("disabled"); // No save — drift sync did not run verify(userRepository, never()).save(any()); @@ -595,8 +595,8 @@ void inactiveUserOnExistingRowThrowsAccessDenied() { /** * Critical safety property: a deactivated SCIM-pre-provisioned row, when first hit by a JIT * login, must throw before the back-fill path runs. Otherwise the row would silently - * be claimed by an attacker who happens to know the {@code externalId}. Verified by - * asserting {@code sub} remains {@code null} after the rejection. + * be claimed by an attacker who happens to know the {@code externalId}. Verified by asserting + * {@code sub} remains {@code null} after the rejection. */ @Test @DisplayName( @@ -614,8 +614,7 @@ void inactiveScimRowFoundByExternalIdThrowsBeforeWritingSub() { when(userRepository.findByExternalId("scim-sub")).thenReturn(Optional.of(row)); assertThatThrownBy(() -> userService.getCurrentUserEntity()) - .isInstanceOf( - org.springframework.security.access.AccessDeniedException.class); + .isInstanceOf(org.springframework.security.access.AccessDeniedException.class); // sub MUST NOT be written onto the deactivated row assertThat(row.getSub()).isNull(); verify(userRepository, never()).save(any()); @@ -625,8 +624,7 @@ void inactiveScimRowFoundByExternalIdThrowsBeforeWritingSub() { @DisplayName("An active user with no claim drift passes the gate and is returned unchanged.") void activeUserPassesThroughNormally() { setupAuth("active-sub", "Active", "active@example.com", null); - final UserEntity row = - createExistingUser("active-sub", "Active", "active@example.com", null); + final UserEntity row = createExistingUser("active-sub", "Active", "active@example.com", null); row.setActive(true); when(userRepository.findBySub("active-sub")).thenReturn(Optional.of(row)); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDataServiceIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDataServiceIntegrationTest.java index f8bd122..432ac54 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDataServiceIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDataServiceIntegrationTest.java @@ -18,11 +18,11 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.context.annotation.Import; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.web.server.ResponseStatusException; import org.testcontainers.junit.jupiter.Testcontainers; @@ -35,26 +35,26 @@ * SHA-256 hash and a display-only prefix stored), authentication (matching a raw key against the * stored hash and ignoring null/blank/unknown inputs), listing (pagination over persisted rows), * and deletion (a 404-mapped {@link ResponseStatusException} for unknown ids). The format of the - * generated key is locked: it must start with the {@code crm_} prefix, be 4 + 48 characters - * long, and produce a redacted {@code keyPrefix} of the form {@code crm_XXXX...XXXX}. Two keys - * created with the same name must be unique. A deleted key must no longer authenticate. + * generated key is locked: it must start with the {@code crm_} prefix, be 4 + 48 characters long, + * and produce a redacted {@code keyPrefix} of the form {@code crm_XXXX...XXXX}. Two keys created + * with the same name must be unique. A deleted key must no longer authenticate. * *

          How it is tested

          * - *

          {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * spins up a real Postgres via Testcontainers. The {@link ApiKeyDataService} bean is the real - * service, and the {@link ApiKeyRepository} is the real Spring Data repository writing to the - * containerised database. + *

          {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} spins + * up a real Postgres via Testcontainers. The {@link ApiKeyDataService} bean is the real service, + * and the {@link ApiKeyRepository} is the real Spring Data repository writing to the containerised + * database. * *

          Mock-Audit. Two {@code @MockitoBean}s: * *

            *
          • {@code UserService} — stubbed to return a static "Test Admin" {@code UserDto}. The - * service-under-test only reads {@code getCurrentUser().name()} to populate {@code - * createdBy} on new keys; a real {@code UserService} would need a JWT-authenticated - * Spring Security context, which adds no coverage to the API-key lifecycle. - *
          • {@code AuthService} — declared because other Spring components in the test context - * wire it transitively; the API-key tests themselves never read from it. + * service-under-test only reads {@code getCurrentUser().name()} to populate {@code createdBy} + * on new keys; a real {@code UserService} would need a JWT-authenticated Spring Security + * context, which adds no coverage to the API-key lifecycle. + *
          • {@code AuthService} — declared because other Spring components in the test context wire it + * transitively; the API-key tests themselves never read from it. *
          */ @SpringBootTest(classes = TestApplication.class) @@ -185,7 +185,8 @@ void shouldAuthenticateWithValidRawKey() { } @Test - @DisplayName("authenticate() returns Optional.empty() for a syntactically plausible key that does not exist.") + @DisplayName( + "authenticate() returns Optional.empty() for a syntactically plausible key that does not exist.") void shouldReturnEmptyForInvalidKey() { // WHEN final Optional result = @@ -196,7 +197,8 @@ void shouldReturnEmptyForInvalidKey() { } @Test - @DisplayName("authenticate(null) returns Optional.empty() — null is treated as a non-match, not an error.") + @DisplayName( + "authenticate(null) returns Optional.empty() — null is treated as a non-match, not an error.") void shouldReturnEmptyForNullKey() { assertThat(apiKeyDataService.authenticate(null)).isEmpty(); } @@ -227,7 +229,8 @@ void shouldNotAuthenticateAfterDeletion() { class ListTest { @Test - @DisplayName("list() on an empty table returns a Page with zero content and zero totalElements.") + @DisplayName( + "list() on an empty table returns a Page with zero content and zero totalElements.") void shouldReturnEmptyPageWhenNoKeys() { // WHEN final Page page = apiKeyDataService.list(PageRequest.of(0, 10)); @@ -279,7 +282,8 @@ void shouldSupportPagination() { class DeleteTest { @Test - @DisplayName("delete(id) for an existing key removes the row — repository.findById returns empty.") + @DisplayName( + "delete(id) for an existing key removes the row — repository.findById returns empty.") void shouldDeleteExistingKey() { // GIVEN final ApiKeyCreatedDto created = apiKeyDataService.create(new ApiKeyCreateDto("To Delete")); @@ -292,7 +296,8 @@ void shouldDeleteExistingKey() { } @Test - @DisplayName("delete(unknownId) throws ResponseStatusException — surfaces as HTTP 404 to the caller.") + @DisplayName( + "delete(unknownId) throws ResponseStatusException — surfaces as HTTP 404 to the caller.") void shouldThrow404ForNonExistentKey() { // GIVEN final UUID nonExistentId = UUID.randomUUID(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDataServiceSha256Test.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDataServiceSha256Test.java index 5d97ae2..432b7c1 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDataServiceSha256Test.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDataServiceSha256Test.java @@ -10,8 +10,7 @@ * *

          What is tested

          * - *

          The contract of the static hashing helper used to fingerprint raw API keys before - * persistence: + *

          The contract of the static hashing helper used to fingerprint raw API keys before persistence: * *

            *
          1. The output matches the canonical SHA-256 digest for a known input ({@code "hello"}) — @@ -21,14 +20,14 @@ *
          2. Different inputs map to different digests — the trivial collision-avoidance baseline. *
          3. The output is always a 64-character lower-case hex string — the {@code keyHash} column * schema depends on this length and casing. - *
          4. The empty string hashes to the canonical SHA-256 of the empty input — documents that - * the helper does no input pre-processing. + *
          5. The empty string hashes to the canonical SHA-256 of the empty input — documents that the + * helper does no input pre-processing. *
          * *

          How it is tested

          * - *

          Pure JUnit 5 with AssertJ. The helper is a pure function with no collaborators; the tests - * call it directly with string literals and compare against pre-computed expected values. + *

          Pure JUnit 5 with AssertJ. The helper is a pure function with no collaborators; the tests call + * it directly with string literals and compare against pre-computed expected values. * *

          Mock-Audit. Zero mocks. */ @@ -51,7 +50,8 @@ void shouldProduceCorrectSha256ForKnownInput() { } @Test - @DisplayName("sha256Hex is deterministic — hashing the same input twice produces identical digests.") + @DisplayName( + "sha256Hex is deterministic — hashing the same input twice produces identical digests.") void shouldProduceConsistentHashForSameInput() { // GIVEN final String input = "crm_abc123"; @@ -65,7 +65,8 @@ void shouldProduceConsistentHashForSameInput() { } @Test - @DisplayName("Different inputs map to different digests — the baseline collision-avoidance check.") + @DisplayName( + "Different inputs map to different digests — the baseline collision-avoidance check.") void shouldProduceDifferentHashesForDifferentInputs() { // WHEN final String hash1 = ApiKeyDataService.sha256Hex("key1"); @@ -76,7 +77,8 @@ void shouldProduceDifferentHashesForDifferentInputs() { } @Test - @DisplayName("sha256Hex output is always 64 lower-case hex characters — matches the keyHash column schema.") + @DisplayName( + "sha256Hex output is always 64 lower-case hex characters — matches the keyHash column schema.") void shouldReturn64CharHexString() { // WHEN final String hash = ApiKeyDataService.sha256Hex("test"); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDtoTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDtoTest.java index a419b3d..c15c218 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDtoTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/apikey/ApiKeyDtoTest.java @@ -12,14 +12,14 @@ *

          What is tested

          * *

          The entity-to-DTO projection: {@code id}, {@code name}, the display-only {@code keyPrefix}, - * and {@code createdBy} are copied across one-for-one. The mapping deliberately omits the - * {@code keyHash} field — confirming it would have been a leak from the trust boundary into a - * DTO that is returned by REST endpoints. + * and {@code createdBy} are copied across one-for-one. The mapping deliberately omits the {@code + * keyHash} field — confirming it would have been a leak from the trust boundary into a DTO that is + * returned by REST endpoints. * *

          How it is tested

          * - *

          Pure JUnit 5 with AssertJ. The test constructs an {@link ApiKeyEntity} in memory, invokes - * the static factory, and asserts each field on the resulting DTO. + *

          Pure JUnit 5 with AssertJ. The test constructs an {@link ApiKeyEntity} in memory, invokes the + * static factory, and asserts each field on the resulting DTO. * *

          Mock-Audit. Zero mocks. */ diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogDataServiceTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogDataServiceTest.java index f622840..25d9378 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogDataServiceTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogDataServiceTest.java @@ -26,33 +26,32 @@ * *

          What is tested

          * - *

          The argument-and-return contract of each finder: {@code findByEntityType}, - * {@code findByUser}, {@code findByEntityTypeAndUser}, {@code findByDay}, {@code findLatest} and - * {@code findLatestByEntityType}. Verified concerns are: (1) the right {@link AuditLogRepository} - * method is called with the right arguments, (2) the day-window finder converts a {@link - * LocalDate} into a {@code [00:00 systemDefault, +1 day)} half-open instant range, (3) each - * finder maps the returned {@link AuditLogEntity}s to {@link AuditLogDto}s (including the nested - * user), (4) every finder rejects null arguments and {@code findLatest*} rejects a non-positive - * limit. Write-side ({@code createEntry}) is covered only for its null-rejection guard. + *

          The argument-and-return contract of each finder: {@code findByEntityType}, {@code findByUser}, + * {@code findByEntityTypeAndUser}, {@code findByDay}, {@code findLatest} and {@code + * findLatestByEntityType}. Verified concerns are: (1) the right {@link AuditLogRepository} method + * is called with the right arguments, (2) the day-window finder converts a {@link LocalDate} into a + * {@code [00:00 systemDefault, +1 day)} half-open instant range, (3) each finder maps the returned + * {@link AuditLogEntity}s to {@link AuditLogDto}s (including the nested user), (4) every finder + * rejects null arguments and {@code findLatest*} rejects a non-positive limit. Write-side ({@code + * createEntry}) is covered only for its null-rejection guard. * *

          How it is tested

          * - *

          Pure JUnit 5 with Mockito and AssertJ. No Spring context — the service is constructed - * directly with three mocked collaborators. + *

          Pure JUnit 5 with Mockito and AssertJ. No Spring context — the service is constructed directly + * with three mocked collaborators. * *

          Mock-Audit. Three mocks, all justified for a coordination-layer service: * *

            - *
          • {@code AuditLogRepository} — stubbing finder return values is the entire point: the - * service is responsible for delegating to the correct query method with the correct - * arguments and mapping the result. Spinning up Postgres for every permutation would add - * no coverage that the integration test ({@link AuditLogIntegrationTest}) does not already - * provide. + *
          • {@code AuditLogRepository} — stubbing finder return values is the entire point: the service + * is responsible for delegating to the correct query method with the correct arguments and + * mapping the result. Spinning up Postgres for every permutation would add no coverage that + * the integration test ({@link AuditLogIntegrationTest}) does not already provide. *
          • {@code UserRepository} — held only because the production constructor takes one for the * write path; the finder tests never invoke it. Could plausibly be unused in finder-only * tests if the service were split. - *
          • {@code ApplicationEventPublisher} — inherited collaborator from - * {@code AbstractDbBackedDataService}; lifecycle events are not exercised here. + *
          • {@code ApplicationEventPublisher} — inherited collaborator from {@code + * AbstractDbBackedDataService}; lifecycle events are not exercised here. *
          */ @DisplayName("AuditLogDataService finders (unit)") diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogDtoTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogDtoTest.java index 164369b..dcef308 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogDtoTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogDtoTest.java @@ -15,12 +15,11 @@ * *

          What is tested

          * - *

          That every field of an {@link AuditLogEntity} is copied verbatim onto the resulting - * {@link AuditLogDto}, including the inherited {@code id} and {@code createdAt} from - * {@link AbstractEntity} (which are not exposed through setters), and that the associated - * {@link UserEntity} is recursively mapped to a nested {@code UserDto} with its own id / name / - * email. Mapper drift would silently strip fields from API responses; the test pins the full - * field set. + *

          That every field of an {@link AuditLogEntity} is copied verbatim onto the resulting {@link + * AuditLogDto}, including the inherited {@code id} and {@code createdAt} from {@link + * AbstractEntity} (which are not exposed through setters), and that the associated {@link + * UserEntity} is recursively mapped to a nested {@code UserDto} with its own id / name / email. + * Mapper drift would silently strip fields from API responses; the test pins the full field set. * *

          How it is tested

          * @@ -28,9 +27,9 @@ * normally set by JPA / Hibernate at flush time; here they are injected via reflection so the * mapper can be exercised without a persistence context. * - *

          Mock-Audit. Zero mocks. The mapper is a pure function; the test builds real - * {@link AuditLogEntity} and {@link UserEntity} instances and uses reflection only to set - * package-private inherited fields. + *

          Mock-Audit. Zero mocks. The mapper is a pure function; the test builds real {@link + * AuditLogEntity} and {@link UserEntity} instances and uses reflection only to set package-private + * inherited fields. */ @DisplayName("AuditLogDto") class AuditLogDtoTest { diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogEventListenerTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogEventListenerTest.java index ba8f81b..9f5b02a 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogEventListenerTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogEventListenerTest.java @@ -33,17 +33,16 @@ *

          Four concerns of the listener: * *

            - *
          1. Action mapping. Create / update / delete events produce {@link AuditAction#INSERT} - * / {@code UPDATE} / {@code DELETE} entries respectively, attributed to the authenticated - * user looked up by {@code sub}. + *
          2. Action mapping. Create / update / delete events produce {@link AuditAction#INSERT} / + * {@code UPDATE} / {@code DELETE} entries respectively, attributed to the authenticated user + * looked up by {@code sub}. *
          3. System-user fallback. Whenever the listener cannot resolve a "real" user — no - * authentication, non-JWT principal (API key), blank/null user name, or a JWT subject with - * no local row — the entry is attributed to {@link SystemUser} instead of being dropped. - * Audit must not have gaps. + * authentication, non-JWT principal (API key), blank/null user name, or a JWT subject with no + * local row — the entry is attributed to {@link SystemUser} instead of being dropped. Audit + * must not have gaps. *
          4. Recursion prevention & failure swallowing. Events for {@link AuditLogDto} are - * ignored (otherwise writing an audit entry would itself trigger one), and an exception - * from the data service is swallowed so a downed audit DB cannot bring down the request - * path. + * ignored (otherwise writing an audit entry would itself trigger one), and an exception from + * the data service is swallowed so a downed audit DB cannot bring down the request path. *
          5. Display-name resolution via {@link NameSupplier}. A correctly annotated zero-arg * String-returning method supplies the human-readable name; missing, multi-arg, or * wrong-return-type annotated methods fall back to the literal {@code "UNKNOWN"}. @@ -51,23 +50,22 @@ * *

            How it is tested

            * - *

            Pure JUnit 5 with Mockito and AssertJ. No Spring context. Domain payloads are tiny - * local records ({@code TestData}, {@code NamedData}, {@code BadlyNamedData}) implementing - * {@link WithId}. + *

            Pure JUnit 5 with Mockito and AssertJ. No Spring context. Domain payloads are tiny local + * records ({@code TestData}, {@code NamedData}, {@code BadlyNamedData}) implementing {@link + * WithId}. * *

            Mock-Audit. Three mocks, each justified: * *

              *
            • {@code AuditLogDataService} — the listener's job IS to delegate to it with the right - * arguments; the {@code verify(...)}-with-captor pattern is the entire test contract. - * Using a real instance would require a database and would shift coverage away from the - * listener decisions onto persistence concerns already covered by {@link - * AuditLogIntegrationTest}. + * arguments; the {@code verify(...)}-with-captor pattern is the entire test contract. Using a + * real instance would require a database and would shift coverage away from the listener + * decisions onto persistence concerns already covered by {@link AuditLogIntegrationTest}. *
            • {@code AuthService} — real {@code AuthService} reads from {@link - * org.springframework.security.core.context.SecurityContextHolder}; reconstructing that - * here would require Spring Security plumbing that adds no listener coverage. - *
            • {@code UserRepository} — stubbing {@code findBySub} and {@code getReferenceById} lets - * the tests exercise both "user resolved" and "user missing" branches without persistence. + * org.springframework.security.core.context.SecurityContextHolder}; reconstructing that here + * would require Spring Security plumbing that adds no listener coverage. + *
            • {@code UserRepository} — stubbing {@code findBySub} and {@code getReferenceById} lets the + * tests exercise both "user resolved" and "user missing" branches without persistence. *
            */ @DisplayName("AuditLogEventListener") @@ -117,7 +115,8 @@ void shouldRecordCreateEntryWithAuthenticatedUser() { } @Test - @DisplayName("OnObjectUpdate produces an UPDATE audit entry attributed to the authenticated user.") + @DisplayName( + "OnObjectUpdate produces an UPDATE audit entry attributed to the authenticated user.") void shouldRecordUpdateEntry() { final TestData data = new TestData(UUID.randomUUID(), "x"); when(authService.getUserInformation()).thenReturn(userNamed("bob-sub", "bob")); @@ -267,9 +266,9 @@ void shouldFallBackToSystemUserWhenLocalUserMissing() { /** * Defensive contract: writing the audit entry must never propagate an exception back to the - * domain transaction that triggered the event — an audit-DB outage cannot be allowed to take - * down the request path. Verified by asserting the listener still completed normally and the - * data service was actually invoked. + * domain transaction that triggered the event — an audit-DB outage cannot be allowed to take down + * the request path. Verified by asserting the listener still completed normally and the data + * service was actually invoked. */ @Test @DisplayName( @@ -292,9 +291,8 @@ void shouldSwallowAuditWriteFailure() { } /** - * Pins the recursion guard: an {@code OnObjectCreate<AuditLogDto>} must NOT trigger - * another {@code createEntry} — otherwise every audit write would loop forever and saturate - * the database. + * Pins the recursion guard: an {@code OnObjectCreate<AuditLogDto>} must NOT trigger another + * {@code createEntry} — otherwise every audit write would loop forever and saturate the database. */ @Test @DisplayName( @@ -327,8 +325,8 @@ void shouldNotRecursivelyAuditAuditEntries() { /** * Successful {@link NameSupplier} resolution: the payload exposes a zero-arg {@code String} - * method annotated {@code @NameSupplier} returning "Hitchhiker's Guide" — the audit entry's - * name column is populated from it rather than the {@code "UNKNOWN"} fallback. + * method annotated {@code @NameSupplier} returning "Hitchhiker's Guide" — the audit entry's name + * column is populated from it rather than the {@code "UNKNOWN"} fallback. */ @Test @DisplayName( @@ -352,8 +350,8 @@ void shouldUseNameFromNameSupplierWhenAnnotatedCorrectly() { /** * Defensive case for incorrectly used {@code @NameSupplier}: a multi-arg method (cannot be - * invoked without arguments) and a non-String return type (would not fit the name column). - * The listener silently falls back to {@code "UNKNOWN"} rather than throwing. + * invoked without arguments) and a non-String return type (would not fit the name column). The + * listener silently falls back to {@code "UNKNOWN"} rather than throwing. */ @Test @DisplayName( diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogIntegrationTest.java index 539ebf1..bb58541 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/audit/AuditLogIntegrationTest.java @@ -25,12 +25,12 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.context.annotation.Import; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.testcontainers.junit.jupiter.Testcontainers; /** @@ -42,36 +42,34 @@ * *
              *
            1. Event-driven entry creation. Calls to {@link TagDataService#save} / {@code delete} - * publish domain events that {@link AuditLogEventListener} translates into persisted - * {@link AuditLogEntity} rows — verified by reading them back through {@link - * AuditLogDataService}'s finders. - *
            2. SystemUser fallback (in DB). Missing or non-JWT authentication causes entries to - * be attributed to {@link SystemUser} in the actual {@code audit_log.user_id} column. - *
            3. Recursion prevention (in DB). Writing an audit entry must not itself produce - * another audit entry — verified by inspecting the persisted table. - *
            4. Query methods on real data. {@code findByEntityType}, {@code findByUser}, - * {@code findByEntityTypeAndUser} against multi-user, multi-type fixtures. + * publish domain events that {@link AuditLogEventListener} translates into persisted {@link + * AuditLogEntity} rows — verified by reading them back through {@link AuditLogDataService}'s + * finders. + *
            5. SystemUser fallback (in DB). Missing or non-JWT authentication causes entries to be + * attributed to {@link SystemUser} in the actual {@code audit_log.user_id} column. + *
            6. Recursion prevention (in DB). Writing an audit entry must not itself produce another + * audit entry — verified by inspecting the persisted table. + *
            7. Query methods on real data. {@code findByEntityType}, {@code findByUser}, {@code + * findByEntityTypeAndUser} against multi-user, multi-type fixtures. *
            8. Retention cleanup. {@link AuditCleanupJob#cleanupExpiredEntries()} deletes only - * entries older than {@code AuditProperties.retentionDays()}; the boundary is checked at - * 91 days (deleted) vs 89 days (kept) against a 90-day window. + * entries older than {@code AuditProperties.retentionDays()}; the boundary is checked at 91 + * days (deleted) vs 89 days (kept) against a 90-day window. *
            * *

            How it is tested

            * - *

            {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * starts a real Postgres via Testcontainers. {@link TagDataService} is used as a real publisher - * of {@code OnObjectCreate/Update/Delete} events so the integration is end-to-end. + *

            {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} starts + * a real Postgres via Testcontainers. {@link TagDataService} is used as a real publisher of {@code + * OnObjectCreate/Update/Delete} events so the integration is end-to-end. * - *

            Mock-Audit. {@code AuthService} is the single {@code @MockitoBean} — real - * {@code AuthService} reads from {@link - * org.springframework.security.core.context.SecurityContextHolder} populated by the filter - * chain, which the tests deliberately bypass to drive listener decisions directly. Every other - * collaborator (data service, repositories, cleanup job, tag service) is a real Spring bean - * backed by real Postgres — there is no mocking of the components under test. + *

            Mock-Audit. {@code AuthService} is the single {@code @MockitoBean} — real {@code + * AuthService} reads from {@link org.springframework.security.core.context.SecurityContextHolder} + * populated by the filter chain, which the tests deliberately bypass to drive listener decisions + * directly. Every other collaborator (data service, repositories, cleanup job, tag service) is a + * real Spring bean backed by real Postgres — there is no mocking of the components under test. * *

            The {@code system} user row is inserted via raw JDBC in {@link #persistSystemUser()} because - * the production data is provisioned by a Flyway migration that does not run in this test - * profile. + * the production data is provisioned by a Flyway migration that does not run in this test profile. */ @SpringBootTest(classes = TestApplication.class) @Import(PostgresTestConfiguration.class) @@ -102,12 +100,7 @@ class AuditLogIntegrationTest { private static java.util.Optional userInfo(final UserEntity user) { return java.util.Optional.of( new UserInformation( - user.getSub(), - user.getName(), - "test@example.com", - null, - user.getSub(), - user.getSub())); + user.getSub(), user.getName(), "test@example.com", null, user.getSub(), user.getSub())); } @BeforeEach @@ -231,9 +224,9 @@ void shouldUseSystemUserForApiKeyPrincipal() { class RecursionPrevention { /** - * Persistence-level confirmation of the unit-test recursion guard: writing an audit entry - * must not itself fire an audit event for entity type {@code AuditLogDto}. Asserted by - * reading the database back after one explicit {@code createEntry} call. + * Persistence-level confirmation of the unit-test recursion guard: writing an audit entry must + * not itself fire an audit event for entity type {@code AuditLogDto}. Asserted by reading the + * database back after one explicit {@code createEntry} call. */ @Test @DisplayName( @@ -328,9 +321,9 @@ void shouldFindSystemAttributedEntries() { class RetentionCleanup { /** - * Retention boundary check against a 90-day window: an entry backdated to 91 days ago must - * be deleted; an entry backdated to 89 days ago must survive. Backdating uses raw SQL - * because {@code created_at} is mapped {@code updatable=false} on {@link + * Retention boundary check against a 90-day window: an entry backdated to 91 days ago must be + * deleted; an entry backdated to 89 days ago must survive. Backdating uses raw SQL because + * {@code created_at} is mapped {@code updatable=false} on {@link * com.openelements.spring.base.data.AbstractEntity}. */ @Test diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/comment/CommentServiceIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/comment/CommentServiceIntegrationTest.java index 6b1241b..7dc1b8c 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/comment/CommentServiceIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/comment/CommentServiceIntegrationTest.java @@ -47,45 +47,45 @@ *

            Four orthogonal concerns of the comment subsystem: * *

              - *
            1. Entity mapping. The DDL is what we expect — the {@code comments} table has an - * {@code author_id uuid NOT NULL} column with the {@code fk_comments_author} foreign key, - * and the {@code @ManyToOne(fetch=LAZY)} association is a real Hibernate proxy that only - * initialises on dereference. + *
            2. Entity mapping. The DDL is what we expect — the {@code comments} table has an {@code + * author_id uuid NOT NULL} column with the {@code fk_comments_author} foreign key, and the + * {@code @ManyToOne(fetch=LAZY)} association is a real Hibernate proxy that only initialises + * on dereference. *
            3. Comment creation. A saved comment is associated with the currently authenticated - * user; on first login the user is provisioned JIT and the comment correctly references - * the new row; missing authentication fails the entire transaction so neither comment - * nor user is persisted. - *
            4. Comment retrieval. {@code findById} returns a {@link CommentDto} whose nested - * {@code AuthorDto} comes from the JPA fetch, not a side-channel call to {@link - * UserService}. {@code getAll} on 100 distinct authors stays under 10 SQL statements - * thanks to {@code @BatchSize(50)} on {@link UserEntity} — a regression that drops the - * annotation would issue 101 queries and fail the assertion. + * user; on first login the user is provisioned JIT and the comment correctly references the + * new row; missing authentication fails the entire transaction so neither comment nor user is + * persisted. + *
            5. Comment retrieval. {@code findById} returns a {@link CommentDto} whose nested {@code + * AuthorDto} comes from the JPA fetch, not a side-channel call to {@link UserService}. {@code + * getAll} on 100 distinct authors stays under 10 SQL statements thanks to + * {@code @BatchSize(50)} on {@link UserEntity} — a regression that drops the annotation would + * issue 101 queries and fail the assertion. *
            6. Referential integrity. A comment with an unknown {@code author_id} is rejected by * Postgres; a user with comments cannot be deleted (FK ON DELETE RESTRICT); a user with no * comments can be deleted normally. - *
            7. Audit integration. Create, update, and delete each emit exactly one matching - * {@code AuditLogEntity} row with the expected {@code AuditAction}. + *
            8. Audit integration. Create, update, and delete each emit exactly one matching {@code + * AuditLogEntity} row with the expected {@code AuditAction}. *
            * *

            How it is tested

            * - *

            {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * spins up a real Postgres via Testcontainers. The {@link JdbcTemplate} is used to introspect - * {@code information_schema} (the only way to verify the actual DDL — Hibernate metadata would - * just echo the entity mapping). Hibernate {@link Statistics} is used for the batch-fetch test - * because the invariant under test (number of SQL statements) is itself a Hibernate-specific - * behaviour; production code stays on standard JPA APIs. + *

            {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} spins + * up a real Postgres via Testcontainers. The {@link JdbcTemplate} is used to introspect {@code + * information_schema} (the only way to verify the actual DDL — Hibernate metadata would just echo + * the entity mapping). Hibernate {@link Statistics} is used for the batch-fetch test because the + * invariant under test (number of SQL statements) is itself a Hibernate-specific behaviour; + * production code stays on standard JPA APIs. * *

            Mock-Audit. * *

              *
            • {@code @MockitoBean AuthService} — the test drives the service from outside the Spring - * Security filter chain, so the {@code SecurityContextHolder} is not populated. Mocking - * lets each test choose the JWT identity per-call via {@code setAuthenticatedUser(...)}. - *
            • {@code @MockitoSpyBean UserService} — wraps the real bean so the - * "no separate lookup" assertion in {@code shouldReturnAuthorDtoWithoutSeparateLookup} can - * call {@code verify(userService, never()).findById(...)}. All real provisioning and - * drift-sync behaviour still runs. + * Security filter chain, so the {@code SecurityContextHolder} is not populated. Mocking lets + * each test choose the JWT identity per-call via {@code setAuthenticatedUser(...)}. + *
            • {@code @MockitoSpyBean UserService} — wraps the real bean so the "no separate lookup" + * assertion in {@code shouldReturnAuthorDtoWithoutSeparateLookup} can call {@code + * verify(userService, never()).findById(...)}. All real provisioning and drift-sync behaviour + * still runs. *
            */ @SpringBootTest(classes = TestApplication.class) @@ -120,8 +120,7 @@ void setUp() { private void setAuthenticatedUser(final String sub, final String name, final String email) { when(authService.getUserInformation()) - .thenReturn( - java.util.Optional.of(new UserInformation(sub, name, email, null, sub, sub))); + .thenReturn(java.util.Optional.of(new UserInformation(sub, name, email, null, sub, sub))); } private UserEntity seedUser(final String sub, final String name) { @@ -147,8 +146,8 @@ class EntityMapping { /** * Asserts the DDL directly against {@code information_schema} rather than via Hibernate - * metadata — Hibernate would just echo back what the entity declares, while a query against - * the running Postgres catches schema drift, missing migrations, and naming mistakes. + * metadata — Hibernate would just echo back what the entity declares, while a query against the + * running Postgres catches schema drift, missing migrations, and naming mistakes. */ @Test @DisplayName( @@ -278,10 +277,10 @@ void shouldFailWhenNoAuthentication() { class CommentRetrieval { /** - * Pins the "no side-channel" rule: the {@code AuthorDto} on a returned {@link CommentDto} - * must come from the JPA fetch graph, never from a separate {@code userService.findById} - * call. Verified with a Mockito spy assertion {@code verify(userService, never())} — a - * future refactor that re-introduces a second lookup would fail this test. + * Pins the "no side-channel" rule: the {@code AuthorDto} on a returned {@link CommentDto} must + * come from the JPA fetch graph, never from a separate {@code userService.findById} call. + * Verified with a Mockito spy assertion {@code verify(userService, never())} — a future + * refactor that re-introduces a second lookup would fail this test. */ @Test @DisplayName( @@ -298,13 +297,13 @@ void shouldReturnAuthorDtoWithoutSeparateLookup() { } /** - * Regression guard against re-introducing N+1 on the author fetch. Seeds 100 distinct - * users with one comment each (1:1 cardinality is deliberate — 5 users / 100 comments - * would silently pass via session-cache deduplication even without batching). With - * {@code @BatchSize(50)} on {@link UserEntity}, 100 distinct author proxies initialise in - * {@code ceil(100/50) = 2} batched SELECTs; total ≈ 3 statements with headroom. Without - * batching this would be 1 + 100 = 101 statements. The {@code ≤ 10} ceiling leaves room - * for Hibernate-internal bookkeeping while still catching a dropped annotation. + * Regression guard against re-introducing N+1 on the author fetch. Seeds 100 distinct users + * with one comment each (1:1 cardinality is deliberate — 5 users / 100 comments would silently + * pass via session-cache deduplication even without batching). With {@code @BatchSize(50)} on + * {@link UserEntity}, 100 distinct author proxies initialise in {@code ceil(100/50) = 2} + * batched SELECTs; total ≈ 3 statements with headroom. Without batching this would be 1 + 100 = + * 101 statements. The {@code ≤ 10} ceiling leaves room for Hibernate-internal bookkeeping while + * still catching a dropped annotation. */ @Test @Transactional @@ -391,7 +390,8 @@ void shouldRejectUserDeleteWhenCommentsExist() { } @Test - @DisplayName("A user with no comments deletes cleanly — the FK only restricts when child rows exist.") + @DisplayName( + "A user with no comments deletes cleanly — the FK only restricts when child rows exist.") void shouldAllowUserDeleteWhenNoComments() { final UserEntity author = seedUser("sub-orphan", "OrphanUser"); @@ -407,7 +407,8 @@ void shouldAllowUserDeleteWhenNoComments() { class AuditIntegration { @Test - @DisplayName("Creating a comment emits exactly one audit row with action=INSERT for that comment id.") + @DisplayName( + "Creating a comment emits exactly one audit row with action=INSERT for that comment id.") void shouldEmitAuditEventOnCreate() { seedUser("sub-audit-c", "AuditC"); setAuthenticatedUser("sub-audit-c", "AuditC", "auditc"); @@ -443,7 +444,8 @@ void shouldEmitAuditEventOnUpdate() { } @Test - @DisplayName("Deleting a comment emits exactly one audit row with action=DELETE for that comment id.") + @DisplayName( + "Deleting a comment emits exactly one audit row with action=DELETE for that comment id.") void shouldEmitAuditEventOnDelete() { seedUser("sub-audit-d", "AuditD"); setAuthenticatedUser("sub-audit-d", "AuditD", "auditd"); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/settings/SettingsDataServiceIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/settings/SettingsDataServiceIntegrationTest.java index 69f0ecd..b44c156 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/settings/SettingsDataServiceIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/settings/SettingsDataServiceIntegrationTest.java @@ -20,31 +20,31 @@ * *

            What is tested

            * - *

            End-to-end CRUD on the {@code settings} table — specifically the regression that motivated - * the {@code findByKey} / {@code deleteByKey} routing. {@link SettingsEntity}'s primary key is a - * UUID (inherited from {@code AbstractEntity}), while the {@code key} column is the business - * identifier callers use. The pre-fix code called {@code findById(String)} which tripped - * Hibernate's id-type check before any SQL was issued. This test confirms: + *

            End-to-end CRUD on the {@code settings} table — specifically the regression that motivated the + * {@code findByKey} / {@code deleteByKey} routing. {@link SettingsEntity}'s primary key is a UUID + * (inherited from {@code AbstractEntity}), while the {@code key} column is the business identifier + * callers use. The pre-fix code called {@code findById(String)} which tripped Hibernate's id-type + * check before any SQL was issued. This test confirms: * *

              *
            • {@code get / set / delete} all round-trip through the business-key column. - *
            • {@code set} is a real upsert: the second write under the same key mutates the existing - * row in place rather than inserting a duplicate (verified by {@code count() == 1L}). + *
            • {@code set} is a real upsert: the second write under the same key mutates the existing row + * in place rather than inserting a duplicate (verified by {@code count() == 1L}). *
            • Distinct keys produce distinct rows (no accidental cross-pollination via the UUID PK). *
            • {@code delete} on an unknown key is a no-op, not an exception. *
            * *

            How it is tested

            * - *

            {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * spins up a real Postgres via Testcontainers. The settings table is truncated in {@code - * @BeforeEach} so each test runs against an empty row set. The integration footprint is - * intentional: the id-type mismatch the test guards against only surfaces against a real JPA - * provider with a real database — no in-memory substitute would catch it. + *

            {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} spins + * up a real Postgres via Testcontainers. The settings table is truncated in {@code @BeforeEach} so + * each test runs against an empty row set. The integration footprint is intentional: the id-type + * mismatch the test guards against only surfaces against a real JPA provider with a real database — + * no in-memory substitute would catch it. * - *

            Mock-Audit. Zero mocks. {@link SettingsDataService} and {@link SettingsRepository} - * are real beans wired by Spring; the database is a real Postgres in a container. Mocking would - * defeat the purpose of the regression guard. + *

            Mock-Audit. Zero mocks. {@link SettingsDataService} and {@link SettingsRepository} are + * real beans wired by Spring; the database is a real Postgres in a container. Mocking would defeat + * the purpose of the regression guard. */ @SpringBootTest(classes = TestApplication.class) @Import(PostgresTestConfiguration.class) @@ -67,7 +67,8 @@ void setUp() { class GetTest { @Test - @DisplayName("get(missing key) against real Postgres returns Optional.empty() — no id-type exception.") + @DisplayName( + "get(missing key) against real Postgres returns Optional.empty() — no id-type exception.") void shouldReturnEmptyForUnknownKeyWithoutThrowing() { final Optional result = settingsDataService.get("missing.key"); @@ -130,7 +131,8 @@ void shouldKeepDistinctKeysIndependent() { class DeleteTest { @Test - @DisplayName("delete(key) for a present key removes the row and a subsequent get returns empty.") + @DisplayName( + "delete(key) for a present key removes the row and a subsequent get returns empty.") void shouldRemoveAnExistingSetting() { settingsDataService.set("brevo.api-key", "secret-123"); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/settings/SettingsDataServiceTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/settings/SettingsDataServiceTest.java index fae38df..0a6f05e 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/settings/SettingsDataServiceTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/settings/SettingsDataServiceTest.java @@ -27,8 +27,8 @@ * NullPointerException} — surfaces misconfiguration immediately. *

        * - *

        End-to-end persistence behaviour (id-type mismatch fix, real Postgres unique constraint on - * the business key) is covered by the sibling {@link SettingsDataServiceIntegrationTest}. + *

        End-to-end persistence behaviour (id-type mismatch fix, real Postgres unique constraint on the + * business key) is covered by the sibling {@link SettingsDataServiceIntegrationTest}. * *

        How it is tested

        * @@ -39,8 +39,8 @@ *

        Mock-Audit. One mock: {@code mock(SettingsRepository.class)}. {@link * SettingsRepository} is a Spring Data JPA interface — there is no in-memory implementation to * substitute. Stubbing {@code findByKey(...)} return values is what lets the upsert branch - * (existing row vs new row) be exercised independently of any database. The {@code thenAnswer(i - * -> i.getArgument(0))} on {@code saveAndFlush} only echoes the argument back; it does not hide + * (existing row vs new row) be exercised independently of any database. The {@code thenAnswer(i -> + * i.getArgument(0))} on {@code saveAndFlush} only echoes the argument back; it does not hide * behaviour. Real-database behaviour is covered by {@link SettingsDataServiceIntegrationTest} * against a Testcontainers Postgres. */ @@ -72,7 +72,8 @@ void shouldReturnValueWhenKeyExists() { } @Test - @DisplayName("get(key) returns Optional.empty() when no row matches — no exception, no default.") + @DisplayName( + "get(key) returns Optional.empty() when no row matches — no exception, no default.") void shouldReturnEmptyWhenKeyDoesNotExist() { // GIVEN when(settingsRepository.findByKey("nonexistent")).thenReturn(Optional.empty()); @@ -85,7 +86,8 @@ void shouldReturnEmptyWhenKeyDoesNotExist() { } @Test - @DisplayName("get(null) throws NullPointerException — caller bug surfaces before any repository call.") + @DisplayName( + "get(null) throws NullPointerException — caller bug surfaces before any repository call.") void shouldRejectNullKey() { assertThatThrownBy(() -> settingsDataService.get(null)) .isInstanceOf(NullPointerException.class); @@ -97,7 +99,8 @@ void shouldRejectNullKey() { class SetTest { @Test - @DisplayName("set(key, value) for an unknown key inserts a new SettingsEntity with both fields populated.") + @DisplayName( + "set(key, value) for an unknown key inserts a new SettingsEntity with both fields populated.") void shouldCreateNewSettingWhenKeyDoesNotExist() { // GIVEN when(settingsRepository.findByKey("new.key")).thenReturn(Optional.empty()); @@ -121,7 +124,8 @@ void shouldCreateNewSettingWhenKeyDoesNotExist() { * {@code saveAndFlush} — no second row is created, no key field is touched. */ @Test - @DisplayName("set(key, value) on an existing key mutates the loaded entity in place and re-flushes.") + @DisplayName( + "set(key, value) on an existing key mutates the loaded entity in place and re-flushes.") void shouldUpdateExistingSettingValue() { // GIVEN final SettingsEntity existing = new SettingsEntity(); @@ -159,7 +163,8 @@ void shouldRejectNullValue() { class DeleteTest { @Test - @DisplayName("delete(key) routes to SettingsRepository.deleteByKey — never deleteById (UUID/String mismatch).") + @DisplayName( + "delete(key) routes to SettingsRepository.deleteByKey — never deleteById (UUID/String mismatch).") void shouldDeleteByKey() { // WHEN settingsDataService.delete("to.delete"); @@ -177,7 +182,8 @@ void shouldRejectNullKey() { } @Test - @DisplayName("SettingsDataService constructor rejects a null repository with NullPointerException.") + @DisplayName( + "SettingsDataService constructor rejects a null repository with NullPointerException.") void shouldRejectNullRepository() { assertThatThrownBy(() -> new SettingsDataService(null)) .isInstanceOf(NullPointerException.class); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/tag/TagDataServiceIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/tag/TagDataServiceIntegrationTest.java index 70f38e2..4a90dd2 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/tag/TagDataServiceIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/tag/TagDataServiceIntegrationTest.java @@ -17,11 +17,11 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.context.annotation.Import; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.testcontainers.junit.jupiter.Testcontainers; /** @@ -29,25 +29,25 @@ * *

        What is tested

        * - *

        The full lifecycle of a tag through the service layer: create with auto-generated id, - * update existing rows, delete, single-row fetch by id, list-all, and paginated listing. Each - * mutation roundtrips through Hibernate so the JPA-mapping, the DTO-to-entity mapper and the - * generated SQL are exercised together. Negative cases (update / delete with an unknown {@code - * UUID}) are pinned to {@link IllegalArgumentException} — the contract surface that REST - * controllers translate to HTTP 404. + *

        The full lifecycle of a tag through the service layer: create with auto-generated id, update + * existing rows, delete, single-row fetch by id, list-all, and paginated listing. Each mutation + * roundtrips through Hibernate so the JPA-mapping, the DTO-to-entity mapper and the generated SQL + * are exercised together. Negative cases (update / delete with an unknown {@code UUID}) are pinned + * to {@link IllegalArgumentException} — the contract surface that REST controllers translate to + * HTTP 404. * *

        How it is tested

        * - *

        {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * spins up a real Postgres via Testcontainers. {@link TagDataService} and {@link TagRepository} - * are real beans; the per-test {@code @BeforeEach} truncates the {@code tag} table to keep - * scenarios independent. + *

        {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} spins + * up a real Postgres via Testcontainers. {@link TagDataService} and {@link TagRepository} are real + * beans; the per-test {@code @BeforeEach} truncates the {@code tag} table to keep scenarios + * independent. * *

        Mock-Audit. One {@code @MockitoBean} of {@link AuthService}. The service inherits from - * {@code AbstractDbBackedDataService}, whose audit hooks consult {@code AuthService} for the - * acting principal — outside a real HTTP request there is no JWT to resolve, so the bean is - * mocked to default-stub behaviour. No other collaborator is mocked: every assertion is made - * against rows actually persisted to Postgres. + * {@code AbstractDbBackedDataService}, whose audit hooks consult {@code AuthService} for the acting + * principal — outside a real HTTP request there is no JWT to resolve, so the bean is mocked to + * default-stub behaviour. No other collaborator is mocked: every assertion is made against rows + * actually persisted to Postgres. */ @SpringBootTest(classes = TestApplication.class) @Import(PostgresTestConfiguration.class) @@ -72,7 +72,8 @@ void setUp() { class SaveCreateTest { @Test - @DisplayName("save(...) with a null id persists a new tag and returns a DTO with a generated UUID.") + @DisplayName( + "save(...) with a null id persists a new tag and returns a DTO with a generated UUID.") void shouldCreateNewTag() { // GIVEN final TagDto dto = new TagDto(null, "Important", "High priority items", "#FF0000"); @@ -123,7 +124,8 @@ void shouldReturnAllTags() { class SaveUpdateTest { @Test - @DisplayName("save(...) with a known id updates the existing row in place — id is preserved, fields are overwritten.") + @DisplayName( + "save(...) with a known id updates the existing row in place — id is preserved, fields are overwritten.") void shouldUpdateExistingTag() { // GIVEN final TagDto saved = tagDataService.save(new TagDto(null, "Original", "Desc", "#000000")); @@ -140,7 +142,8 @@ void shouldUpdateExistingTag() { } @Test - @DisplayName("save(...) with an unknown id raises IllegalArgumentException — no row is silently inserted with the caller-supplied UUID.") + @DisplayName( + "save(...) with an unknown id raises IllegalArgumentException — no row is silently inserted with the caller-supplied UUID.") void shouldThrowForNonExistentId() { final TagDto dto = new TagDto(UUID.randomUUID(), "Ghost", "Desc", "#000000"); assertThatThrownBy(() -> tagDataService.save(dto)) @@ -166,7 +169,8 @@ void shouldDeleteExistingTag() { } @Test - @DisplayName("delete(...) with an unknown id raises IllegalArgumentException — a stale REST DELETE never silently no-ops.") + @DisplayName( + "delete(...) with an unknown id raises IllegalArgumentException — a stale REST DELETE never silently no-ops.") void shouldThrowWhenDeletingNonExistentTag() { final TagDto dto = new TagDto(UUID.randomUUID(), "Ghost", "Desc", "#000000"); assertThatThrownBy(() -> tagDataService.delete(dto)) @@ -179,7 +183,8 @@ void shouldThrowWhenDeletingNonExistentTag() { class FindAllPaginatedTest { @Test - @DisplayName("findAll(PageRequest.of(0, 20)) over 25 rows returns 20 items, totalElements=25, totalPages=2.") + @DisplayName( + "findAll(PageRequest.of(0, 20)) over 25 rows returns 20 items, totalElements=25, totalPages=2.") void shouldReturnPaginatedResults() { // GIVEN for (int i = 0; i < 25; i++) { @@ -226,7 +231,8 @@ void shouldFindExistingTag() { } @Test - @DisplayName("findById(unknownId) returns Optional.empty() — no exception, the caller gets a clean miss.") + @DisplayName( + "findById(unknownId) returns Optional.empty() — no exception, the caller gets a clean miss.") void shouldReturnEmptyForNonExistentId() { // WHEN final Optional found = tagDataService.findById(UUID.randomUUID()); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/tag/TagDtoTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/tag/TagDtoTest.java index c5f6196..18fe2dd 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/tag/TagDtoTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/tag/TagDtoTest.java @@ -13,22 +13,22 @@ * *

        That every field on a populated {@link TagEntity} ({@code id}, {@code name}, {@code * description}, {@code color}) is copied 1:1 into the immutable {@link TagDto} record. This pins - * the contract between persistence layer and API/DTO layer — a silent rename or omitted field - * would corrupt the JSON payload sent to consumers. + * the contract between persistence layer and API/DTO layer — a silent rename or omitted field would + * corrupt the JSON payload sent to consumers. * *

        How it is tested

        * - *

        Plain JUnit 5 — instantiate a {@link TagEntity}, run the static mapper, assert each - * accessor. + *

        Plain JUnit 5 — instantiate a {@link TagEntity}, run the static mapper, assert each accessor. * - *

        Mock-Audit. Zero mocks. The entity is a POJO with public setters and the mapper has - * no collaborators; nothing to stub. + *

        Mock-Audit. Zero mocks. The entity is a POJO with public setters and the mapper has no + * collaborators; nothing to stub. */ @DisplayName("TagDto") class TagDtoTest { @Test - @DisplayName("TagDto.fromEntity(...) copies id, name, description and color 1:1 from the TagEntity.") + @DisplayName( + "TagDto.fromEntity(...) copies id, name, description and color 1:1 from the TagEntity.") void shouldConvertFromEntity() { // GIVEN final UUID id = UUID.randomUUID(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookDeliveryIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookDeliveryIntegrationTest.java index 497f044..7b0f318 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookDeliveryIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookDeliveryIntegrationTest.java @@ -37,21 +37,20 @@ * *

        What is tested

        * - *

        That a data event is delivered on the webhook executor, not on the thread that saved the - * data: {@code save(...)} returns while the receiver is still holding the call, and the call's - * status is recorded on the webhook row once the receiver answers. Also that the dedicated - * executor does not replace Spring Boot's {@code applicationTaskExecutor}. + *

        That a data event is delivered on the webhook executor, not on the thread that saved the data: + * {@code save(...)} returns while the receiver is still holding the call, and the call's status is + * recorded on the webhook row once the receiver answers. Also that the dedicated executor does not + * replace Spring Boot's {@code applicationTaskExecutor}. * *

        How it is tested

        * - *

        The webhook row is written through the repository, so that creating it does not itself - * trigger a webhook call. + *

        The webhook row is written through the repository, so that creating it does not itself trigger + * a webhook call. * - *

        {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * starts a real Postgres via Testcontainers. The receiver is a JDK {@link HttpServer} whose - * handler blocks until the test releases it, so the test does not depend on timing: if the call - * ran on the saving thread, {@code save(...)} would block until the bounded timeout fails the - * test. + *

        {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} starts + * a real Postgres via Testcontainers. The receiver is a JDK {@link HttpServer} whose handler blocks + * until the test releases it, so the test does not depend on timing: if the call ran on the saving + * thread, {@code save(...)} would block until the bounded timeout fails the test. * *

        Mock-Audit. {@code AuthService} is the single {@code @MockitoBean}, for the audit * listener that also reacts to the tag events. Data services, repositories, the webhook sender and @@ -111,7 +110,8 @@ void tearDown() { } @Test - @DisplayName("save(...) returns while the webhook receiver still holds the call; the status is recorded once it answers.") + @DisplayName( + "save(...) returns while the webhook receiver still holds the call; the status is recorded once it answers.") void shouldDeliverWithoutBlockingTheSave() throws InterruptedException { // GIVEN final WebhookEntity webhook = new WebhookEntity(); @@ -136,7 +136,8 @@ void shouldDeliverWithoutBlockingTheSave() throws InterruptedException { } @Test - @DisplayName("The webhook executor sits next to Spring Boot's applicationTaskExecutor instead of replacing it.") + @DisplayName( + "The webhook executor sits next to Spring Boot's applicationTaskExecutor instead of replacing it.") void shouldKeepTheApplicationTaskExecutor() { assertThat(applicationContext.containsBean(WebhookConfig.EXECUTOR_BEAN_NAME)).isTrue(); assertThat(applicationContext.containsBean("applicationTaskExecutor")).isTrue(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookEventListenerTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookEventListenerTest.java index 25ffe81..29bc434 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookEventListenerTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookEventListenerTest.java @@ -21,22 +21,22 @@ *

        What is tested

        * *

        That each Spring {@code @TransactionalEventListener} method ({@code handleOnObjectCreate}, - * {@code handleOnObjectUpdate}, {@code handleOnObjectDelete}) wraps its incoming domain event - * into a {@link WebhookDataEventPayload} and forwards it to {@link WebhookSender#sendAndTrack}. - * Also covers the two fail-fast guards: a {@code null} event raises {@link NullPointerException}; - * a {@code null} {@link WebhookSender} at construction time raises {@link NullPointerException} - * so a misconfigured Spring context surfaces immediately rather than on first event. + * {@code handleOnObjectUpdate}, {@code handleOnObjectDelete}) wraps its incoming domain event into + * a {@link WebhookDataEventPayload} and forwards it to {@link WebhookSender#sendAndTrack}. Also + * covers the two fail-fast guards: a {@code null} event raises {@link NullPointerException}; a + * {@code null} {@link WebhookSender} at construction time raises {@link NullPointerException} so a + * misconfigured Spring context surfaces immediately rather than on first event. * *

        How it is tested

        * *

        Plain JUnit 5 with Mockito, no Spring context — the listener is plain Java once instantiated; - * the {@code @TransactionalEventListener} annotation has no effect outside a Spring container. - * The forwarded payload is captured with an {@link ArgumentCaptor}. + * the {@code @TransactionalEventListener} annotation has no effect outside a Spring container. The + * forwarded payload is captured with an {@link ArgumentCaptor}. * *

        Mock-Audit. A single {@code mock(WebhookSender.class)} — {@link WebhookSender} is the * downstream collaborator under verification; substituting the real sender would require WireMock - * and a Spring context for no added coverage of the listener's wiring logic. That coverage lives - * in {@code WebhookSenderTest}. + * and a Spring context for no added coverage of the listener's wiring logic. That coverage lives in + * {@code WebhookSenderTest}. */ @DisplayName("WebhookEventListener") class WebhookEventListenerTest { @@ -47,13 +47,14 @@ private record TestData(UUID id, String value) implements WithId {} private final WebhookEventListener listener = new WebhookEventListener(webhookSender); /** - * An {@link OnObjectCreate} event reaches {@link WebhookSender#sendAndTrack} carrying the original - * {@code data} reference and, crucially, {@link WebhookDataEventType#CREATED} as its {@code - * eventType} — the listener must propagate the lifecycle type rather than collapsing every event - * to a single value. + * An {@link OnObjectCreate} event reaches {@link WebhookSender#sendAndTrack} carrying the + * original {@code data} reference and, crucially, {@link WebhookDataEventType#CREATED} as its + * {@code eventType} — the listener must propagate the lifecycle type rather than collapsing every + * event to a single value. */ @Test - @DisplayName("An OnObjectCreate event is wrapped into a WebhookDataEventPayload with eventType=CREATED and forwarded to WebhookSender.sendAndTrack — payload carries the original data reference.") + @DisplayName( + "An OnObjectCreate event is wrapped into a WebhookDataEventPayload with eventType=CREATED and forwarded to WebhookSender.sendAndTrack — payload carries the original data reference.") void shouldDelegateCreateEventToSender() { // GIVEN final TestData data = new TestData(UUID.randomUUID(), "created"); @@ -71,7 +72,8 @@ void shouldDelegateCreateEventToSender() { } @Test - @DisplayName("An OnObjectUpdate event is wrapped into a WebhookDataEventPayload with eventType=UPDATED and forwarded to WebhookSender.sendAndTrack.") + @DisplayName( + "An OnObjectUpdate event is wrapped into a WebhookDataEventPayload with eventType=UPDATED and forwarded to WebhookSender.sendAndTrack.") void shouldDelegateUpdateEventToSender() { // GIVEN final TestData data = new TestData(UUID.randomUUID(), "updated"); @@ -89,7 +91,8 @@ void shouldDelegateUpdateEventToSender() { } @Test - @DisplayName("An OnObjectDelete event is wrapped into a WebhookDataEventPayload with eventType=DELETED and forwarded to WebhookSender.sendAndTrack.") + @DisplayName( + "An OnObjectDelete event is wrapped into a WebhookDataEventPayload with eventType=DELETED and forwarded to WebhookSender.sendAndTrack.") void shouldDelegateDeleteEventToSender() { // GIVEN final TestData data = new TestData(UUID.randomUUID(), "deleted"); @@ -107,14 +110,16 @@ void shouldDelegateDeleteEventToSender() { } @Test - @DisplayName("handleOnObjectCreate(null) throws NullPointerException — a null event must never reach WebhookSender.") + @DisplayName( + "handleOnObjectCreate(null) throws NullPointerException — a null event must never reach WebhookSender.") void shouldRejectNullEvent() { assertThatThrownBy(() -> listener.handleOnObjectCreate(null)) .isInstanceOf(NullPointerException.class); } @Test - @DisplayName("WebhookEventListener constructor rejects a null WebhookSender — a misconfigured Spring context fails fast at startup.") + @DisplayName( + "WebhookEventListener constructor rejects a null WebhookSender — a misconfigured Spring context fails fast at startup.") void shouldRejectNullWebhookSender() { assertThatThrownBy(() -> new WebhookEventListener(null)) .isInstanceOf(NullPointerException.class); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookSenderTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookSenderTest.java index 9d29d48..36b4c71 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookSenderTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/WebhookSenderTest.java @@ -31,10 +31,9 @@ * *

          *
        1. {@code ping(webhookId)}. Issues an HTTP POST to the registered URL, captures the - * response status (2xx / 4xx / 5xx) and the connection-failure sentinel (0 or -1) via - * {@code recordCall(...)}, and rejects an unknown - * webhook id with {@link IllegalArgumentException} and a null id with {@link - * NullPointerException}. + * response status (2xx / 4xx / 5xx) and the connection-failure sentinel (0 or -1) via {@code + * recordCall(...)}, and rejects an unknown webhook id with {@link IllegalArgumentException} + * and a null id with {@link NullPointerException}. *
        2. {@code sendAndTrack(payload)}. Fans out a single payload as an HTTP POST to every * row returned by {@link WebhookDataService#findAllActive()}. *
        @@ -43,22 +42,23 @@ * *

        How it is tested

        * - *

        Plain JUnit 5. A {@link WireMockServer} bound to a dynamic port is started once per class - * and reset between tests; the {@link WebhookSender} is constructed with a real {@link - * RestClient} pointed at WireMock's base URL and an executor that runs each call on the calling - * thread. Status-code stubs are configured per scenario; - * outgoing requests are verified against WireMock's recorded interactions. + *

        Plain JUnit 5. A {@link WireMockServer} bound to a dynamic port is started once per class and + * reset between tests; the {@link WebhookSender} is constructed with a real {@link RestClient} + * pointed at WireMock's base URL and an executor that runs each call on the calling thread. + * Status-code stubs are configured per scenario; outgoing requests are verified against WireMock's + * recorded interactions. * *

        Mock-Audit. One {@code mock(WebhookDataService.class)}. The sender's contract is to - * read webhook rows from {@code WebhookDataService} and write back status updates via - * {@code recordCall(...)}; mocking it lets the test (a) stub the row to return a WireMock-backed - * URL without spinning up Postgres and (b) capture the recorded status to verify status-tracking. End-to-end persistence is covered by {@link + * read webhook rows from {@code WebhookDataService} and write back status updates via {@code + * recordCall(...)}; mocking it lets the test (a) stub the row to return a WireMock-backed URL + * without spinning up Postgres and (b) capture the recorded status to verify status-tracking. + * End-to-end persistence is covered by {@link * com.openelements.spring.base.services.webhook.data.WebhookDataServiceIntegrationTest}. * - *

        Status: currently {@link Disabled @Disabled}. The {@code @Disabled} on the class and - * on the {@code PingTest} nested class is intentional — these tests are pending stabilisation - * work (likely around connection-error status values that differ between local and CI runs). - * The {@code @DisplayName}s and the Javadoc above are kept in place so that when the suite is + *

        Status: currently {@link Disabled @Disabled}. The {@code @Disabled} on the class and on + * the {@code PingTest} nested class is intentional — these tests are pending stabilisation work + * (likely around connection-error status values that differ between local and CI runs). The + * {@code @DisplayName}s and the Javadoc above are kept in place so that when the suite is * re-enabled, the documentation reads correctly on the JUnit report from day one. */ @DisplayName("WebhookSender") @@ -98,7 +98,8 @@ private WebhookDto createWebhook(final String path) { } @Test - @DisplayName("WebhookSender constructor rejects null for RestClient, WebhookDataService or Executor — a misconfigured Spring context fails fast at startup.") + @DisplayName( + "WebhookSender constructor rejects null for RestClient, WebhookDataService or Executor — a misconfigured Spring context fails fast at startup.") void shouldRejectNullConstructorArgs() { final RestClient restClient = RestClient.builder().build(); final WebhookDataService dataService = mock(WebhookDataService.class); @@ -119,7 +120,8 @@ private record TestData(UUID id) implements com.openelements.spring.base.data.Wi class PingTest { @Test - @DisplayName("ping(webhookId) issues an HTTP POST with Content-Type: application/json to the registered URL.") + @DisplayName( + "ping(webhookId) issues an HTTP POST with Content-Type: application/json to the registered URL.") void shouldSendHttpPostToWebhookUrl() { // GIVEN wireMockServer.stubFor(post(urlEqualTo("/ping")).willReturn(aResponse().withStatus(200))); @@ -135,7 +137,8 @@ void shouldSendHttpPostToWebhookUrl() { } @Test - @DisplayName("A 2xx response records status 200 and the call time via WebhookDataService.recordCall(...).") + @DisplayName( + "A 2xx response records status 200 and the call time via WebhookDataService.recordCall(...).") void shouldTrackSuccessStatus() { // GIVEN wireMockServer.stubFor(post(urlEqualTo("/success")).willReturn(aResponse().withStatus(200))); @@ -149,7 +152,8 @@ void shouldTrackSuccessStatus() { } @Test - @DisplayName("A 5xx response records status 500 via WebhookDataService.recordCall(...) — the failure is recorded, not swallowed.") + @DisplayName( + "A 5xx response records status 500 via WebhookDataService.recordCall(...) — the failure is recorded, not swallowed.") void shouldTrackServerErrorStatus() { // GIVEN wireMockServer.stubFor( @@ -164,7 +168,8 @@ void shouldTrackServerErrorStatus() { } @Test - @DisplayName("A 4xx response records status 404 via WebhookDataService.recordCall(...) — the failure is recorded, not swallowed.") + @DisplayName( + "A 4xx response records status 404 via WebhookDataService.recordCall(...) — the failure is recorded, not swallowed.") void shouldTrackClientErrorStatus() { // GIVEN wireMockServer.stubFor( @@ -179,13 +184,14 @@ void shouldTrackClientErrorStatus() { } /** - * Posts to {@code 192.0.2.1} — a TEST-NET-1 ({@code RFC 5737}) address guaranteed not to - * route — so the {@link RestClient} surfaces a connection-level failure rather than an HTTP - * status. The sender encodes such failures as {@code 0} or {@code -1} in {@code lastStatus} - * so operators can distinguish transport errors from server-side rejections. + * Posts to {@code 192.0.2.1} — a TEST-NET-1 ({@code RFC 5737}) address guaranteed not to route + * — so the {@link RestClient} surfaces a connection-level failure rather than an HTTP status. + * The sender encodes such failures as {@code 0} or {@code -1} in {@code lastStatus} so + * operators can distinguish transport errors from server-side rejections. */ @Test - @DisplayName("A connection failure (unreachable host) records status 0 or -1 — transport errors are distinguishable from HTTP status codes.") + @DisplayName( + "A connection failure (unreachable host) records status 0 or -1 — transport errors are distinguishable from HTTP status codes.") void shouldTrackConnectionErrorAsZeroOrMinusOne() { // GIVEN - unreachable host final UUID webhookId = UUID.randomUUID(); @@ -203,7 +209,8 @@ void shouldTrackConnectionErrorAsZeroOrMinusOne() { } @Test - @DisplayName("ping(unknownId) raises IllegalArgumentException with message containing \"not found\" — translated by REST layer to HTTP 404.") + @DisplayName( + "ping(unknownId) raises IllegalArgumentException with message containing \"not found\" — translated by REST layer to HTTP 404.") void shouldThrowForNonExistentWebhook() { // GIVEN when(webhookDataService.findById(any(UUID.class))).thenReturn(Optional.empty()); @@ -215,7 +222,8 @@ void shouldThrowForNonExistentWebhook() { } @Test - @DisplayName("ping(null) throws NullPointerException — fail-fast at the API boundary, no repository lookup attempted.") + @DisplayName( + "ping(null) throws NullPointerException — fail-fast at the API boundary, no repository lookup attempted.") void shouldRejectNullId() { assertThatThrownBy(() -> webhookSender.ping(null)).isInstanceOf(NullPointerException.class); } @@ -226,7 +234,8 @@ void shouldRejectNullId() { class SendAndTrackPayloadTest { @Test - @DisplayName("sendAndTrack(payload) fans out one HTTP POST per active webhook returned by findAllActive() — both registered endpoints receive the call.") + @DisplayName( + "sendAndTrack(payload) fans out one HTTP POST per active webhook returned by findAllActive() — both registered endpoints receive the call.") void shouldSendToAllActiveWebhooks() { // GIVEN wireMockServer.stubFor(post(urlEqualTo("/hook1")).willReturn(aResponse().withStatus(200))); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/data/WebhookDataServiceIntegrationTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/data/WebhookDataServiceIntegrationTest.java index 5f5fe5b..26ffb83 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/data/WebhookDataServiceIntegrationTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/data/WebhookDataServiceIntegrationTest.java @@ -18,11 +18,11 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.context.annotation.Import; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.event.ApplicationEvents; import org.springframework.test.context.event.RecordApplicationEvents; import org.testcontainers.junit.jupiter.Testcontainers; @@ -37,22 +37,22 @@ * auto-generated id, update (URL change and active-flag toggle), delete, single-row fetch by id, * list-all, paginated listing, and the {@code findAllActive()} filter that the {@code * WebhookSender} relies on to fan out events only to live endpoints, and {@code recordCall(...)}, - * which stores the result of a delivery without publishing a lifecycle event. Negative cases (update / - * delete with an unknown {@code UUID}) are pinned to {@link IllegalArgumentException} — the - * contract surface that REST controllers translate to HTTP 404. + * which stores the result of a delivery without publishing a lifecycle event. Negative cases + * (update / delete with an unknown {@code UUID}) are pinned to {@link IllegalArgumentException} — + * the contract surface that REST controllers translate to HTTP 404. * *

        How it is tested

        * - *

        {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} - * spins up a real Postgres via Testcontainers. {@link WebhookDataService} and {@link - * WebhookRepository} are real beans; the per-test {@code @BeforeEach} truncates the {@code - * webhook} table to keep scenarios independent. + *

        {@link SpringBootTest} loads {@link TestApplication}; {@link PostgresTestConfiguration} spins + * up a real Postgres via Testcontainers. {@link WebhookDataService} and {@link WebhookRepository} + * are real beans; the per-test {@code @BeforeEach} truncates the {@code webhook} table to keep + * scenarios independent. * *

        Mock-Audit. One {@code @MockitoBean} of {@link AuthService}. The service inherits from - * {@code AbstractDbBackedDataService}, whose audit hooks consult {@code AuthService} for the - * acting principal — outside a real HTTP request there is no JWT to resolve, so the bean is - * mocked to default-stub behaviour. No other collaborator is mocked: every assertion is made - * against rows actually persisted to Postgres. + * {@code AbstractDbBackedDataService}, whose audit hooks consult {@code AuthService} for the acting + * principal — outside a real HTTP request there is no JWT to resolve, so the bean is mocked to + * default-stub behaviour. No other collaborator is mocked: every assertion is made against rows + * actually persisted to Postgres. */ @SpringBootTest(classes = TestApplication.class) @Import(PostgresTestConfiguration.class) @@ -80,7 +80,8 @@ void setUp() { class SaveTest { @Test - @DisplayName("save(...) with a null id persists a new webhook and returns a DTO with a generated UUID.") + @DisplayName( + "save(...) with a null id persists a new webhook and returns a DTO with a generated UUID.") void shouldCreateNewWebhook() { // GIVEN final WebhookDto dto = new WebhookDto(null, "https://example.com/hook", true, null, null); @@ -100,7 +101,8 @@ void shouldCreateNewWebhook() { class FindAllActiveTest { @Test - @DisplayName("findAllActive() returns only rows with active=true — the filter WebhookSender relies on to skip disabled endpoints.") + @DisplayName( + "findAllActive() returns only rows with active=true — the filter WebhookSender relies on to skip disabled endpoints.") void shouldReturnOnlyActiveWebhooks() { // GIVEN webhookDataService.save(new WebhookDto(null, "https://active1.com/hook", true, null, null)); @@ -119,7 +121,8 @@ void shouldReturnOnlyActiveWebhooks() { } @Test - @DisplayName("findAllActive() returns an empty list when every persisted webhook has active=false.") + @DisplayName( + "findAllActive() returns an empty list when every persisted webhook has active=false.") void shouldReturnEmptyListWhenNoActiveWebhooks() { // GIVEN webhookDataService.save(new WebhookDto(null, "https://inactive.com/hook", false, null, null)); @@ -173,7 +176,8 @@ void shouldUpdateExistingWebhookUrl() { } @Test - @DisplayName("Toggling active=false through save(...) persists the change — findAllActive() will subsequently exclude this row.") + @DisplayName( + "Toggling active=false through save(...) persists the change — findAllActive() will subsequently exclude this row.") void shouldDeactivateWebhook() { // GIVEN final WebhookDto saved = @@ -190,7 +194,8 @@ void shouldDeactivateWebhook() { } @Test - @DisplayName("save(...) with an unknown id raises IllegalArgumentException — no row is silently inserted with the caller-supplied UUID.") + @DisplayName( + "save(...) with an unknown id raises IllegalArgumentException — no row is silently inserted with the caller-supplied UUID.") void shouldThrowForNonExistentId() { final WebhookDto dto = new WebhookDto(UUID.randomUUID(), "https://example.com/hook", true, null, null); @@ -219,7 +224,8 @@ void shouldDeleteExistingWebhook() { } @Test - @DisplayName("delete(...) with an unknown id raises IllegalArgumentException — a stale REST DELETE never silently no-ops.") + @DisplayName( + "delete(...) with an unknown id raises IllegalArgumentException — a stale REST DELETE never silently no-ops.") void shouldThrowWhenDeletingNonExistentWebhook() { final WebhookDto dto = new WebhookDto(UUID.randomUUID(), "https://example.com/hook", true, null, null); @@ -233,7 +239,8 @@ void shouldThrowWhenDeletingNonExistentWebhook() { class FindAllPaginatedTest { @Test - @DisplayName("findAll(PageRequest.of(0, 20)) over 25 rows returns 20 items, totalElements=25, totalPages=2.") + @DisplayName( + "findAll(PageRequest.of(0, 20)) over 25 rows returns 20 items, totalElements=25, totalPages=2.") void shouldReturnPaginatedResults() { // GIVEN for (int i = 0; i < 25; i++) { @@ -283,7 +290,8 @@ void shouldFindExistingWebhook() { } @Test - @DisplayName("findById(unknownId) returns Optional.empty() — no exception, the caller gets a clean miss.") + @DisplayName( + "findById(unknownId) returns Optional.empty() — no exception, the caller gets a clean miss.") void shouldReturnEmptyForNonExistentId() { // WHEN final Optional found = webhookDataService.findById(UUID.randomUUID()); @@ -298,11 +306,13 @@ void shouldReturnEmptyForNonExistentId() { class RecordCallTest { @Test - @DisplayName("recordCall(...) stores status and call time and keeps URL and active flag unchanged.") + @DisplayName( + "recordCall(...) stores status and call time and keeps URL and active flag unchanged.") void shouldRecordStatusAndCallTime() { // GIVEN final WebhookDto saved = - webhookDataService.save(new WebhookDto(null, "https://example.com/hook", true, null, null)); + webhookDataService.save( + new WebhookDto(null, "https://example.com/hook", true, null, null)); final Instant calledAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); // WHEN @@ -317,11 +327,13 @@ void shouldRecordStatusAndCallTime() { } @Test - @DisplayName("recordCall(...) publishes no lifecycle event — otherwise every webhook call would trigger another webhook call.") + @DisplayName( + "recordCall(...) publishes no lifecycle event — otherwise every webhook call would trigger another webhook call.") void shouldNotPublishEvent() { // GIVEN final WebhookDto saved = - webhookDataService.save(new WebhookDto(null, "https://example.com/hook", true, null, null)); + webhookDataService.save( + new WebhookDto(null, "https://example.com/hook", true, null, null)); applicationEvents.clear(); // WHEN @@ -332,7 +344,8 @@ void shouldNotPublishEvent() { } @Test - @DisplayName("recordCall(...) for a webhook deleted in the meantime does nothing instead of failing the delivery.") + @DisplayName( + "recordCall(...) for a webhook deleted in the meantime does nothing instead of failing the delivery.") void shouldIgnoreDeletedWebhook() { // WHEN webhookDataService.recordCall(UUID.randomUUID(), 200, Instant.now()); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/data/WebhookDtoTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/data/WebhookDtoTest.java index ecee4b7..60d0f73 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/data/WebhookDtoTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/data/WebhookDtoTest.java @@ -17,9 +17,9 @@ *

          *
        1. A fully populated {@link WebhookEntity} (with {@code lastStatus} and {@code lastCalledAt} * set) is copied 1:1 — pins the API payload shape. - *
        2. A never-called inactive webhook produces a DTO with {@code lastStatus = null} and - * {@code lastCalledAt = null} — confirms the nullable HTTP-tracking fields survive the - * mapping without being defaulted to {@code 0} or {@code Instant.EPOCH}. + *
        3. A never-called inactive webhook produces a DTO with {@code lastStatus = null} and {@code + * lastCalledAt = null} — confirms the nullable HTTP-tracking fields survive the mapping + * without being defaulted to {@code 0} or {@code Instant.EPOCH}. *
        * *

        How it is tested

        @@ -27,14 +27,15 @@ *

        Plain JUnit 5 — instantiate a {@link WebhookEntity}, run the static mapper, assert each * accessor. * - *

        Mock-Audit. Zero mocks. The entity is a POJO with public setters and the mapper has - * no collaborators; nothing to stub. + *

        Mock-Audit. Zero mocks. The entity is a POJO with public setters and the mapper has no + * collaborators; nothing to stub. */ @DisplayName("WebhookDto") class WebhookDtoTest { @Test - @DisplayName("WebhookDto.fromEntity(...) copies id, url, active, lastStatus and lastCalledAt 1:1 from the WebhookEntity.") + @DisplayName( + "WebhookDto.fromEntity(...) copies id, url, active, lastStatus and lastCalledAt 1:1 from the WebhookEntity.") void shouldConvertFromEntity() { // GIVEN final UUID id = UUID.randomUUID(); @@ -58,7 +59,8 @@ void shouldConvertFromEntity() { } @Test - @DisplayName("An inactive webhook with unset lastStatus/lastCalledAt maps to null fields — nullable tracking values are preserved.") + @DisplayName( + "An inactive webhook with unset lastStatus/lastCalledAt maps to null fields — nullable tracking values are preserved.") void shouldConvertInactiveWebhookWithNullStatus() { // GIVEN final WebhookEntity entity = new WebhookEntity(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/payload/WebhookPayloadTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/payload/WebhookPayloadTest.java index 2615aae..decc4c8 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/payload/WebhookPayloadTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/services/webhook/payload/WebhookPayloadTest.java @@ -11,9 +11,8 @@ import org.junit.jupiter.api.Test; /** - * Unit tests for the immutable {@link WebhookDataEventPayload} and {@link - * WebhookPingEventPayload} records — the JSON shapes serialised onto outgoing webhook HTTP POST - * bodies. + * Unit tests for the immutable {@link WebhookDataEventPayload} and {@link WebhookPingEventPayload} + * records — the JSON shapes serialised onto outgoing webhook HTTP POST bodies. * *

        What is tested

        * @@ -25,11 +24,10 @@ * {@code eventType}, {@code dataClass} and {@code data} unmodified. *
      • Inferred-class form. {@code of(eventType, data)} derives {@code dataClass} from * {@code data.getClass()} — used by listeners that do not have a class reference handy. - *
      • Constructor null-guard. The compact record constructor rejects {@code null} - * {@code data} and {@code null} {@code eventType} so a malformed payload never reaches the - * wire. - *
      • Ping payload. Each {@code WebhookPingEventPayload.create()} yields a distinct - * {@code eventId} so retries and idempotency keys remain meaningful. + *
      • Constructor null-guard. The compact record constructor rejects {@code null} {@code + * data} and {@code null} {@code eventType} so a malformed payload never reaches the wire. + *
      • Ping payload. Each {@code WebhookPingEventPayload.create()} yields a distinct {@code + * eventId} so retries and idempotency keys remain meaningful. * * *

        How it is tested

        @@ -48,7 +46,8 @@ private record TestData(UUID id, String value) implements WithId {} class DataEventPayloadTest { @Test - @DisplayName("of(eventType, dataClass, data) populates eventId, eventType, dataClass, data and a non-null timestamp.") + @DisplayName( + "of(eventType, dataClass, data) populates eventId, eventType, dataClass, data and a non-null timestamp.") void shouldCreatePayloadWithCorrectFields() { // GIVEN final TestData data = new TestData(UUID.randomUUID(), "test"); @@ -66,7 +65,8 @@ void shouldCreatePayloadWithCorrectFields() { } @Test - @DisplayName("of(eventType, data) without an explicit class infers dataClass from data.getClass().") + @DisplayName( + "of(eventType, data) without an explicit class infers dataClass from data.getClass().") void shouldCreatePayloadWithInferredType() { // GIVEN final TestData data = new TestData(UUID.randomUUID(), "inferred"); @@ -81,14 +81,16 @@ void shouldCreatePayloadWithInferredType() { } @Test - @DisplayName("of(eventType, null) throws NullPointerException — a payload with null data must not reach the wire.") + @DisplayName( + "of(eventType, null) throws NullPointerException — a payload with null data must not reach the wire.") void shouldRejectNullData() { assertThatThrownBy(() -> WebhookDataEventPayload.of(WebhookDataEventType.CREATED, null)) .isInstanceOf(NullPointerException.class); } @Test - @DisplayName("of(null, data) throws NullPointerException — a payload with null eventType must not reach the wire.") + @DisplayName( + "of(null, data) throws NullPointerException — a payload with null eventType must not reach the wire.") void shouldRejectNullEventType() { final TestData data = new TestData(UUID.randomUUID(), "test"); assertThatThrownBy(() -> WebhookDataEventPayload.of(null, data)) @@ -101,7 +103,8 @@ void shouldRejectNullEventType() { class PingPayloadTest { @Test - @DisplayName("Each WebhookPingEventPayload.create() invocation yields a distinct eventId and a non-null timestamp.") + @DisplayName( + "Each WebhookPingEventPayload.create() invocation yields a distinct eventId and a non-null timestamp.") void shouldCreatePingWithUniqueIdAndTimestamp() { // WHEN final WebhookEventPayload ping1 = WebhookPingEventPayload.create(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/testcontainers/PostgresTestConfiguration.java b/spring-services-core/src/test/java/com/openelements/spring/base/testcontainers/PostgresTestConfiguration.java index 26a7b13..6472368 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/testcontainers/PostgresTestConfiguration.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/testcontainers/PostgresTestConfiguration.java @@ -29,17 +29,17 @@ public RestClient webhookRestClient() { } /** - * Stub {@link JwtDecoder} required by the library's default - * {@link org.springframework.security.web.SecurityFilterChain}, which wires - * {@code oauth2ResourceServer.jwt(...)}. The integration tests do not exercise actual JWT - * validation — they mock {@link com.openelements.spring.base.security.AuthService} — but the - * bean must exist for the chain factory method to instantiate. + * Stub {@link JwtDecoder} required by the library's default {@link + * org.springframework.security.web.SecurityFilterChain}, which wires {@code + * oauth2ResourceServer.jwt(...)}. The integration tests do not exercise actual JWT validation — + * they mock {@link com.openelements.spring.base.security.AuthService} — but the bean must exist + * for the chain factory method to instantiate. * - *

        Note: a custom {@code testSecurityFilterChain} matching {@code anyRequest()} would - * conflict with the library's {@code defaultFilterChain} (Spring Security 6.2+ rejects two - * unscoped chains). The integration tests invoke services directly via {@code @Autowired} - * beans rather than through HTTP, so the production filter chains can run as-is without - * affecting test behaviour. + *

        Note: a custom {@code testSecurityFilterChain} matching {@code anyRequest()} would conflict + * with the library's {@code defaultFilterChain} (Spring Security 6.2+ rejects two unscoped + * chains). The integration tests invoke services directly via {@code @Autowired} beans rather + * than through HTTP, so the production filter chains can run as-is without affecting test + * behaviour. */ @Bean public JwtDecoder testJwtDecoder() { diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceContextFilterWebTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceContextFilterWebTest.java index 7819f7f..847358f 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceContextFilterWebTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceContextFilterWebTest.java @@ -45,9 +45,10 @@ * MDC carries are the same value — that is the whole point of correlating a response with a * log line. *

      • The MDC is cleaned up on the request thread. Servlet containers pool threads, so a - * leaked entry would silently attach one request's trace ID to a later, unrelated request. The - * assertion runs inside the handler, after the filter's {@code finally} has had its - * chance on a second request, rather than on the test thread where it would prove nothing. + * leaked entry would silently attach one request's trace ID to a later, unrelated request. + * The assertion runs inside the handler, after the filter's {@code finally} has had + * its chance on a second request, rather than on the test thread where it would prove + * nothing. *
      • An application {@link TraceIdResolver} really is used, not just registered. * * @@ -117,7 +118,8 @@ private void run(final MvcAssertion assertion) { } /** Performs a request to the probe and returns the trace ID it reported. */ - private static String traceIdOf(final MockMvc mvc, final String... traceparents) throws Exception { + private static String traceIdOf(final MockMvc mvc, final String... traceparents) + throws Exception { var request = get("/api/trace"); for (final String traceparent : traceparents) { request = request.header(TraceParentTraceIdResolver.TRACEPARENT_HEADER, traceparent); @@ -195,7 +197,9 @@ void malformedTraceParentIsIgnored(final String traceparent) { void duplicateTraceParentHeadersAreIgnored() { run( mvc -> - assertThat(traceIdOf(mvc, VALID_TRACEPARENT, "00-" + "a".repeat(32) + "-00f067aa0ba902b7-01")) + assertThat( + traceIdOf( + mvc, VALID_TRACEPARENT, "00-" + "a".repeat(32) + "-00f067aa0ba902b7-01")) .isNotEqualTo(VALID_TRACE_ID) .isNotEqualTo("a".repeat(32))); } diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceContextTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceContextTest.java index aa6f236..f94340b 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceContextTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceContextTest.java @@ -16,12 +16,12 @@ * *
          *
        1. Stability. Repeated reads of the same request yield the same ID, whether the filter - * stored one or the fallback had to resolve it. Without this, the ID logged with a {@code 500} - * and the ID in the response body could differ, which is precisely what the feature exists to - * prevent. - *
        2. Fallback semantics. With no attribute present the context applies the default rules — - * honour a valid {@code traceparent}, generate otherwise — and stores the result, so - * the first read fixes the value for the rest of the request. + * stored one or the fallback had to resolve it. Without this, the ID logged with a {@code + * 500} and the ID in the response body could differ, which is precisely what the feature + * exists to prevent. + *
        3. Fallback semantics. With no attribute present the context applies the default rules + * — honour a valid {@code traceparent}, generate otherwise — and stores the result, + * so the first read fixes the value for the rest of the request. *
        * *

        How it is tested

        @@ -54,7 +54,8 @@ void fallbackHonoursTraceParentAndStores() { } @Test - @DisplayName("Without the attribute and without a traceparent, the generated ID is stable across reads.") + @DisplayName( + "Without the attribute and without a traceparent, the generated ID is stable across reads.") void fallbackGeneratesStableId() { final MockHttpServletRequest request = new MockHttpServletRequest(); diff --git a/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceParentTraceIdResolverTest.java b/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceParentTraceIdResolverTest.java index 75378ba..7a1136a 100644 --- a/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceParentTraceIdResolverTest.java +++ b/spring-services-core/src/test/java/com/openelements/spring/base/trace/TraceParentTraceIdResolverTest.java @@ -72,7 +72,9 @@ void futureVersionWithTrailingDataIsHonoured() { @Test @DisplayName("Without a traceparent header an ID is generated.") void missingHeaderGeneratesId() { - assertThat(resolver.resolve(requestWith())).matches("[0-9a-f]{32}").isNotEqualTo("0".repeat(32)); + assertThat(resolver.resolve(requestWith())) + .matches("[0-9a-f]{32}") + .isNotEqualTo("0".repeat(32)); } @Test @@ -110,7 +112,10 @@ void malformedTraceParentIsIgnored(final String traceparent) { void duplicateTraceParentHeadersAreIgnored() { final String second = "00-" + "a".repeat(32) + "-00f067aa0ba902b7-01"; final String resolved = resolver.resolve(requestWith(VALID_TRACEPARENT, second)); - assertThat(resolved).matches("[0-9a-f]{32}").isNotEqualTo(VALID_TRACE_ID).isNotEqualTo("a".repeat(32)); + assertThat(resolved) + .matches("[0-9a-f]{32}") + .isNotEqualTo(VALID_TRACE_ID) + .isNotEqualTo("a".repeat(32)); } /** diff --git a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/dbbackup/DbBackupAutoConfiguration.java b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/dbbackup/DbBackupAutoConfiguration.java index 9a333b4..2149c7e 100644 --- a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/dbbackup/DbBackupAutoConfiguration.java +++ b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/dbbackup/DbBackupAutoConfiguration.java @@ -7,16 +7,16 @@ /** * Auto-configuration for the optional db-backup-service sidecar client feature. * - *

        Registered through this module's - * {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the - * feature self-activates when {@code spring-services-dbbackup} is on the classpath. The module - * carries no extra third-party dependency (it talks to the sidecar over Spring's {@code RestClient} - * via core), so there is no heavy-dependency class to guard on; runtime opt-in stays governed by - * {@link DbBackupConfig}'s existing {@code @ConditionalOnProperty(openelements.db-backup.enabled)}. + *

        Registered through this module's {@code + * META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the feature + * self-activates when {@code spring-services-dbbackup} is on the classpath. The module carries no + * extra third-party dependency (it talks to the sidecar over Spring's {@code RestClient} via core), + * so there is no heavy-dependency class to guard on; runtime opt-in stays governed by {@link + * DbBackupConfig}'s existing {@code @ConditionalOnProperty(openelements.db-backup.enabled)}. * - *

        Lives outside the {@code services.dbbackup} package on purpose: {@link DbBackupConfig} declares - * a {@code @ComponentScan} over its own package, and an auto-configuration co-located there would be - * swept up by that scan and registered twice. + *

        Lives outside the {@code services.dbbackup} package on purpose: {@link DbBackupConfig} + * declares a {@code @ComponentScan} over its own package, and an auto-configuration co-located + * there would be swept up by that scan and registered twice. */ @AutoConfiguration @Import(DbBackupConfig.class) diff --git a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupClient.java b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupClient.java index 1441850..58ffc98 100644 --- a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupClient.java +++ b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupClient.java @@ -81,9 +81,9 @@ public BackupServiceInfo getInfo() { /** * Triggers a new backup via {@code POST /api/v1/backups}. The sidecar allows at most one backup - * to run at a time; if a backup is already in flight the returned - * {@link BackupTriggerResult#alreadyRunning()} is {@code true} and {@link - * BackupTriggerResult#job()} refers to the still-running job. + * to run at a time; if a backup is already in flight the returned {@link + * BackupTriggerResult#alreadyRunning()} is {@code true} and {@link BackupTriggerResult#job()} + * refers to the still-running job. * * @return the result describing the enqueued or already-running backup job */ diff --git a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupConfig.java b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupConfig.java index 4c4d6bd..30b115e 100644 --- a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupConfig.java +++ b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupConfig.java @@ -17,11 +17,11 @@ * reliably picks up plain configurations but excludes auto-configurations, so the properties are * always registered alongside the client. * - *

        The feature is opt-in and disabled by default: none of these beans are created - * unless {@code openelements.db-backup.enabled=true}. This avoids forcing a db-backup configuration - * on consumers that do not use the sidecar. When enabled, {@code openelements.db-backup.base-url} is - * required (see {@link DbBackupProperties}) — a missing base URL fails startup rather than defaulting - * to {@code localhost}. + *

        The feature is opt-in and disabled by default: none of these beans are + * created unless {@code openelements.db-backup.enabled=true}. This avoids forcing a db-backup + * configuration on consumers that do not use the sidecar. When enabled, {@code + * openelements.db-backup.base-url} is required (see {@link DbBackupProperties}) — a missing base + * URL fails startup rather than defaulting to {@code localhost}. */ @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "openelements.db-backup", name = "enabled", havingValue = "true") diff --git a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupProperties.java b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupProperties.java index 8536e18..992cc71 100644 --- a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupProperties.java +++ b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/DbBackupProperties.java @@ -11,10 +11,11 @@ * from {@code openelements.db-backup.*} application properties. * *

        The db-backup feature is opt-in: it is disabled by default and only activates - * when {@code openelements.db-backup.enabled=true} (see {@link DbBackupConfig}). When the feature is - * enabled, {@code baseUrl} is required — there is no default. A blank or missing - * {@code baseUrl} fails context startup with a binding/validation error rather than silently - * pointing at {@code localhost}, so a misconfiguration surfaces immediately instead of at first use. + * when {@code openelements.db-backup.enabled=true} (see {@link DbBackupConfig}). When the feature + * is enabled, {@code baseUrl} is required — there is no default. A blank or + * missing {@code baseUrl} fails context startup with a binding/validation error rather than + * silently pointing at {@code localhost}, so a misconfiguration surfaces immediately instead of at + * first use. * *

        The sidecar exposes two unauthenticated probes ({@code /health}, {@code /info}) and a set of * authenticated backup endpoints under {@code /api/v1/backups/*} that require a Bearer token diff --git a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/package-info.java b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/package-info.java index fc7be71..afa5462 100644 --- a/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/package-info.java +++ b/spring-services-dbbackup/src/main/java/com/openelements/spring/base/services/dbbackup/package-info.java @@ -12,14 +12,14 @@ *

          *
        • {@link com.openelements.spring.base.services.dbbackup.DbBackupClient} — thin HTTP wrapper * around the sidecar's REST API, built on Spring's {@code RestClient}. - *
        • {@link com.openelements.spring.base.services.dbbackup.BackupJob}, - * {@link com.openelements.spring.base.services.dbbackup.BackupMetadata}, - * {@link com.openelements.spring.base.services.dbbackup.BackupServiceInfo} — DTOs that mirror - * the sidecar's JSON payloads. - *
        • {@link com.openelements.spring.base.services.dbbackup.BackupTriggerResult} — wraps a - * {@link com.openelements.spring.base.services.dbbackup.BackupJob} together with an - * {@code alreadyRunning} flag that distinguishes the sidecar's {@code 202} (new job) from - * {@code 409} (a backup is already in flight) responses. + *
        • {@link com.openelements.spring.base.services.dbbackup.BackupJob}, {@link + * com.openelements.spring.base.services.dbbackup.BackupMetadata}, {@link + * com.openelements.spring.base.services.dbbackup.BackupServiceInfo} — DTOs that mirror the + * sidecar's JSON payloads. + *
        • {@link com.openelements.spring.base.services.dbbackup.BackupTriggerResult} — wraps a {@link + * com.openelements.spring.base.services.dbbackup.BackupJob} together with an {@code + * alreadyRunning} flag that distinguishes the sidecar's {@code 202} (new job) from {@code + * 409} (a backup is already in flight) responses. *
        • {@link com.openelements.spring.base.services.dbbackup.BackupDownload} — {@link * java.lang.AutoCloseable} wrapper around the streamed gzip body returned by the download * endpoints. diff --git a/spring-services-dbbackup/src/test/java/com/openelements/spring/base/services/dbbackup/DbBackupClientTest.java b/spring-services-dbbackup/src/test/java/com/openelements/spring/base/services/dbbackup/DbBackupClientTest.java index 61584ab..d3d54e7 100644 --- a/spring-services-dbbackup/src/test/java/com/openelements/spring/base/services/dbbackup/DbBackupClientTest.java +++ b/spring-services-dbbackup/src/test/java/com/openelements/spring/base/services/dbbackup/DbBackupClientTest.java @@ -24,48 +24,48 @@ /** * Wire-level tests for {@link DbBackupClient}. Uses WireMock to verify request paths, the - * Authorization header on authenticated calls, and that the JSON shapes we receive deserialise - * into the documented DTOs. + * Authorization header on authenticated calls, and that the JSON shapes we receive deserialise into + * the documented DTOs. * *

          What is tested

          * *

          The HTTP contract between {@link DbBackupClient} and its remote backup service partner: * *

            - *
          • {@code isHealthy()} maps HTTP {@code 200} to {@code true} and HTTP {@code 503} to - * {@code false} — the health probe does not throw. + *
          • {@code isHealthy()} maps HTTP {@code 200} to {@code true} and HTTP {@code 503} to {@code + * false} — the health probe does not throw. *
          • {@code getInfo()} deserialises the nested service-info JSON (version, pgDump version, * retention, backup interval, last-backup age) into {@link BackupServiceInfo}. *
          • {@code triggerBackup()} accepts HTTP {@code 202} as a successful enqueue, treats HTTP * {@code 409} as an "already running" signal (returning the existing job rather than - * throwing), and propagates {@code 401} as a {@link DbBackupException}. Missing - * configuration ({@code api-token} unset) fails fast before any network call. - *
          • {@code getJob(id)} parses a fully populated terminal-state job; HTTP {@code 404} - * returns {@code Optional.empty()} — not an error. - *
          • {@code listBackups()} parses the array shape and maps {@code triggeredBy} to the - * {@link BackupTrigger} enum. + * throwing), and propagates {@code 401} as a {@link DbBackupException}. Missing configuration + * ({@code api-token} unset) fails fast before any network call. + *
          • {@code getJob(id)} parses a fully populated terminal-state job; HTTP {@code 404} returns + * {@code Optional.empty()} — not an error. + *
          • {@code listBackups()} parses the array shape and maps {@code triggeredBy} to the {@link + * BackupTrigger} enum. *
          • {@code getLatestBackup()} returns {@code Optional.empty()} on {@code 404} — a brand-new * installation with no backups yet is a valid state. *
          • {@code downloadBackup(id)} streams the response body as an auto-closeable {@link - * BackupDownload}, reads {@code Content-Length} into {@code sizeBytes}, and sends the - * bearer token. A {@code 404} on download surfaces as {@link DbBackupException} (unlike - * {@code getLatestBackup}, downloading a missing id is a programming error). + * BackupDownload}, reads {@code Content-Length} into {@code sizeBytes}, and sends the bearer + * token. A {@code 404} on download surfaces as {@link DbBackupException} (unlike {@code + * getLatestBackup}, downloading a missing id is a programming error). *
          * *

          The Authorization header is asserted on the authenticated routes ({@code triggerBackup}, - * {@code downloadBackup}) — silently dropping the token would break production immediately, so - * the test pins it explicitly. + * {@code downloadBackup}) — silently dropping the token would break production immediately, so the + * test pins it explicitly. * *

          How it is tested

          * - *

          WireMock runs as a JVM-local HTTP server on a dynamic port; the client is constructed with - * its {@code baseUrl} pointed at WireMock. Each test stubs the routes it needs and the client - * is exercised end-to-end through its real JSON deserialiser. Pure JUnit 5 — no Spring context. + *

          WireMock runs as a JVM-local HTTP server on a dynamic port; the client is constructed with its + * {@code baseUrl} pointed at WireMock. Each test stubs the routes it needs and the client is + * exercised end-to-end through its real JSON deserialiser. Pure JUnit 5 — no Spring context. * *

          Mock-Audit. Zero Mockito mocks. WireMock is a network-level fake (not a mock of the - * {@code DbBackupClient} collaborator) — it replaces the remote service, not the client logic - * under test. The {@link DbBackupClient}, the JSON deserialiser, and the {@link - * DbBackupProperties} configuration are all real. + * {@code DbBackupClient} collaborator) — it replaces the remote service, not the client logic under + * test. The {@link DbBackupClient}, the JSON deserialiser, and the {@link DbBackupProperties} + * configuration are all real. */ class DbBackupClientTest { @@ -144,8 +144,8 @@ void getInfoParsesNestedShape() { /** * Verifies two things at once: HTTP {@code 202} maps to {@code alreadyRunning=false} with the - * parsed queued {@link BackupJob}, and the request carried the configured bearer token — - * silently dropping the Authorization header would break production immediately. + * parsed queued {@link BackupJob}, and the request carried the configured bearer token — silently + * dropping the Authorization header would break production immediately. */ @Test @DisplayName( @@ -275,7 +275,8 @@ void getJobReturnsPresentOn200() { } @Test - @DisplayName("getJob(unknownId) on HTTP 404 returns Optional.empty() — a missing job is not an error.") + @DisplayName( + "getJob(unknownId) on HTTP 404 returns Optional.empty() — a missing job is not an error.") void getJobReturnsEmptyOn404() { wireMockServer.stubFor( get(urlEqualTo("/api/v1/backups/jobs/nope")).willReturn(aResponse().withStatus(404))); @@ -284,7 +285,8 @@ void getJobReturnsEmptyOn404() { } @Test - @DisplayName("listBackups() parses the JSON array response and maps triggeredBy to the BackupTrigger enum.") + @DisplayName( + "listBackups() parses the JSON array response and maps triggeredBy to the BackupTrigger enum.") void listBackupsParsesArray() { final String body = """ diff --git a/spring-services-email/src/main/java/com/openelements/spring/base/email/EmailAutoConfiguration.java b/spring-services-email/src/main/java/com/openelements/spring/base/email/EmailAutoConfiguration.java index 64e700d..923c2fa 100644 --- a/spring-services-email/src/main/java/com/openelements/spring/base/email/EmailAutoConfiguration.java +++ b/spring-services-email/src/main/java/com/openelements/spring/base/email/EmailAutoConfiguration.java @@ -9,17 +9,17 @@ /** * Auto-configuration for the optional SMTP email feature. * - *

          Registered through this module's - * {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the - * feature self-activates when {@code spring-services-email} is on the classpath. - * {@link ConditionalOnClass @ConditionalOnClass(MimeMessage.class)} keeps it inert if the - * {@code spring-boot-starter-mail} dependency is not present, so a bundle that ships this class - * without the mail library causes no {@code NoClassDefFoundError}. + *

          Registered through this module's {@code + * META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the feature + * self-activates when {@code spring-services-email} is on the classpath. {@link + * ConditionalOnClass @ConditionalOnClass(MimeMessage.class)} keeps it inert if the {@code + * spring-boot-starter-mail} dependency is not present, so a bundle that ships this class without + * the mail library causes no {@code NoClassDefFoundError}. * *

          Lives outside the {@code services.email} package on purpose: {@link EmailConfig} declares a * {@code @ComponentScan} over its own package, and an auto-configuration co-located there would be - * swept up by that scan and registered twice. {@code EmailService} still degrades gracefully when no - * {@code JavaMailSender} is configured (no {@code spring.mail.host}). + * swept up by that scan and registered twice. {@code EmailService} still degrades gracefully when + * no {@code JavaMailSender} is configured (no {@code spring.mail.host}). */ @AutoConfiguration @ConditionalOnClass(MimeMessage.class) diff --git a/spring-services-email/src/main/java/com/openelements/spring/base/services/email/EmailService.java b/spring-services-email/src/main/java/com/openelements/spring/base/services/email/EmailService.java index 6ad0575..cc9551c 100644 --- a/spring-services-email/src/main/java/com/openelements/spring/base/services/email/EmailService.java +++ b/spring-services-email/src/main/java/com/openelements/spring/base/services/email/EmailService.java @@ -46,8 +46,8 @@ public class EmailService { /** * Creates the service. * - * @param mailSenderProvider provider for the optional {@link JavaMailSender}; if none is available - * the service is still created but every send fails fast + * @param mailSenderProvider provider for the optional {@link JavaMailSender}; if none is + * available the service is still created but every send fails fast * @param properties the email configuration properties */ public EmailService( diff --git a/spring-services-email/src/test/java/com/openelements/spring/base/services/email/EmailConfigTest.java b/spring-services-email/src/test/java/com/openelements/spring/base/services/email/EmailConfigTest.java index c2c4a71..377e40f 100644 --- a/spring-services-email/src/test/java/com/openelements/spring/base/services/email/EmailConfigTest.java +++ b/spring-services-email/src/test/java/com/openelements/spring/base/services/email/EmailConfigTest.java @@ -21,9 +21,9 @@ * *

          What is tested

          * - *

          The graceful-degradation contract: applications must boot whether or not SMTP is wired. - * Spring Boot's {@link MailSenderAutoConfiguration} only registers a {@link JavaMailSender} when - * {@code spring.mail.host} is present, and {@link EmailService} must cope with its absence: + *

          The graceful-degradation contract: applications must boot whether or not SMTP is wired. Spring + * Boot's {@link MailSenderAutoConfiguration} only registers a {@link JavaMailSender} when {@code + * spring.mail.host} is present, and {@link EmailService} must cope with its absence: * *

            *
          • Without {@code spring.mail.host}, the context boots and registers an {@link EmailService} @@ -34,15 +34,15 @@ * *

            How it is tested

            * - *

            Spring Boot's {@link ApplicationContextRunner} drives {@link EmailConfig} alongside the - * real {@link MailSenderAutoConfiguration} in isolation, with the property varied per test. A - * Logback {@link ListAppender} is attached to the {@link EmailService} logger before each test - * and detached after; WARN events are filtered out for assertion. + *

            Spring Boot's {@link ApplicationContextRunner} drives {@link EmailConfig} alongside the real + * {@link MailSenderAutoConfiguration} in isolation, with the property varied per test. A Logback + * {@link ListAppender} is attached to the {@link EmailService} logger before each test and detached + * after; WARN events are filtered out for assertion. * *

            Mock-Audit. Zero mocks. Both auto-configurations run as real Spring beans inside the * runner. No SMTP server is contacted because no test actually calls {@code sendEmail} — that - * surface belongs to {@link EmailServiceTest}; this test only verifies bean wiring and the - * startup WARN. + * surface belongs to {@link EmailServiceTest}; this test only verifies bean wiring and the startup + * WARN. */ @DisplayName("EmailConfig — application startup") class EmailConfigTest { @@ -70,7 +70,8 @@ void detachLogAppender() { } @Test - @DisplayName("Without spring.mail.host the context still boots: EmailService is registered, no JavaMailSender bean exists, and a WARN is logged at startup.") + @DisplayName( + "Without spring.mail.host the context still boots: EmailService is registered, no JavaMailSender bean exists, and a WARN is logged at startup.") void startsWithoutMailHost() { contextRunner.run( context -> { @@ -81,7 +82,8 @@ void startsWithoutMailHost() { } @Test - @DisplayName("With spring.mail.host set, both EmailService and JavaMailSender are wired and no WARN is emitted.") + @DisplayName( + "With spring.mail.host set, both EmailService and JavaMailSender are wired and no WARN is emitted.") void startsWithMailHost() { contextRunner .withPropertyValues("spring.mail.host=smtp.example.com") diff --git a/spring-services-email/src/test/java/com/openelements/spring/base/services/email/EmailServiceTest.java b/spring-services-email/src/test/java/com/openelements/spring/base/services/email/EmailServiceTest.java index f7e6edc..1d29c42 100644 --- a/spring-services-email/src/test/java/com/openelements/spring/base/services/email/EmailServiceTest.java +++ b/spring-services-email/src/test/java/com/openelements/spring/base/services/email/EmailServiceTest.java @@ -29,14 +29,13 @@ * JavaMailSender#send(SimpleMailMessage)}, and applies the optional display-name formatting * (RFC-style {@code "Name "}) only when {@code open-elements.email.from-name} is set * and non-blank. - *

          • {@code sendEmail(UserEntity user, ...)} reads the email from the user row and delegates; - * a user with {@code null}/blank email throws {@link IllegalArgumentException} - * before any mail-sender call. + *
          • {@code sendEmail(UserEntity user, ...)} reads the email from the user row and delegates; a + * user with {@code null}/blank email throws {@link IllegalArgumentException} before + * any mail-sender call. *
          • Graceful degradation: missing {@link JavaMailSender} or missing/blank {@code - * open-elements.email.from} both surface as {@link EmailException} with descriptive - * messages. - *
          • SMTP delivery failure ({@link MailSendException}) is wrapped as {@link EmailException} - * with the original cause preserved. + * open-elements.email.from} both surface as {@link EmailException} with descriptive messages. + *
          • SMTP delivery failure ({@link MailSendException}) is wrapped as {@link EmailException} with + * the original cause preserved. *
          • {@code null} arguments are rejected with {@link NullPointerException} on the public * contract — caller bugs surface immediately. *
          @@ -45,23 +44,23 @@ * *

          Plain JUnit 5 with Mockito, no Spring context. {@link EmailService} is instantiated directly * with a fake {@link ObjectProvider} and a plain {@link EmailProperties} POJO populated per test. - * The composed {@link SimpleMailMessage} is captured via {@link ArgumentCaptor} so each field - * (to, from, subject, body) can be asserted independently. + * The composed {@link SimpleMailMessage} is captured via {@link ArgumentCaptor} so each field (to, + * from, subject, body) can be asserted independently. * *

          Mock-Audit. Two mocks: * *

            *
          • {@code mock(JavaMailSender.class)} — Spring's SMTP gateway. A real {@code JavaMailSender} - * would open a TCP connection to an SMTP server; this surface is verified end-to-end only - * at deployment time. The mock lets us (a) capture the composed message for field-level + * would open a TCP connection to an SMTP server; this surface is verified end-to-end only at + * deployment time. The mock lets us (a) capture the composed message for field-level * assertions and (b) inject a {@link MailSendException} for the error-wrapping test. - *
          • {@code mock(ObjectProvider.class)} — Spring's optional-bean wrapper. Mocking lets a - * single test toggle between the "configured" and "not configured" states without a Spring - * context. The real wiring is covered by {@link EmailConfigTest}. + *
          • {@code mock(ObjectProvider.class)} — Spring's optional-bean wrapper. Mocking lets a single + * test toggle between the "configured" and "not configured" states without a Spring context. + * The real wiring is covered by {@link EmailConfigTest}. *
          * - *

          {@link EmailProperties} is used as a real POJO, not mocked — it has no behaviour beyond - * field accessors, so a mock would only obscure the test setup. + *

          {@link EmailProperties} is used as a real POJO, not mocked — it has no behaviour beyond field + * accessors, so a mock would only obscure the test setup. */ @DisplayName("EmailService") class EmailServiceTest { @@ -97,7 +96,8 @@ private SimpleMailMessage capturedMessage() { class SendByAddress { @Test - @DisplayName("sendEmail(to, subject, body) composes a SimpleMailMessage with the correct to / from / subject / text and hands it to JavaMailSender.") + @DisplayName( + "sendEmail(to, subject, body) composes a SimpleMailMessage with the correct to / from / subject / text and hands it to JavaMailSender.") void sendsPlainTextEmail() { emailService.sendEmail("recipient@example.com", "Test Subject", "Hello World"); @@ -109,12 +109,13 @@ void sendsPlainTextEmail() { } /** - * Pins the RFC-style {@code "Display Name "} formatting that downstream - * mail clients use to render the sender. The {@link jakarta.mail.internet.InternetAddress} + * Pins the RFC-style {@code "Display Name "} formatting that downstream mail + * clients use to render the sender. The {@link jakarta.mail.internet.InternetAddress} * formatting is what's being delegated to here; the test confirms the wiring, not the RFC. */ @Test - @DisplayName("With from-name configured, sendEmail produces an RFC-style \"Display Name \" From header.") + @DisplayName( + "With from-name configured, sendEmail produces an RFC-style \"Display Name \" From header.") void includesDisplayName() { properties.setFromName("My App"); @@ -125,7 +126,8 @@ void includesDisplayName() { } @Test - @DisplayName("With no from-name configured, the From header is the bare address — no empty \"\" wrapper.") + @DisplayName( + "With no from-name configured, the From header is the bare address — no empty \"\" wrapper.") void plainAddressWhenNoDisplayName() { emailService.sendEmail("recipient@example.com", "Subject", "Body"); @@ -133,12 +135,13 @@ void plainAddressWhenNoDisplayName() { } /** - * Symmetric to the WARN-on-blank-token check in {@code SlackConfigTest} (spring-services-slack): - * an environment that exports {@code OPEN_ELEMENTS_EMAIL_FROM_NAME=" "} must not emit an RFC - * header containing only whitespace as the display name. + * Symmetric to the WARN-on-blank-token check in {@code SlackConfigTest} + * (spring-services-slack): an environment that exports {@code OPEN_ELEMENTS_EMAIL_FROM_NAME=" + * "} must not emit an RFC header containing only whitespace as the display name. */ @Test - @DisplayName("A whitespace-only from-name is treated as missing — the From header is the bare address.") + @DisplayName( + "A whitespace-only from-name is treated as missing — the From header is the bare address.") void plainAddressWhenDisplayNameBlank() { properties.setFromName(" "); @@ -164,7 +167,8 @@ void sendsToUserEmail() { } @Test - @DisplayName("A user with email=null throws IllegalArgumentException before JavaMailSender.send is touched.") + @DisplayName( + "A user with email=null throws IllegalArgumentException before JavaMailSender.send is touched.") void throwsWhenUserEmailNull() { final UserEntity user = new UserEntity(); user.setEmail(null); @@ -176,7 +180,8 @@ void throwsWhenUserEmailNull() { } @Test - @DisplayName("A user with email=\"\" (blank) throws IllegalArgumentException before JavaMailSender.send is touched.") + @DisplayName( + "A user with email=\"\" (blank) throws IllegalArgumentException before JavaMailSender.send is touched.") void throwsWhenUserEmailBlank() { final UserEntity user = new UserEntity(); user.setEmail(""); @@ -188,7 +193,8 @@ void throwsWhenUserEmailBlank() { } @Test - @DisplayName("sendEmail((UserEntity) null, ...) throws NullPointerException — no JavaMailSender.send call.") + @DisplayName( + "sendEmail((UserEntity) null, ...) throws NullPointerException — no JavaMailSender.send call.") void rejectsNullUser() { assertThatThrownBy(() -> emailService.sendEmail((UserEntity) null, "Subject", "Body")) .isInstanceOf(NullPointerException.class); @@ -200,7 +206,8 @@ void rejectsNullUser() { class GracefulDegradation { @Test - @DisplayName("With no JavaMailSender available, sendEmail fails fast with EmailException carrying the \"not configured\" hint.") + @DisplayName( + "With no JavaMailSender available, sendEmail fails fast with EmailException carrying the \"not configured\" hint.") void throwsWhenMailSenderUnavailable() { final EmailService unconfigured = new EmailService(provider(null), properties); @@ -210,7 +217,8 @@ void throwsWhenMailSenderUnavailable() { } @Test - @DisplayName("With open-elements.email.from=null, sendEmail throws EmailException pointing to the missing sender property.") + @DisplayName( + "With open-elements.email.from=null, sendEmail throws EmailException pointing to the missing sender property.") void throwsWhenFromMissing() { properties.setFrom(null); @@ -220,7 +228,8 @@ void throwsWhenFromMissing() { } @Test - @DisplayName("A whitespace-only open-elements.email.from is treated as missing — sendEmail throws EmailException.") + @DisplayName( + "A whitespace-only open-elements.email.from is treated as missing — sendEmail throws EmailException.") void throwsWhenFromBlank() { properties.setFrom(" "); @@ -235,13 +244,13 @@ void throwsWhenFromBlank() { class ErrorHandling { /** - * Confirms SMTP failures preserve their cause for operator triage: a {@link - * MailSendException} ({code MailException} subclass thrown on SMTP timeout, auth failure, - * etc.) is wrapped as {@link EmailException} with the original {@code MailException} set as - * {@code cause}. + * Confirms SMTP failures preserve their cause for operator triage: a {@link MailSendException} + * ({code MailException} subclass thrown on SMTP timeout, auth failure, etc.) is wrapped as + * {@link EmailException} with the original {@code MailException} set as {@code cause}. */ @Test - @DisplayName("A MailException from JavaMailSender (e.g. SMTP timeout) is wrapped as EmailException with the original MailException as cause.") + @DisplayName( + "A MailException from JavaMailSender (e.g. SMTP timeout) is wrapped as EmailException with the original MailException as cause.") void wrapsMailException() { final MailSendException cause = new MailSendException("smtp timeout"); doThrow(cause).when(mailSender).send(any(SimpleMailMessage.class)); @@ -257,21 +266,24 @@ void wrapsMailException() { class InputValidation { @Test - @DisplayName("sendEmail((String) null, ...) throws NullPointerException — no JavaMailSender.send call.") + @DisplayName( + "sendEmail((String) null, ...) throws NullPointerException — no JavaMailSender.send call.") void rejectsNullTo() { assertThatThrownBy(() -> emailService.sendEmail((String) null, "Subject", "Body")) .isInstanceOf(NullPointerException.class); } @Test - @DisplayName("sendEmail(to, null, body) throws NullPointerException — no JavaMailSender.send call.") + @DisplayName( + "sendEmail(to, null, body) throws NullPointerException — no JavaMailSender.send call.") void rejectsNullSubject() { assertThatThrownBy(() -> emailService.sendEmail("a@b.c", null, "Body")) .isInstanceOf(NullPointerException.class); } @Test - @DisplayName("sendEmail(to, subject, null) throws NullPointerException — no JavaMailSender.send call.") + @DisplayName( + "sendEmail(to, subject, null) throws NullPointerException — no JavaMailSender.send call.") void rejectsNullBody() { assertThatThrownBy(() -> emailService.sendEmail("a@b.c", "Subject", null)) .isInstanceOf(NullPointerException.class); diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpActorLabel.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpActorLabel.java index c819c17..4adc1d1 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpActorLabel.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpActorLabel.java @@ -5,35 +5,33 @@ /** * Resolves a human-readable actor label for MCP access logging. * - *

          The label is captured on the request thread by the transport's context - * extractor (see {@code McpServerConfig}) — the tool handler may run on a - * different thread without the Spring security context — and stored in the - * {@link McpTransportContext} under {@link #ACTOR_LABEL_KEY}. For the Phase 1 - * API-key profile the label is {@code "apikey:"}. + *

          The label is captured on the request thread by the transport's context extractor (see {@code + * McpServerConfig}) — the tool handler may run on a different thread without the Spring security + * context — and stored in the {@link McpTransportContext} under {@link #ACTOR_LABEL_KEY}. For the + * Phase 1 API-key profile the label is {@code "apikey:"}. * - *

          This is used only for operational log lines; MCP reads are not written to - * the {@code audit_log} (that table records mutations, and read access — like a - * frontend record view — is not audited). See {@code docs/TODO.md} for a possible - * future read-access audit hung off API keys / controller endpoints. + *

          This is used only for operational log lines; MCP reads are not written to the {@code + * audit_log} (that table records mutations, and read access — like a frontend record view — is not + * audited). See {@code docs/TODO.md} for a possible future read-access audit hung off API keys / + * controller endpoints. */ final class McpActorLabel { - /** Key under which the actor label is stored in the {@link McpTransportContext}. */ - static final String ACTOR_LABEL_KEY = "mcp.actor.label"; + /** Key under which the actor label is stored in the {@link McpTransportContext}. */ + static final String ACTOR_LABEL_KEY = "mcp.actor.label"; - private static final String UNKNOWN = "unknown"; + private static final String UNKNOWN = "unknown"; - private McpActorLabel() { - } + private McpActorLabel() {} - /** - * Reads the actor label from the transport context. - * - * @param context the transport context for the current tool call (may be {@code null}) - * @return the actor label, or {@code "unknown"} if none was captured - */ - static String from(final McpTransportContext context) { - final Object label = context == null ? null : context.get(ACTOR_LABEL_KEY); - return label != null ? label.toString() : UNKNOWN; - } + /** + * Reads the actor label from the transport context. + * + * @param context the transport context for the current tool call (may be {@code null}) + * @return the actor label, or {@code "unknown"} if none was captured + */ + static String from(final McpTransportContext context) { + final Object label = context == null ? null : context.get(ACTOR_LABEL_KEY); + return label != null ? label.toString() : UNKNOWN; + } } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpAutoConfiguration.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpAutoConfiguration.java index 8a91f9f..1546ca0 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpAutoConfiguration.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpAutoConfiguration.java @@ -8,25 +8,25 @@ /** * Auto-configuration for the optional Model Context Protocol (MCP) server feature. * - *

          Registered through this module's - * {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the - * feature self-activates when {@code spring-services-mcp} is on the classpath — the endpoint and its - * dedicated security filter chain can no longer be accidentally present in an application that never - * added the module. {@link ConditionalOnClass @ConditionalOnClass(McpServer.class)} keeps it inert - * if the MCP SDK is absent, so a bundle shipping this class without the SDK causes no - * {@code NoClassDefFoundError}. + *

          Registered through this module's {@code + * META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the feature + * self-activates when {@code spring-services-mcp} is on the classpath — the endpoint and its + * dedicated security filter chain can no longer be accidentally present in an application that + * never added the module. {@link ConditionalOnClass @ConditionalOnClass(McpServer.class)} keeps it + * inert if the MCP SDK is absent, so a bundle shipping this class without the SDK causes no {@code + * NoClassDefFoundError}. * *

          Imports {@link McpConfiguration}, the feature entry point, which binds {@link McpProperties} - * unconditionally and wires the server/security beans only when {@code openelements.mcp.enabled=true} - * (unchanged {@code @ConditionalOnProperty} behaviour). {@code @Import(McpConfiguration.class)} - * therefore remains valid for consumers who prefer explicit wiring. + * unconditionally and wires the server/security beans only when {@code + * openelements.mcp.enabled=true} (unchanged {@code @ConditionalOnProperty} behaviour). + * {@code @Import(McpConfiguration.class)} therefore remains valid for consumers who prefer explicit + * wiring. */ @AutoConfiguration @ConditionalOnClass(McpServer.class) @Import(McpConfiguration.class) public class McpAutoConfiguration { - /** Creates the auto-configuration. */ - public McpAutoConfiguration() { - } + /** Creates the auto-configuration. */ + public McpAutoConfiguration() {} } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpConfiguration.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpConfiguration.java index 48728c5..49e1323 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpConfiguration.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpConfiguration.java @@ -7,25 +7,21 @@ /** * Entry point for the generic MCP server support. * - *

          Binds {@link McpProperties} unconditionally so the {@code @ConditionalOnProperty} - * MCP beans (security chain, server wiring) can read the master switch and the - * per-profile toggles; the endpoint and server beans themselves are only created - * when {@code openelements.mcp.enabled=true}. + *

          Binds {@link McpProperties} unconditionally so the {@code @ConditionalOnProperty} MCP beans + * (security chain, server wiring) can read the master switch and the per-profile toggles; the + * endpoint and server beans themselves are only created when {@code openelements.mcp.enabled=true}. * - *

          Because these classes live outside an application's component-scan base - * package, the application wires the feature in with - * {@code @Import(McpConfiguration.class)} (mirroring how - * {@code com.openelements.spring.base.FullSpringServiceConfig} pulls in the rest - * of the library). Domain modules contribute tools by exposing - * {@link McpToolProvider} beans, which {@code McpServerConfig} discovers and - * aggregates. + *

          Because these classes live outside an application's component-scan base package, the + * application wires the feature in with {@code @Import(McpConfiguration.class)} (mirroring how + * {@code com.openelements.spring.base.FullSpringServiceConfig} pulls in the rest of the library). + * Domain modules contribute tools by exposing {@link McpToolProvider} beans, which {@code + * McpServerConfig} discovers and aggregates. */ @Configuration @EnableConfigurationProperties(McpProperties.class) @Import({McpPaging.class, McpToolSupport.class, McpSecurityConfig.class, McpServerConfig.class}) public class McpConfiguration { - /** Creates the configuration. */ - public McpConfiguration() { - } + /** Creates the configuration. */ + public McpConfiguration() {} } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpPage.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpPage.java index 246f0d2..45cc9c9 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpPage.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpPage.java @@ -1,46 +1,37 @@ package com.openelements.spring.base.mcp; -import org.springframework.data.domain.Page; - import java.util.List; +import org.springframework.data.domain.Page; /** * Paginated tool-response envelope. * - *

          Collection tools return this instead of a bare array so the model can tell - * whether it has seen everything: {@link #hasMore()} together with - * {@link #totalCount()} signals that further pages exist, preventing answers from - * a silently truncated first page. + *

          Collection tools return this instead of a bare array so the model can tell whether it has seen + * everything: {@link #hasMore()} together with {@link #totalCount()} signals that further pages + * exist, preventing answers from a silently truncated first page. * - * @param items the items on this page (at most {@link #size()}) - * @param page the zero-based page index - * @param size the page size used for this response + * @param items the items on this page (at most {@link #size()}) + * @param page the zero-based page index + * @param size the page size used for this response * @param totalCount the total number of matching items across all pages - * @param hasMore {@code true} if at least one more page exists after this one - * @param the item type + * @param hasMore {@code true} if at least one more page exists after this one + * @param the item type */ -public record McpPage( - List items, - int page, - int size, - long totalCount, - boolean hasMore -) { +public record McpPage(List items, int page, int size, long totalCount, boolean hasMore) { - /** - * Wraps a Spring Data {@link Page} into the MCP envelope. - * - * @param page the source page - * @param the item type - * @return the envelope - */ - public static McpPage from(final Page page) { - return new McpPage<>( - page.getContent(), - page.getNumber(), - page.getSize(), - page.getTotalElements(), - !page.isLast() - ); - } + /** + * Wraps a Spring Data {@link Page} into the MCP envelope. + * + * @param page the source page + * @param the item type + * @return the envelope + */ + public static McpPage from(final Page page) { + return new McpPage<>( + page.getContent(), + page.getNumber(), + page.getSize(), + page.getTotalElements(), + !page.isLast()); + } } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpPaging.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpPaging.java index d110822..44c21cd 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpPaging.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpPaging.java @@ -1,77 +1,76 @@ package com.openelements.spring.base.mcp; +import java.util.Objects; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; -import java.util.Objects; - /** - * Resolves and clamps the {@code page}/{@code size} parameters of paginated MCP - * tools against {@link McpProperties}. + * Resolves and clamps the {@code page}/{@code size} parameters of paginated MCP tools against + * {@link McpProperties}. * - *

          An omitted {@code size} falls back to the configured default; a {@code size} - * above the configured maximum is clamped down; a non-positive {@code size} or a - * negative {@code page} is rejected with {@link IllegalArgumentException} (mapped - * to a JSON-RPC invalid-parameter error in the tool layer). + *

          An omitted {@code size} falls back to the configured default; a {@code size} above the + * configured maximum is clamped down; a non-positive {@code size} or a negative {@code page} is + * rejected with {@link IllegalArgumentException} (mapped to a JSON-RPC invalid-parameter error in + * the tool layer). */ @Component public class McpPaging { - private final McpProperties properties; + private final McpProperties properties; - /** - * Creates the paging helper. - * - * @param properties the MCP properties supplying the default and maximum page sizes - */ - public McpPaging(final McpProperties properties) { - this.properties = Objects.requireNonNull(properties, "properties must not be null"); - } + /** + * Creates the paging helper. + * + * @param properties the MCP properties supplying the default and maximum page sizes + */ + public McpPaging(final McpProperties properties) { + this.properties = Objects.requireNonNull(properties, "properties must not be null"); + } - /** - * Resolves the effective page size: default when {@code null}, clamped to the - * configured maximum, rejecting non-positive values. - * - * @param requested the requested size, or {@code null} - * @return the effective size in {@code [1, maxPageSize]} - */ - public int resolveSize(final Integer requested) { - if (requested == null) { - return properties.defaultPageSize(); - } - if (requested <= 0) { - throw new IllegalArgumentException("size must be >= 1"); - } - return Math.min(requested, properties.maxPageSize()); + /** + * Resolves the effective page size: default when {@code null}, clamped to the configured maximum, + * rejecting non-positive values. + * + * @param requested the requested size, or {@code null} + * @return the effective size in {@code [1, maxPageSize]} + */ + public int resolveSize(final Integer requested) { + if (requested == null) { + return properties.defaultPageSize(); } - - /** - * Resolves the effective page index: {@code 0} when {@code null}, rejecting negatives. - * - * @param requested the requested zero-based page, or {@code null} - * @return the effective page index - */ - public int resolvePage(final Integer requested) { - if (requested == null) { - return 0; - } - if (requested < 0) { - throw new IllegalArgumentException("page must be >= 0"); - } - return requested; + if (requested <= 0) { + throw new IllegalArgumentException("size must be >= 1"); } + return Math.min(requested, properties.maxPageSize()); + } - /** - * Builds a sorted {@link Pageable} from the requested parameters. - * - * @param page the requested page, or {@code null} - * @param size the requested size, or {@code null} - * @param sort the sort to apply - * @return the resolved pageable - */ - public Pageable toPageable(final Integer page, final Integer size, final Sort sort) { - return PageRequest.of(resolvePage(page), resolveSize(size), sort); + /** + * Resolves the effective page index: {@code 0} when {@code null}, rejecting negatives. + * + * @param requested the requested zero-based page, or {@code null} + * @return the effective page index + */ + public int resolvePage(final Integer requested) { + if (requested == null) { + return 0; + } + if (requested < 0) { + throw new IllegalArgumentException("page must be >= 0"); } + return requested; + } + + /** + * Builds a sorted {@link Pageable} from the requested parameters. + * + * @param page the requested page, or {@code null} + * @param size the requested size, or {@code null} + * @param sort the sort to apply + * @return the resolved pageable + */ + public Pageable toPageable(final Integer page, final Integer size, final Sort sort) { + return PageRequest.of(resolvePage(page), resolveSize(size), sort); + } } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpProperties.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpProperties.java index c10bda9..1626f00 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpProperties.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpProperties.java @@ -6,57 +6,51 @@ /** * Configuration for the Model Context Protocol (MCP) server. * - *

          Bound from the {@code openelements.mcp.*} namespace. The {@link #enabled()} - * master switch defaults to {@code false}: the MCP endpoint exposes personal CRM - * data to external clients and must be turned on deliberately per environment, - * after the Phase-1 GDPR checklist is satisfied. + *

          Bound from the {@code openelements.mcp.*} namespace. The {@link #enabled()} master switch + * defaults to {@code false}: the MCP endpoint exposes personal CRM data to external clients and + * must be turned on deliberately per environment, after the Phase-1 GDPR checklist is satisfied. * - *

          The two auth profiles are toggled independently: Phase 1 uses - * {@code auth.api-key} (Onyx via {@code X-API-Key}); Phase 2 will add - * {@code auth.oidc} (Claude via per-user Authentik OIDC). + *

          The two auth profiles are toggled independently: Phase 1 uses {@code auth.api-key} (Onyx via + * {@code X-API-Key}); Phase 2 will add {@code auth.oidc} (Claude via per-user Authentik OIDC). * - * @param enabled master switch; when {@code false} no MCP endpoint or bean is registered - * @param serverName MCP server name advertised to clients (shown in their tool picker); generic default, override per deployment - * @param serverVersion MCP server version advertised to clients; generic default, override per deployment - * @param maxPageSize hard upper bound for paginated tools; requested sizes are clamped to this + * @param enabled master switch; when {@code false} no MCP endpoint or bean is registered + * @param serverName MCP server name advertised to clients (shown in their tool picker); generic + * default, override per deployment + * @param serverVersion MCP server version advertised to clients; generic default, override per + * deployment + * @param maxPageSize hard upper bound for paginated tools; requested sizes are clamped to this * @param defaultPageSize page size used when a tool call omits {@code size} - * @param auth per-profile authentication switches + * @param auth per-profile authentication switches */ @ConfigurationProperties(prefix = "openelements.mcp") public record McpProperties( - @DefaultValue("false") boolean enabled, - @DefaultValue("MCP Server") String serverName, - @DefaultValue("0.0.0") String serverVersion, - @DefaultValue("50") int maxPageSize, - @DefaultValue("20") int defaultPageSize, - @DefaultValue Auth auth -) { + @DefaultValue("false") boolean enabled, + @DefaultValue("MCP Server") String serverName, + @DefaultValue("0.0.0") String serverVersion, + @DefaultValue("50") int maxPageSize, + @DefaultValue("20") int defaultPageSize, + @DefaultValue Auth auth) { + + /** + * Authentication profile switches. + * + * @param apiKey Phase 1 — API-key profile (Onyx) + * @param oidc Phase 2 — per-user OIDC profile (Claude) + */ + public record Auth(@DefaultValue ApiKey apiKey, @DefaultValue Oidc oidc) { /** - * Authentication profile switches. + * API-key auth profile (Phase 1). * - * @param apiKey Phase 1 — API-key profile (Onyx) - * @param oidc Phase 2 — per-user OIDC profile (Claude) + * @param enabled whether the {@code X-API-Key} profile is active on {@code /mcp} */ - public record Auth( - @DefaultValue ApiKey apiKey, - @DefaultValue Oidc oidc - ) { - - /** - * API-key auth profile (Phase 1). - * - * @param enabled whether the {@code X-API-Key} profile is active on {@code /mcp} - */ - public record ApiKey(@DefaultValue("true") boolean enabled) { - } + public record ApiKey(@DefaultValue("true") boolean enabled) {} - /** - * Per-user OIDC auth profile (Phase 2, not yet implemented). - * - * @param enabled whether the OIDC profile is active on {@code /mcp} - */ - public record Oidc(@DefaultValue("false") boolean enabled) { - } - } + /** + * Per-user OIDC auth profile (Phase 2, not yet implemented). + * + * @param enabled whether the OIDC profile is active on {@code /mcp} + */ + public record Oidc(@DefaultValue("false") boolean enabled) {} + } } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpSecurityConfig.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpSecurityConfig.java index 9b07027..f21670a 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpSecurityConfig.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpSecurityConfig.java @@ -17,63 +17,62 @@ /** * Security configuration for the MCP endpoint (Phase 1). * - *

          Registers a dedicated {@link SecurityFilterChain} scoped to {@code /mcp/**} - * with {@code @Order(0)} — ahead of the spring-services - * {@code externalApiFilterChain} ({@code @Order(1)}, locked to GET on - * {@code /api/external/**}) and {@code defaultFilterChain} ({@code @Order(2)}, - * the JWT catch-all). Because the chain's {@code securityMatcher} only matches + *

          Registers a dedicated {@link SecurityFilterChain} scoped to {@code /mcp/**} with + * {@code @Order(0)} — ahead of the spring-services {@code externalApiFilterChain} + * ({@code @Order(1)}, locked to GET on {@code /api/external/**}) and {@code defaultFilterChain} + * ({@code @Order(2)}, the JWT catch-all). Because the chain's {@code securityMatcher} only matches * {@code /mcp}, ordering it first never interferes with {@code /api/**}. * - *

          Authentication reuses the spring-services {@link ApiKeyAuthenticationFilter} - * (which is HTTP-method-agnostic — it only inspects the {@code X-API-Key} - * header), so the MCP {@code POST} endpoint authenticates with the existing - * CRM API keys even though spring-services' own external chain permits only GET. - * A fresh filter instance is constructed here (rather than reusing the library - * bean) to keep this chain self-contained and avoid global servlet-filter - * registration side effects. + *

          Authentication reuses the spring-services {@link ApiKeyAuthenticationFilter} (which is + * HTTP-method-agnostic — it only inspects the {@code X-API-Key} header), so the MCP {@code POST} + * endpoint authenticates with the existing CRM API keys even though spring-services' own external + * chain permits only GET. A fresh filter instance is constructed here (rather than reusing the + * library bean) to keep this chain self-contained and avoid global servlet-filter registration side + * effects. * - *

          The whole configuration is gated on {@code openelements.mcp.enabled=true} - * and the API-key profile being enabled. CSRF is disabled and the session - * policy is stateless — this is a machine-to-machine JSON-RPC endpoint. + *

          The whole configuration is gated on {@code openelements.mcp.enabled=true} and the API-key + * profile being enabled. CSRF is disabled and the session policy is stateless — this is a + * machine-to-machine JSON-RPC endpoint. */ @Configuration @ConditionalOnProperty(prefix = "openelements.mcp", name = "enabled", havingValue = "true") public class McpSecurityConfig { - /** Creates the configuration. */ - public McpSecurityConfig() { - } + /** Creates the configuration. */ + public McpSecurityConfig() {} - /** Path patterns covered by the MCP security chain: the endpoint itself and any sub-path. */ - static final String[] MCP_PATHS = {"/mcp", "/mcp/**"}; + /** Path patterns covered by the MCP security chain: the endpoint itself and any sub-path. */ + static final String[] MCP_PATHS = {"/mcp", "/mcp/**"}; - /** - * The {@code /mcp} filter chain for the API-key auth profile (Phase 1). - * - * @param http the {@link HttpSecurity} to configure - * @param apiKeyDataService the spring-services key store used for validation - * @param apiKeyEntryPoint the JSON 401 entry point used by the external API chain - * @return the configured {@link SecurityFilterChain} - * @throws Exception if the chain cannot be built - */ - @Bean - @Order(0) - @ConditionalOnProperty(prefix = "openelements.mcp.auth.api-key", name = "enabled", - havingValue = "true", matchIfMissing = true) - public SecurityFilterChain mcpApiKeyFilterChain( - final HttpSecurity http, - final ApiKeyDataService apiKeyDataService, - @Qualifier("apiKeyAuthenticationEntryPoint") final AuthenticationEntryPoint apiKeyEntryPoint - ) throws Exception { - final ApiKeyAuthenticationFilter mcpApiKeyFilter = - new ApiKeyAuthenticationFilter(apiKeyDataService, apiKeyEntryPoint); - http - .securityMatcher(MCP_PATHS) - .csrf(AbstractHttpConfigurer::disable) - .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) - .exceptionHandling(eh -> eh.authenticationEntryPoint(apiKeyEntryPoint)) - .addFilterBefore(mcpApiKeyFilter, UsernamePasswordAuthenticationFilter.class); - return http.build(); - } + /** + * The {@code /mcp} filter chain for the API-key auth profile (Phase 1). + * + * @param http the {@link HttpSecurity} to configure + * @param apiKeyDataService the spring-services key store used for validation + * @param apiKeyEntryPoint the JSON 401 entry point used by the external API chain + * @return the configured {@link SecurityFilterChain} + * @throws Exception if the chain cannot be built + */ + @Bean + @Order(0) + @ConditionalOnProperty( + prefix = "openelements.mcp.auth.api-key", + name = "enabled", + havingValue = "true", + matchIfMissing = true) + public SecurityFilterChain mcpApiKeyFilterChain( + final HttpSecurity http, + final ApiKeyDataService apiKeyDataService, + @Qualifier("apiKeyAuthenticationEntryPoint") final AuthenticationEntryPoint apiKeyEntryPoint) + throws Exception { + final ApiKeyAuthenticationFilter mcpApiKeyFilter = + new ApiKeyAuthenticationFilter(apiKeyDataService, apiKeyEntryPoint); + http.securityMatcher(MCP_PATHS) + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) + .exceptionHandling(eh -> eh.authenticationEntryPoint(apiKeyEntryPoint)) + .addFilterBefore(mcpApiKeyFilter, UsernamePasswordAuthenticationFilter.class); + return http.build(); + } } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpServerConfig.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpServerConfig.java index f152e22..1f7048d 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpServerConfig.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpServerConfig.java @@ -7,6 +7,8 @@ import io.modelcontextprotocol.server.McpServerFeatures.SyncToolSpecification; import io.modelcontextprotocol.server.McpSyncServer; import io.modelcontextprotocol.spec.McpSchema; +import java.util.List; +import java.util.Map; import org.springframework.ai.mcp.server.webmvc.transport.WebMvcStreamableServerTransportProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; @@ -15,105 +17,101 @@ import org.springframework.web.servlet.function.ServerResponse; import tools.jackson.databind.json.JsonMapper; -import java.util.List; -import java.util.Map; - /** * Wires the MCP server endpoint. * - *

          Only active when {@code openelements.mcp.enabled=true}. Builds Spring AI's - * {@link WebMvcStreamableServerTransportProvider} for the official Java MCP SDK (Streamable HTTP - * at {@code /mcp}), assembles the {@link McpSyncServer} from the tool catalog - * contributed by every {@link McpToolProvider} bean, and exposes the transport's - * {@link RouterFunction} so Spring WebMVC serves the endpoint. + *

          Only active when {@code openelements.mcp.enabled=true}. Builds Spring AI's {@link + * WebMvcStreamableServerTransportProvider} for the official Java MCP SDK (Streamable HTTP at {@code + * /mcp}), assembles the {@link McpSyncServer} from the tool catalog contributed by every {@link + * McpToolProvider} bean, and exposes the transport's {@link RouterFunction} so Spring WebMVC serves + * the endpoint. * - *

          This configuration carries no domain knowledge: the actual tools come from - * the {@link McpToolProvider} implementations discovered in the application - * context, so feature modules contribute tools without this class changing. + *

          This configuration carries no domain knowledge: the actual tools come from the {@link + * McpToolProvider} implementations discovered in the application context, so feature modules + * contribute tools without this class changing. */ @Configuration @ConditionalOnProperty(prefix = "openelements.mcp", name = "enabled", havingValue = "true") public class McpServerConfig { - /** Creates the configuration. */ - public McpServerConfig() { - } + /** Creates the configuration. */ + public McpServerConfig() {} - /** - * The MCP endpoint path; kept in sync with {@link McpSecurityConfig#MCP_PATHS}. - */ - static final String MCP_ENDPOINT = "/mcp"; + /** The MCP endpoint path; kept in sync with {@link McpSecurityConfig#MCP_PATHS}. */ + static final String MCP_ENDPOINT = "/mcp"; - /** - * The Streamable HTTP transport provider. Uses the application's Jackson - * {@link JsonMapper} (so date/time and other modules match the REST API) - * wrapped as the SDK's {@code McpJsonMapper}. - * - * @param jsonMapper the application's Jackson mapper used to (de)serialize MCP payloads - * @param apiKeyDataService the key store used to resolve the authenticated actor from the - * {@code X-API-Key} header for the transport context - * @return the configured Streamable HTTP transport provider serving {@code /mcp} - */ - @Bean - public WebMvcStreamableServerTransportProvider mcpTransportProvider( - final JsonMapper jsonMapper, final ApiKeyDataService apiKeyDataService) { - return WebMvcStreamableServerTransportProvider.builder() - .jsonMapper(new JacksonMcpJsonMapper(jsonMapper)) - .mcpEndpoint(MCP_ENDPOINT) - // Capture the authenticated actor label on the request thread (where - // the X-API-Key header is available) and pass it through the MCP - // transport context — the tool handler may run on a different thread - // without the Spring SecurityContext. - .contextExtractor(request -> { - final String apiKey = request.headers().firstHeader("X-API-Key"); - if (apiKey == null) { - return McpTransportContext.EMPTY; - } - return apiKeyDataService.authenticate(apiKey) - .map(entity -> McpTransportContext.create( - Map.of(McpActorLabel.ACTOR_LABEL_KEY, "apikey:" + entity.getName()))) - .orElse(McpTransportContext.EMPTY); - }) - .build(); - } + /** + * The Streamable HTTP transport provider. Uses the application's Jackson {@link JsonMapper} (so + * date/time and other modules match the REST API) wrapped as the SDK's {@code McpJsonMapper}. + * + * @param jsonMapper the application's Jackson mapper used to (de)serialize MCP payloads + * @param apiKeyDataService the key store used to resolve the authenticated actor from the {@code + * X-API-Key} header for the transport context + * @return the configured Streamable HTTP transport provider serving {@code /mcp} + */ + @Bean + public WebMvcStreamableServerTransportProvider mcpTransportProvider( + final JsonMapper jsonMapper, final ApiKeyDataService apiKeyDataService) { + return WebMvcStreamableServerTransportProvider.builder() + .jsonMapper(new JacksonMcpJsonMapper(jsonMapper)) + .mcpEndpoint(MCP_ENDPOINT) + // Capture the authenticated actor label on the request thread (where + // the X-API-Key header is available) and pass it through the MCP + // transport context — the tool handler may run on a different thread + // without the Spring SecurityContext. + .contextExtractor( + request -> { + final String apiKey = request.headers().firstHeader("X-API-Key"); + if (apiKey == null) { + return McpTransportContext.EMPTY; + } + return apiKeyDataService + .authenticate(apiKey) + .map( + entity -> + McpTransportContext.create( + Map.of(McpActorLabel.ACTOR_LABEL_KEY, "apikey:" + entity.getName()))) + .orElse(McpTransportContext.EMPTY); + }) + .build(); + } - /** - * The sync MCP server. Building it registers the session factory on the - * transport provider, so this bean must be initialized before the endpoint - * serves requests (the router-function bean depends on it). - * - * @param transportProvider the transport provider - * @param toolProviders all tool providers contributing to the catalog - * @param properties the MCP server properties (name/version) - * @return the built sync server - */ - @Bean - public McpSyncServer mcpSyncServer(final WebMvcStreamableServerTransportProvider transportProvider, - final List toolProviders, - final McpProperties properties) { - final List tools = toolProviders.stream() - .flatMap(provider -> provider.toolSpecifications().stream()) - .toList(); - return McpServer.sync(transportProvider) - .serverInfo(properties.serverName(), properties.serverVersion()) - .capabilities(McpSchema.ServerCapabilities.builder().tools(true).build()) - .tools(tools) - .build(); - } + /** + * The sync MCP server. Building it registers the session factory on the transport provider, so + * this bean must be initialized before the endpoint serves requests (the router-function bean + * depends on it). + * + * @param transportProvider the transport provider + * @param toolProviders all tool providers contributing to the catalog + * @param properties the MCP server properties (name/version) + * @return the built sync server + */ + @Bean + public McpSyncServer mcpSyncServer( + final WebMvcStreamableServerTransportProvider transportProvider, + final List toolProviders, + final McpProperties properties) { + final List tools = + toolProviders.stream().flatMap(provider -> provider.toolSpecifications().stream()).toList(); + return McpServer.sync(transportProvider) + .serverInfo(properties.serverName(), properties.serverVersion()) + .capabilities(McpSchema.ServerCapabilities.builder().tools(true).build()) + .tools(tools) + .build(); + } - /** - * Exposes the transport's router function to Spring WebMVC. Depends on - * {@link #mcpSyncServer} so the transport's session factory is wired before - * any request is routed. - * - * @param transportProvider the transport provider - * @param mcpSyncServer the built server (ordering dependency; not used directly) - * @return the router function serving {@code /mcp} - */ - @Bean - public RouterFunction mcpRouterFunction( - final WebMvcStreamableServerTransportProvider transportProvider, - final McpSyncServer mcpSyncServer) { - return transportProvider.getRouterFunction(); - } + /** + * Exposes the transport's router function to Spring WebMVC. Depends on {@link #mcpSyncServer} so + * the transport's session factory is wired before any request is routed. + * + * @param transportProvider the transport provider + * @param mcpSyncServer the built server (ordering dependency; not used directly) + * @return the router function serving {@code /mcp} + */ + @Bean + public RouterFunction mcpRouterFunction( + final WebMvcStreamableServerTransportProvider transportProvider, + final McpSyncServer mcpSyncServer) { + return transportProvider.getRouterFunction(); + } } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolLogic.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolLogic.java index 6f5326c..dc5fd28 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolLogic.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolLogic.java @@ -3,25 +3,23 @@ import java.util.Map; /** - * The executable body of an MCP tool: validates and parses its - * arguments, calls a backing service, and returns the payload object to - * serialize as the tool result. + * The executable body of an MCP tool: validates and parses its arguments, calls a backing service, + * and returns the payload object to serialize as the tool result. * - *

          Thrown exceptions are mapped to JSON-RPC error results by - * {@link McpToolSupport#spec}: {@link IllegalArgumentException} becomes an - * invalid-argument error, {@link java.util.NoSuchElementException} a not-found - * error, {@link McpUnavailableException} a temporary-unavailable error, and any - * other exception a generic internal error. + *

          Thrown exceptions are mapped to JSON-RPC error results by {@link McpToolSupport#spec}: {@link + * IllegalArgumentException} becomes an invalid-argument error, {@link + * java.util.NoSuchElementException} a not-found error, {@link McpUnavailableException} a + * temporary-unavailable error, and any other exception a generic internal error. */ @FunctionalInterface public interface McpToolLogic { - /** - * Runs the tool. - * - * @param args the tool arguments (never {@code null}; empty when none were sent) - * @return the payload to serialize as the tool result - * @throws Exception to signal an error, mapped to a JSON-RPC error result - */ - Object run(Map args) throws Exception; + /** + * Runs the tool. + * + * @param args the tool arguments (never {@code null}; empty when none were sent) + * @return the payload to serialize as the tool result + * @throws Exception to signal an error, mapped to a JSON-RPC error result + */ + Object run(Map args) throws Exception; } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolProvider.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolProvider.java index 58e0c06..06f92aa 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolProvider.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolProvider.java @@ -1,27 +1,25 @@ package com.openelements.spring.base.mcp; import io.modelcontextprotocol.server.McpServerFeatures.SyncToolSpecification; - import java.util.List; /** * SPI for contributing MCP tools to the server. * - *

          Each feature module implements this interface and is discovered as a Spring - * bean. {@code McpServerConfig} aggregates the tool specifications of all - * providers into the single {@code McpSyncServer}, so a module adds tools without - * touching the generic server wiring. + *

          Each feature module implements this interface and is discovered as a Spring bean. {@code + * McpServerConfig} aggregates the tool specifications of all providers into the single {@code + * McpSyncServer}, so a module adds tools without touching the generic server wiring. * - *

          Implementations typically build their specifications with {@link McpTools} - * (schema and argument helpers) and {@link McpToolSupport#spec} (dispatch, access - * logging, and JSON-RPC error mapping). + *

          Implementations typically build their specifications with {@link McpTools} (schema and + * argument helpers) and {@link McpToolSupport#spec} (dispatch, access logging, and JSON-RPC error + * mapping). */ public interface McpToolProvider { - /** - * Returns the MCP tool specifications contributed by this provider. - * - * @return the tool specifications contributed by this provider - */ - List toolSpecifications(); + /** + * Returns the MCP tool specifications contributed by this provider. + * + * @return the tool specifications contributed by this provider + */ + List toolSpecifications(); } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolSupport.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolSupport.java index f57dc0b..9256ccd 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolSupport.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpToolSupport.java @@ -2,114 +2,124 @@ import io.modelcontextprotocol.server.McpServerFeatures.SyncToolSpecification; import io.modelcontextprotocol.spec.McpSchema; +import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import tools.jackson.core.JacksonException; import tools.jackson.databind.ObjectMapper; -import java.util.*; - /** * Generic runtime support for MCP tool implementations. * - *

          {@link #spec} wraps a tool's {@link McpToolLogic} into a - * {@link SyncToolSpecification} that resolves the calling actor, runs the logic, - * serializes the payload to JSON, logs one structured access line - * ({@code tool=… actor=…}, never the arguments), and maps failures to JSON-RPC - * error results. {@link #paginate} slices a fully materialized list into the - * {@link McpPage} envelope using the configured paging defaults and clamps. + *

          {@link #spec} wraps a tool's {@link McpToolLogic} into a {@link SyncToolSpecification} that + * resolves the calling actor, runs the logic, serializes the payload to JSON, logs one structured + * access line ({@code tool=… actor=…}, never the arguments), and maps failures to JSON-RPC error + * results. {@link #paginate} slices a fully materialized list into the {@link McpPage} envelope + * using the configured paging defaults and clamps. * - *

          This class carries no domain knowledge; {@link McpToolProvider} - * implementations build their schemas and parse arguments with {@link McpTools}. + *

          This class carries no domain knowledge; {@link McpToolProvider} implementations build their + * schemas and parse arguments with {@link McpTools}. * - *

          MCP reads are not written to an audit log: read access (like - * viewing a record in a frontend) is recorded only as a structured INFO log line. + *

          MCP reads are not written to an audit log: read access (like viewing a record in a + * frontend) is recorded only as a structured INFO log line. */ @Component public class McpToolSupport { - private static final Logger log = LoggerFactory.getLogger(McpToolSupport.class); + private static final Logger log = LoggerFactory.getLogger(McpToolSupport.class); - private final McpPaging paging; - private final ObjectMapper objectMapper; + private final McpPaging paging; + private final ObjectMapper objectMapper; - /** - * Creates the tool support. - * - * @param paging the paging helper used to resolve and clamp page requests - * @param objectMapper the Jackson mapper used to serialize tool payloads to JSON - */ - public McpToolSupport(final McpPaging paging, final ObjectMapper objectMapper) { - this.paging = Objects.requireNonNull(paging, "paging must not be null"); - this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); - } + /** + * Creates the tool support. + * + * @param paging the paging helper used to resolve and clamp page requests + * @param objectMapper the Jackson mapper used to serialize tool payloads to JSON + */ + public McpToolSupport(final McpPaging paging, final ObjectMapper objectMapper) { + this.paging = Objects.requireNonNull(paging, "paging must not be null"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); + } - /** - * Wraps tool logic into a sync tool specification with access logging and - * JSON-RPC error mapping. - * - * @param tool the tool definition (see {@link McpTools#tool}) - * @param logic the tool body - * @return the sync tool specification - */ - public SyncToolSpecification spec(final McpSchema.Tool tool, final McpToolLogic logic) { - return SyncToolSpecification.builder() - .tool(tool) - .callHandler((exchange, request) -> invoke(tool.name(), logic, request.arguments(), - McpActorLabel.from(exchange.transportContext()))) - .build(); - } + /** + * Wraps tool logic into a sync tool specification with access logging and JSON-RPC error mapping. + * + * @param tool the tool definition (see {@link McpTools#tool}) + * @param logic the tool body + * @return the sync tool specification + */ + public SyncToolSpecification spec(final McpSchema.Tool tool, final McpToolLogic logic) { + return SyncToolSpecification.builder() + .tool(tool) + .callHandler( + (exchange, request) -> + invoke( + tool.name(), + logic, + request.arguments(), + McpActorLabel.from(exchange.transportContext()))) + .build(); + } - private McpSchema.CallToolResult invoke(final String name, final McpToolLogic logic, - final Map rawArgs, final String actor) { - final Map args = rawArgs == null ? Map.of() : rawArgs; - try { - final Object payload = logic.run(args); - log.info("MCP tool call tool={} actor={}", name, actor); - return result(json(payload), false); - } catch (final IllegalArgumentException e) { - log.info("MCP tool call rejected tool={} actor={} reason=invalid-argument", name, actor); - return result("Invalid argument: " + e.getMessage(), true); - } catch (final NoSuchElementException e) { - log.info("MCP tool call not-found tool={} actor={}", name, actor); - return result(e.getMessage(), true); - } catch (final McpUnavailableException e) { - log.info("MCP tool call unavailable tool={} actor={}", name, actor); - return result(e.getMessage(), true); - } catch (final Exception e) { - log.warn("MCP tool call errored tool={} actor={} error={}", name, actor, e.getClass().getSimpleName()); - return result("Internal error executing tool " + name, true); - } + private McpSchema.CallToolResult invoke( + final String name, + final McpToolLogic logic, + final Map rawArgs, + final String actor) { + final Map args = rawArgs == null ? Map.of() : rawArgs; + try { + final Object payload = logic.run(args); + log.info("MCP tool call tool={} actor={}", name, actor); + return result(json(payload), false); + } catch (final IllegalArgumentException e) { + log.info("MCP tool call rejected tool={} actor={} reason=invalid-argument", name, actor); + return result("Invalid argument: " + e.getMessage(), true); + } catch (final NoSuchElementException e) { + log.info("MCP tool call not-found tool={} actor={}", name, actor); + return result(e.getMessage(), true); + } catch (final McpUnavailableException e) { + log.info("MCP tool call unavailable tool={} actor={}", name, actor); + return result(e.getMessage(), true); + } catch (final Exception e) { + log.warn( + "MCP tool call errored tool={} actor={} error={}", + name, + actor, + e.getClass().getSimpleName()); + return result("Internal error executing tool " + name, true); } + } - private static McpSchema.CallToolResult result(final String text, final boolean error) { - return McpSchema.CallToolResult.builder().addTextContent(text).isError(error).build(); - } + private static McpSchema.CallToolResult result(final String text, final boolean error) { + return McpSchema.CallToolResult.builder().addTextContent(text).isError(error).build(); + } - private String json(final Object payload) { - try { - return objectMapper.writeValueAsString(payload); - } catch (final JacksonException e) { - throw new IllegalStateException("Failed to serialize MCP tool payload", e); - } + private String json(final Object payload) { + try { + return objectMapper.writeValueAsString(payload); + } catch (final JacksonException e) { + throw new IllegalStateException("Failed to serialize MCP tool payload", e); } + } - /** - * Slices a fully materialized list into the {@link McpPage} envelope using the - * configured paging defaults and clamps. - * - * @param all the full result list - * @param pageReq the requested zero-based page, or {@code null} - * @param sizeReq the requested page size, or {@code null} - * @param the item type - * @return the page envelope - */ - public McpPage paginate(final List all, final Integer pageReq, final Integer sizeReq) { - final int size = paging.resolveSize(sizeReq); - final int page = paging.resolvePage(pageReq); - final int from = Math.min(page * size, all.size()); - final int to = Math.min(from + size, all.size()); - return new McpPage<>(new ArrayList<>(all.subList(from, to)), page, size, all.size(), to < all.size()); - } + /** + * Slices a fully materialized list into the {@link McpPage} envelope using the configured paging + * defaults and clamps. + * + * @param all the full result list + * @param pageReq the requested zero-based page, or {@code null} + * @param sizeReq the requested page size, or {@code null} + * @param the item type + * @return the page envelope + */ + public McpPage paginate(final List all, final Integer pageReq, final Integer sizeReq) { + final int size = paging.resolveSize(sizeReq); + final int page = paging.resolvePage(pageReq); + final int from = Math.min(page * size, all.size()); + final int to = Math.min(from + size, all.size()); + return new McpPage<>( + new ArrayList<>(all.subList(from, to)), page, size, all.size(), to < all.size()); + } } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpTools.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpTools.java index fb53bf9..59682ac 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpTools.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpTools.java @@ -1,220 +1,226 @@ package com.openelements.spring.base.mcp; import io.modelcontextprotocol.spec.McpSchema; - import java.util.*; /** - * Domain-agnostic helpers for building MCP tool input schemas and for parsing and - * validating tool arguments. + * Domain-agnostic helpers for building MCP tool input schemas and for parsing and validating tool + * arguments. * - *

          Intended for static import by {@link McpToolProvider} implementations. The - * schema builders produce the JSON-schema fragments the MCP SDK expects; the - * argument accessors coerce the loosely typed argument map into Java types, - * throwing {@link IllegalArgumentException} on malformed or missing required - * input (which {@link McpToolSupport} maps to a JSON-RPC invalid-argument error). + *

          Intended for static import by {@link McpToolProvider} implementations. The schema builders + * produce the JSON-schema fragments the MCP SDK expects; the argument accessors coerce the loosely + * typed argument map into Java types, throwing {@link IllegalArgumentException} on malformed or + * missing required input (which {@link McpToolSupport} maps to a JSON-RPC invalid-argument error). */ public final class McpTools { - private McpTools() { + private McpTools() {} + + // -- Schema builders ---------------------------------------------------- + + /** + * Builds a tool with an {@code object} input schema. + * + * @param name the tool name + * @param description the tool description shown to the model + * @param properties the input properties (insertion order preserved) + * @param required the names of required properties + * @return the tool definition + */ + public static McpSchema.Tool tool( + final String name, + final String description, + final Map properties, + final List required) { + return McpSchema.Tool.builder() + .name(name) + .description(description) + .inputSchema( + new McpSchema.JsonSchema("object", properties, required, Boolean.FALSE, null, null)) + .build(); + } + + /** + * Builds the standard pagination input properties. + * + * @return a mutable property map pre-populated with the standard {@code page} and {@code size} + * pagination properties + */ + public static Map paginationProps() { + final Map props = new LinkedHashMap<>(); + props.put("page", prop("integer", "Zero-based page index (default 0).")); + props.put("size", prop("integer", "Page size (default 20, max 50).")); + return props; + } + + /** + * Builds a schema fragment for a single typed property. + * + * @param type the JSON-schema type (e.g. {@code "string"}, {@code "integer"}) + * @param description the property description + * @return a single-property schema fragment + */ + public static Map prop(final String type, final String description) { + return Map.of("type", type, "description", description); + } + + /** + * Builds a schema fragment for a UUID-formatted string property. + * + * @param description the property description + * @return a schema fragment for a UUID-formatted string property + */ + public static Map uuidProp(final String description) { + return Map.of("type", "string", "format", "uuid", "description", description); + } + + /** + * Builds a schema fragment for an array of UUID-formatted strings. + * + * @param description the property description + * @return a schema fragment for an array of UUID-formatted strings + */ + public static Map uuidArray(final String description) { + return Map.of( + "type", + "array", + "description", + description, + "items", + Map.of("type", "string", "format", "uuid")); + } + + // -- Argument parsing --------------------------------------------------- + + /** + * Reads an optional string argument. + * + * @param args the tool argument map + * @param key the argument name + * @return the argument as a string, or {@code null} if absent + */ + public static String string(final Map args, final String key) { + final Object value = args.get(key); + return value == null ? null : value.toString(); + } + + /** + * Reads a required, non-blank string argument. + * + * @param args the tool argument map + * @param key the argument name + * @return the non-blank argument as a string + * @throws IllegalArgumentException if absent or blank + */ + public static String requiredString(final Map args, final String key) { + final String value = string(args, key); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(key + " is required"); } - - // -- Schema builders ---------------------------------------------------- - - /** - * Builds a tool with an {@code object} input schema. - * - * @param name the tool name - * @param description the tool description shown to the model - * @param properties the input properties (insertion order preserved) - * @param required the names of required properties - * @return the tool definition - */ - public static McpSchema.Tool tool(final String name, final String description, - final Map properties, final List required) { - return McpSchema.Tool.builder() - .name(name) - .description(description) - .inputSchema(new McpSchema.JsonSchema("object", properties, required, Boolean.FALSE, null, null)) - .build(); + return value; + } + + /** + * Reads an optional integer argument. + * + * @param args the tool argument map + * @param key the argument name + * @return the argument as an integer, or {@code null} if absent + * @throws IllegalArgumentException if present but not a valid integer + */ + public static Integer integer(final Map args, final String key) { + final Object value = args.get(key); + if (value == null) { + return null; } - - /** - * Builds the standard pagination input properties. - * - * @return a mutable property map pre-populated with the standard {@code page} - * and {@code size} pagination properties - */ - public static Map paginationProps() { - final Map props = new LinkedHashMap<>(); - props.put("page", prop("integer", "Zero-based page index (default 0).")); - props.put("size", prop("integer", "Page size (default 20, max 50).")); - return props; + if (value instanceof Number number) { + return number.intValue(); } - - /** - * Builds a schema fragment for a single typed property. - * - * @param type the JSON-schema type (e.g. {@code "string"}, {@code "integer"}) - * @param description the property description - * @return a single-property schema fragment - */ - public static Map prop(final String type, final String description) { - return Map.of("type", type, "description", description); + try { + return Integer.valueOf(value.toString().trim()); + } catch (final NumberFormatException e) { + throw new IllegalArgumentException(key + " must be an integer"); } - - /** - * Builds a schema fragment for a UUID-formatted string property. - * - * @param description the property description - * @return a schema fragment for a UUID-formatted string property - */ - public static Map uuidProp(final String description) { - return Map.of("type", "string", "format", "uuid", "description", description); - } - - /** - * Builds a schema fragment for an array of UUID-formatted strings. - * - * @param description the property description - * @return a schema fragment for an array of UUID-formatted strings - */ - public static Map uuidArray(final String description) { - return Map.of("type", "array", "description", description, - "items", Map.of("type", "string", "format", "uuid")); + } + + /** + * Reads an optional boolean argument. + * + * @param args the tool argument map + * @param key the argument name + * @return the argument as a boolean, or {@code null} if absent + */ + public static Boolean bool(final Map args, final String key) { + final Object value = args.get(key); + if (value == null) { + return null; } - - // -- Argument parsing --------------------------------------------------- - - /** - * Reads an optional string argument. - * - * @param args the tool argument map - * @param key the argument name - * @return the argument as a string, or {@code null} if absent - */ - public static String string(final Map args, final String key) { - final Object value = args.get(key); - return value == null ? null : value.toString(); + if (value instanceof Boolean b) { + return b; } - - /** - * Reads a required, non-blank string argument. - * - * @param args the tool argument map - * @param key the argument name - * @return the non-blank argument as a string - * @throws IllegalArgumentException if absent or blank - */ - public static String requiredString(final Map args, final String key) { - final String value = string(args, key); - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(key + " is required"); - } - return value; + return Boolean.valueOf(value.toString().trim()); + } + + /** + * Reads an optional UUID argument. + * + * @param args the tool argument map + * @param key the argument name + * @return the argument as a UUID, or {@code null} if absent or blank + * @throws IllegalArgumentException if present but not a valid UUID + */ + public static UUID uuid(final Map args, final String key) { + final String value = string(args, key); + if (value == null || value.isBlank()) { + return null; } - - /** - * Reads an optional integer argument. - * - * @param args the tool argument map - * @param key the argument name - * @return the argument as an integer, or {@code null} if absent - * @throws IllegalArgumentException if present but not a valid integer - */ - public static Integer integer(final Map args, final String key) { - final Object value = args.get(key); - if (value == null) { - return null; - } - if (value instanceof Number number) { - return number.intValue(); - } - try { - return Integer.valueOf(value.toString().trim()); - } catch (final NumberFormatException e) { - throw new IllegalArgumentException(key + " must be an integer"); - } + try { + return UUID.fromString(value.trim()); + } catch (final IllegalArgumentException e) { + throw new IllegalArgumentException(key + " must be a valid UUID"); } - - /** - * Reads an optional boolean argument. - * - * @param args the tool argument map - * @param key the argument name - * @return the argument as a boolean, or {@code null} if absent - */ - public static Boolean bool(final Map args, final String key) { - final Object value = args.get(key); - if (value == null) { - return null; - } - if (value instanceof Boolean b) { - return b; - } - return Boolean.valueOf(value.toString().trim()); + } + + /** + * Reads a required UUID argument. + * + * @param args the tool argument map + * @param key the argument name + * @return the required argument as a UUID + * @throws IllegalArgumentException if absent, blank, or not a valid UUID + */ + public static UUID requiredUuid(final Map args, final String key) { + final UUID value = uuid(args, key); + if (value == null) { + throw new IllegalArgumentException(key + " is required"); } - - /** - * Reads an optional UUID argument. - * - * @param args the tool argument map - * @param key the argument name - * @return the argument as a UUID, or {@code null} if absent or blank - * @throws IllegalArgumentException if present but not a valid UUID - */ - public static UUID uuid(final Map args, final String key) { - final String value = string(args, key); - if (value == null || value.isBlank()) { - return null; - } - try { - return UUID.fromString(value.trim()); - } catch (final IllegalArgumentException e) { - throw new IllegalArgumentException(key + " must be a valid UUID"); - } + return value; + } + + /** + * Reads an optional array-of-UUIDs argument. + * + * @param args the tool argument map + * @param key the argument name + * @return the argument as a list of UUIDs, or {@code null} if absent + * @throws IllegalArgumentException if present but not an array of valid UUIDs + */ + public static List uuidList(final Map args, final String key) { + final Object value = args.get(key); + if (value == null) { + return null; } - - /** - * Reads a required UUID argument. - * - * @param args the tool argument map - * @param key the argument name - * @return the required argument as a UUID - * @throws IllegalArgumentException if absent, blank, or not a valid UUID - */ - public static UUID requiredUuid(final Map args, final String key) { - final UUID value = uuid(args, key); - if (value == null) { - throw new IllegalArgumentException(key + " is required"); - } - return value; + if (!(value instanceof List list)) { + throw new IllegalArgumentException(key + " must be an array of UUIDs"); } - - /** - * Reads an optional array-of-UUIDs argument. - * - * @param args the tool argument map - * @param key the argument name - * @return the argument as a list of UUIDs, or {@code null} if absent - * @throws IllegalArgumentException if present but not an array of valid UUIDs - */ - public static List uuidList(final Map args, final String key) { - final Object value = args.get(key); - if (value == null) { - return null; - } - if (!(value instanceof List list)) { - throw new IllegalArgumentException(key + " must be an array of UUIDs"); - } - final List result = new ArrayList<>(list.size()); - for (final Object element : list) { - try { - result.add(UUID.fromString(String.valueOf(element).trim())); - } catch (final IllegalArgumentException e) { - throw new IllegalArgumentException(key + " must contain valid UUIDs"); - } - } - return result; + final List result = new ArrayList<>(list.size()); + for (final Object element : list) { + try { + result.add(UUID.fromString(String.valueOf(element).trim())); + } catch (final IllegalArgumentException e) { + throw new IllegalArgumentException(key + " must contain valid UUIDs"); + } } + return result; + } } diff --git a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpUnavailableException.java b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpUnavailableException.java index 9f0f8af..d0f5a51 100644 --- a/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpUnavailableException.java +++ b/spring-services-mcp/src/main/java/com/openelements/spring/base/mcp/McpUnavailableException.java @@ -1,18 +1,18 @@ package com.openelements.spring.base.mcp; /** - * Signals that an MCP tool cannot be served right now because a backing - * subsystem is temporarily unavailable (e.g. the search index is still - * bootstrapping). Mapped to a JSON-RPC error result by the tool dispatcher. + * Signals that an MCP tool cannot be served right now because a backing subsystem is temporarily + * unavailable (e.g. the search index is still bootstrapping). Mapped to a JSON-RPC error result by + * the tool dispatcher. */ public class McpUnavailableException extends RuntimeException { - /** - * Creates the exception. - * - * @param message the detail message describing why the subsystem is unavailable - */ - public McpUnavailableException(final String message) { - super(message); - } + /** + * Creates the exception. + * + * @param message the detail message describing why the subsystem is unavailable + */ + public McpUnavailableException(final String message) { + super(message); + } } diff --git a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpActorLabelTest.java b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpActorLabelTest.java index f01d637..4bff2f1 100644 --- a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpActorLabelTest.java +++ b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpActorLabelTest.java @@ -1,35 +1,34 @@ package com.openelements.spring.base.mcp; -import io.modelcontextprotocol.common.McpTransportContext; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import io.modelcontextprotocol.common.McpTransportContext; import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** - * Unit tests for {@link McpActorLabel} transport-context label resolution. - * Lives in the same package so it can exercise the package-private - * helper directly. + * Unit tests for {@link McpActorLabel} transport-context label resolution. Lives in the same + * package so it can exercise the package-private helper directly. */ class McpActorLabelTest { - @Test - void returnsLabelStoredUnderTheActorKey() { - final McpTransportContext context = McpTransportContext.create( - Map.of(McpActorLabel.ACTOR_LABEL_KEY, "apikey:onyx")); - - assertEquals("apikey:onyx", McpActorLabel.from(context)); - } - - @Test - void fallsBackToUnknownForNullContext() { - assertEquals("unknown", McpActorLabel.from(null)); - } - - @Test - void fallsBackToUnknownWhenLabelIsAbsent() { - assertEquals("unknown", McpActorLabel.from(McpTransportContext.EMPTY)); - assertEquals("unknown", McpActorLabel.from(McpTransportContext.create(Map.of("other", "value")))); - } + @Test + void returnsLabelStoredUnderTheActorKey() { + final McpTransportContext context = + McpTransportContext.create(Map.of(McpActorLabel.ACTOR_LABEL_KEY, "apikey:onyx")); + + assertEquals("apikey:onyx", McpActorLabel.from(context)); + } + + @Test + void fallsBackToUnknownForNullContext() { + assertEquals("unknown", McpActorLabel.from(null)); + } + + @Test + void fallsBackToUnknownWhenLabelIsAbsent() { + assertEquals("unknown", McpActorLabel.from(McpTransportContext.EMPTY)); + assertEquals( + "unknown", McpActorLabel.from(McpTransportContext.create(Map.of("other", "value")))); + } } diff --git a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpAutoConfigurationTest.java b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpAutoConfigurationTest.java index dff1f7b..e5f7fe6 100644 --- a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpAutoConfigurationTest.java +++ b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpAutoConfigurationTest.java @@ -19,8 +19,8 @@ /** * Activation-guard test for {@link McpAutoConfiguration}: proves the {@code @ConditionalOnClass} - * guard keeps the feature inert when the MCP SDK is not on the classpath, so a bundle that ships the - * auto-configuration class without the SDK causes no failure. + * guard keeps the feature inert when the MCP SDK is not on the classpath, so a bundle that ships + * the auto-configuration class without the SDK causes no failure. */ @DisplayName("McpAutoConfiguration — activation guard") class McpAutoConfigurationTest { @@ -48,14 +48,14 @@ void inertWhenNotEnabled() { contextRunner .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(McpSyncServer.class) - .doesNotHaveBean(WebMvcStreamableServerTransportProvider.class) - .doesNotHaveBean(McpServerConfig.class) - .doesNotHaveBean(McpSecurityConfig.class) - .doesNotHaveBean("mcpApiKeyFilterChain")); + context -> + assertThat(context) + .hasNotFailed() + .doesNotHaveBean(McpSyncServer.class) + .doesNotHaveBean(WebMvcStreamableServerTransportProvider.class) + .doesNotHaveBean(McpServerConfig.class) + .doesNotHaveBean(McpSecurityConfig.class) + .doesNotHaveBean("mcpApiKeyFilterChain")); } @Test diff --git a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpPagingTest.java b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpPagingTest.java index b5739e7..7df043a 100644 --- a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpPagingTest.java +++ b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpPagingTest.java @@ -1,71 +1,70 @@ package com.openelements.spring.base.mcp; +import static org.junit.jupiter.api.Assertions.*; + import com.openelements.spring.base.mcp.McpProperties.Auth; import com.openelements.spring.base.mcp.McpProperties.Auth.ApiKey; import com.openelements.spring.base.mcp.McpProperties.Auth.Oidc; +import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; - /** - * Unit tests for {@link McpPaging} clamping and {@link McpPage} envelope mapping. - * No Spring context / database required. + * Unit tests for {@link McpPaging} clamping and {@link McpPage} envelope mapping. No Spring context + * / database required. */ class McpPagingTest { - private static final McpProperties PROPS = new McpProperties( - true, "Open CRM", "0.1.0", 50, 20, - new Auth(new ApiKey(true), new Oidc(false))); + private static final McpProperties PROPS = + new McpProperties( + true, "Open CRM", "0.1.0", 50, 20, new Auth(new ApiKey(true), new Oidc(false))); - private final McpPaging paging = new McpPaging(PROPS); + private final McpPaging paging = new McpPaging(PROPS); - @Test - void resolveSizeAppliesDefaultClampAndRejectsNonPositive() { - assertEquals(20, paging.resolveSize(null), "default size"); - assertEquals(5, paging.resolveSize(5), "in-range size kept"); - assertEquals(50, paging.resolveSize(200), "clamped to max"); - assertEquals(50, paging.resolveSize(51), "just over max clamps"); - assertThrows(IllegalArgumentException.class, () -> paging.resolveSize(0)); - assertThrows(IllegalArgumentException.class, () -> paging.resolveSize(-5)); - } + @Test + void resolveSizeAppliesDefaultClampAndRejectsNonPositive() { + assertEquals(20, paging.resolveSize(null), "default size"); + assertEquals(5, paging.resolveSize(5), "in-range size kept"); + assertEquals(50, paging.resolveSize(200), "clamped to max"); + assertEquals(50, paging.resolveSize(51), "just over max clamps"); + assertThrows(IllegalArgumentException.class, () -> paging.resolveSize(0)); + assertThrows(IllegalArgumentException.class, () -> paging.resolveSize(-5)); + } - @Test - void resolvePageDefaultsToZeroAndRejectsNegative() { - assertEquals(0, paging.resolvePage(null)); - assertEquals(3, paging.resolvePage(3)); - assertThrows(IllegalArgumentException.class, () -> paging.resolvePage(-1)); - } + @Test + void resolvePageDefaultsToZeroAndRejectsNegative() { + assertEquals(0, paging.resolvePage(null)); + assertEquals(3, paging.resolvePage(3)); + assertThrows(IllegalArgumentException.class, () -> paging.resolvePage(-1)); + } - @Test - void toPageableUsesResolvedValues() { - final var pageable = paging.toPageable(2, 100, org.springframework.data.domain.Sort.by("name")); - assertEquals(2, pageable.getPageNumber()); - assertEquals(50, pageable.getPageSize()); - assertEquals(org.springframework.data.domain.Sort.by("name"), pageable.getSort()); - } + @Test + void toPageableUsesResolvedValues() { + final var pageable = paging.toPageable(2, 100, org.springframework.data.domain.Sort.by("name")); + assertEquals(2, pageable.getPageNumber()); + assertEquals(50, pageable.getPageSize()); + assertEquals(org.springframework.data.domain.Sort.by("name"), pageable.getSort()); + } - @Test - void envelopeSignalsMoreOnNonLastPage() { - final McpPage page = McpPage.from( - new PageImpl<>(List.of("a", "b"), PageRequest.of(0, 2), 5)); + @Test + void envelopeSignalsMoreOnNonLastPage() { + final McpPage page = + McpPage.from(new PageImpl<>(List.of("a", "b"), PageRequest.of(0, 2), 5)); - assertEquals(2, page.items().size()); - assertEquals(0, page.page()); - assertEquals(2, page.size()); - assertEquals(5, page.totalCount()); - assertTrue(page.hasMore(), "first of three pages has more"); - } + assertEquals(2, page.items().size()); + assertEquals(0, page.page()); + assertEquals(2, page.size()); + assertEquals(5, page.totalCount()); + assertTrue(page.hasMore(), "first of three pages has more"); + } - @Test - void envelopeSignalsNoMoreOnLastPage() { - final McpPage page = McpPage.from( - new PageImpl<>(List.of("e"), PageRequest.of(2, 2), 5)); + @Test + void envelopeSignalsNoMoreOnLastPage() { + final McpPage page = + McpPage.from(new PageImpl<>(List.of("e"), PageRequest.of(2, 2), 5)); - assertEquals(5, page.totalCount()); - assertFalse(page.hasMore(), "last page has no more"); - } + assertEquals(5, page.totalCount()); + assertFalse(page.hasMore(), "last page has no more"); + } } diff --git a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpPropertiesTest.java b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpPropertiesTest.java index acb6d22..8f5fc5a 100644 --- a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpPropertiesTest.java +++ b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpPropertiesTest.java @@ -1,57 +1,56 @@ package com.openelements.spring.base.mcp; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; import org.springframework.mock.env.MockEnvironment; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.*; - /** - * Binding tests for {@link McpProperties}. Uses the Spring Boot {@link Binder} - * directly (no application context, no database) so the test is fast and - * deterministic. + * Binding tests for {@link McpProperties}. Uses the Spring Boot {@link Binder} directly (no + * application context, no database) so the test is fast and deterministic. */ class McpPropertiesTest { - private static McpProperties bind(final Map properties) { - final MockEnvironment environment = new MockEnvironment(); - properties.forEach(environment::setProperty); - return new Binder(ConfigurationPropertySources.get(environment)) - .bindOrCreate("openelements.mcp", McpProperties.class); - } - - @Test - void defaultsAreSafeWhenNothingIsConfigured() { - final McpProperties props = bind(Map.of()); - - assertFalse(props.enabled(), "MCP must be off by default"); - assertEquals("MCP Server", props.serverName()); - assertEquals("0.0.0", props.serverVersion()); - assertEquals(20, props.defaultPageSize()); - assertEquals(50, props.maxPageSize()); - assertTrue(props.auth().apiKey().enabled(), "API-key profile defaults on"); - assertFalse(props.auth().oidc().enabled(), "OIDC profile defaults off"); - } - - @Test - void valuesBindFromConfiguration() { - final McpProperties props = bind(Map.of( + private static McpProperties bind(final Map properties) { + final MockEnvironment environment = new MockEnvironment(); + properties.forEach(environment::setProperty); + return new Binder(ConfigurationPropertySources.get(environment)) + .bindOrCreate("openelements.mcp", McpProperties.class); + } + + @Test + void defaultsAreSafeWhenNothingIsConfigured() { + final McpProperties props = bind(Map.of()); + + assertFalse(props.enabled(), "MCP must be off by default"); + assertEquals("MCP Server", props.serverName()); + assertEquals("0.0.0", props.serverVersion()); + assertEquals(20, props.defaultPageSize()); + assertEquals(50, props.maxPageSize()); + assertTrue(props.auth().apiKey().enabled(), "API-key profile defaults on"); + assertFalse(props.auth().oidc().enabled(), "OIDC profile defaults off"); + } + + @Test + void valuesBindFromConfiguration() { + final McpProperties props = + bind( + Map.of( "openelements.mcp.enabled", "true", "openelements.mcp.server-name", "MCP Test", "openelements.mcp.default-page-size", "10", "openelements.mcp.max-page-size", "30", "openelements.mcp.auth.api-key.enabled", "false", - "openelements.mcp.auth.oidc.enabled", "true" - )); - - assertTrue(props.enabled()); - assertEquals("MCP Test", props.serverName()); - assertEquals(10, props.defaultPageSize()); - assertEquals(30, props.maxPageSize()); - assertFalse(props.auth().apiKey().enabled()); - assertTrue(props.auth().oidc().enabled()); - } + "openelements.mcp.auth.oidc.enabled", "true")); + + assertTrue(props.enabled()); + assertEquals("MCP Test", props.serverName()); + assertEquals(10, props.defaultPageSize()); + assertEquals(30, props.maxPageSize()); + assertFalse(props.auth().apiKey().enabled()); + assertTrue(props.auth().oidc().enabled()); + } } diff --git a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpSecurityChainWebTest.java b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpSecurityChainWebTest.java index 2123b4f..38fac92 100644 --- a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpSecurityChainWebTest.java +++ b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpSecurityChainWebTest.java @@ -36,18 +36,18 @@ * *

          What is tested

          * - *

          That {@code /mcp} answers an unauthenticated request with the same RFC 9457 problem as the rest - * of the platform (spec 024). The MCP chain injects the shared {@code apiKeyAuthenticationEntryPoint} - * bean by qualifier, so this is really a test that the wiring still resolves to the problem entry - * point after spec 024 changed that bean's type from {@code JsonAuthenticationEntryPoint} to - * {@code AuthenticationEntryPoint} — a change that compiles either way and would otherwise only show - * up as an MCP client receiving a body it does not recognise. + *

          That {@code /mcp} answers an unauthenticated request with the same RFC 9457 problem as the + * rest of the platform (spec 024). The MCP chain injects the shared {@code + * apiKeyAuthenticationEntryPoint} bean by qualifier, so this is really a test that the wiring still + * resolves to the problem entry point after spec 024 changed that bean's type from {@code + * JsonAuthenticationEntryPoint} to {@code AuthenticationEntryPoint} — a change that compiles either + * way and would otherwise only show up as an MCP client receiving a body it does not recognise. * *

          How it is tested

          * - *

          A {@link WebApplicationContextRunner} with the library's {@link SecurityConfig} beans that this - * chain depends on, plus the problem-details and trace auto-configurations. The request never reaches - * a handler, so no MCP server is needed. + *

          A {@link WebApplicationContextRunner} with the library's {@link SecurityConfig} beans that + * this chain depends on, plus the problem-details and trace auto-configurations. The request never + * reaches a handler, so no MCP server is needed. * *

          Mock-Audit. One mock: {@link ApiKeyDataService}, which would otherwise pull in a JPA * repository and a datasource. It is stubbed to find no key, which is exactly the path under test — @@ -67,7 +67,8 @@ class McpSecurityChainWebTest { TraceAutoConfiguration.class, JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - SecurityAutoConfiguration.class, ServletWebSecurityAutoConfiguration.class, + SecurityAutoConfiguration.class, + ServletWebSecurityAutoConfiguration.class, WebMvcAutoConfiguration.class)) .withUserConfiguration(EntryPoints.class, McpSecurityConfig.class) .withPropertyValues("openelements.mcp.enabled=true"); diff --git a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpToolSupportTest.java b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpToolSupportTest.java index d459aca..2708cac 100644 --- a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpToolSupportTest.java +++ b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpToolSupportTest.java @@ -1,7 +1,9 @@ package com.openelements.spring.base.mcp; -import tools.jackson.databind.ObjectMapper; -import tools.jackson.databind.json.JsonMapper; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.openelements.spring.base.mcp.McpProperties.Auth; import com.openelements.spring.base.mcp.McpProperties.Auth.ApiKey; import com.openelements.spring.base.mcp.McpProperties.Auth.Oidc; @@ -11,183 +13,201 @@ import io.modelcontextprotocol.spec.McpSchema; import io.modelcontextprotocol.spec.McpSchema.CallToolResult; import io.modelcontextprotocol.spec.McpSchema.TextContent; -import org.junit.jupiter.api.Test; - import java.util.List; import java.util.Map; import java.util.NoSuchElementException; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** - * Unit tests for {@link McpToolSupport}: tool-call dispatch with structured access - * logging, JSON serialization, JSON-RPC error mapping, and in-memory pagination. - * The {@link McpSyncServerExchange} is mocked; no Spring context or - * database is required. + * Unit tests for {@link McpToolSupport}: tool-call dispatch with structured access logging, JSON + * serialization, JSON-RPC error mapping, and in-memory pagination. The {@link + * McpSyncServerExchange} is mocked; no Spring context or database is required. */ class McpToolSupportTest { - private static final McpSchema.Tool TOOL = - McpTools.tool("demo", "Demo tool.", Map.of(), List.of()); - - private final ObjectMapper objectMapper = new JsonMapper(); - private final McpPaging paging = new McpPaging(new McpProperties( - true, "Open CRM", "0.1.0", 50, 20, new Auth(new ApiKey(true), new Oidc(false)))); - private final McpToolSupport support = new McpToolSupport(paging, objectMapper); - - private static String text(final CallToolResult result) { - return ((TextContent) result.content().get(0)).text(); - } - - private CallToolResult call(final McpToolLogic logic, final Map args) { - final McpSyncServerExchange exchange = mock(McpSyncServerExchange.class); - when(exchange.transportContext()).thenReturn( - McpTransportContext.create(Map.of(McpActorLabel.ACTOR_LABEL_KEY, "apikey:test"))); - final SyncToolSpecification spec = support.spec(TOOL, logic); - return spec.callHandler().apply(exchange, new McpSchema.CallToolRequest(TOOL.name(), args)); - } - - // -- spec(): success ----------------------------------------------------- - - @Test - void specCarriesTheGivenTool() { - final SyncToolSpecification spec = support.spec(TOOL, args -> "ok"); - assertEquals("demo", spec.tool().name()); - } - - @Test - void successResultIsSerializedJsonAndNotAnError() throws Exception { - final Map payload = Map.of("a", 1, "b", "two"); - - final CallToolResult result = call(args -> payload, Map.of()); - - assertFalse(result.isError(), "successful call must not be an error result"); - assertEquals(objectMapper.writeValueAsString(payload), text(result)); - } - - @Test - void nullArgumentsArePassedToLogicAsEmptyMap() { - final CallToolResult result = call(args -> { - assertNotNull(args, "logic must never receive null args"); - return args.size(); - }, null); - - assertFalse(result.isError()); - assertEquals("0", text(result)); - } - - @Test - void missingActorLabelDoesNotBreakDispatch() { - final McpSyncServerExchange exchange = mock(McpSyncServerExchange.class); - when(exchange.transportContext()).thenReturn(McpTransportContext.EMPTY); - - final CallToolResult result = support.spec(TOOL, args -> "ok") - .callHandler() - .apply(exchange, new McpSchema.CallToolRequest(TOOL.name(), Map.of())); - - assertFalse(result.isError()); - assertEquals("\"ok\"", text(result)); - } - - // -- spec(): error mapping ---------------------------------------------- - - @Test - void illegalArgumentBecomesInvalidArgumentError() { - final CallToolResult result = call(args -> { - throw new IllegalArgumentException("id is required"); - }, Map.of()); - - assertTrue(result.isError()); - assertEquals("Invalid argument: id is required", text(result)); - } - - @Test - void noSuchElementBecomesNotFoundErrorWithMessage() { - final CallToolResult result = call(args -> { - throw new NoSuchElementException("Company not found: 42"); - }, Map.of()); - - assertTrue(result.isError()); - assertEquals("Company not found: 42", text(result)); - } - - @Test - void unavailableExceptionBecomesUnavailableErrorWithMessage() { - final CallToolResult result = call(args -> { - throw new McpUnavailableException("Search index is initializing; retry shortly."); - }, Map.of()); - - assertTrue(result.isError()); - assertEquals("Search index is initializing; retry shortly.", text(result)); - } - - @Test - void unexpectedExceptionBecomesGenericInternalErrorWithoutLeakingDetails() { - final CallToolResult result = call(args -> { - throw new IllegalStateException("connection pool exhausted at jdbc://secret"); - }, Map.of()); - - assertTrue(result.isError()); - assertEquals("Internal error executing tool demo", text(result), - "internal errors must not leak the underlying message"); - } - - @Test - void payloadThatCannotBeSerializedBecomesGenericInternalError() { - // Jackson 3 reports this as the unchecked JacksonException (Jackson 2: checked - // JsonProcessingException); the client must see the same generic error either way. - final CallToolResult result = call(args -> new Unserializable(), Map.of()); - - assertTrue(result.isError()); - assertEquals("Internal error executing tool demo", text(result)); - } - - /** A payload whose only property fails while being serialized. */ - private static final class Unserializable { - public String getValue() { - throw new IllegalStateException("cannot be read"); - } - } - - // -- paginate() ---------------------------------------------------------- - - @Test - void paginateFirstPageSignalsMore() { - final McpPage page = support.paginate(List.of(0, 1, 2, 3, 4), 0, 2); - - assertEquals(List.of(0, 1), page.items()); - assertEquals(0, page.page()); - assertEquals(2, page.size()); - assertEquals(5, page.totalCount()); - assertTrue(page.hasMore()); - } - - @Test - void paginateLastPageSignalsNoMore() { - final McpPage page = support.paginate(List.of(0, 1, 2, 3, 4), 2, 2); - - assertEquals(List.of(4), page.items()); - assertFalse(page.hasMore()); - assertEquals(5, page.totalCount()); - } - - @Test - void paginateBeyondRangeReturnsEmptyPage() { - final McpPage page = support.paginate(List.of(0, 1, 2, 3, 4), 10, 2); - - assertTrue(page.items().isEmpty()); - assertFalse(page.hasMore()); - assertEquals(5, page.totalCount()); - } - - @Test - void paginateAppliesDefaultSizeWhenSizeOmitted() { - final McpPage page = support.paginate(List.of(0, 1, 2, 3, 4), null, null); - - assertEquals(5, page.items().size(), "default size (20) covers all 5 items"); - assertEquals(20, page.size()); - assertFalse(page.hasMore()); - } + private static final McpSchema.Tool TOOL = + McpTools.tool("demo", "Demo tool.", Map.of(), List.of()); + + private final ObjectMapper objectMapper = new JsonMapper(); + private final McpPaging paging = + new McpPaging( + new McpProperties( + true, "Open CRM", "0.1.0", 50, 20, new Auth(new ApiKey(true), new Oidc(false)))); + private final McpToolSupport support = new McpToolSupport(paging, objectMapper); + + private static String text(final CallToolResult result) { + return ((TextContent) result.content().get(0)).text(); + } + + private CallToolResult call(final McpToolLogic logic, final Map args) { + final McpSyncServerExchange exchange = mock(McpSyncServerExchange.class); + when(exchange.transportContext()) + .thenReturn( + McpTransportContext.create(Map.of(McpActorLabel.ACTOR_LABEL_KEY, "apikey:test"))); + final SyncToolSpecification spec = support.spec(TOOL, logic); + return spec.callHandler().apply(exchange, new McpSchema.CallToolRequest(TOOL.name(), args)); + } + + // -- spec(): success ----------------------------------------------------- + + @Test + void specCarriesTheGivenTool() { + final SyncToolSpecification spec = support.spec(TOOL, args -> "ok"); + assertEquals("demo", spec.tool().name()); + } + + @Test + void successResultIsSerializedJsonAndNotAnError() throws Exception { + final Map payload = Map.of("a", 1, "b", "two"); + + final CallToolResult result = call(args -> payload, Map.of()); + + assertFalse(result.isError(), "successful call must not be an error result"); + assertEquals(objectMapper.writeValueAsString(payload), text(result)); + } + + @Test + void nullArgumentsArePassedToLogicAsEmptyMap() { + final CallToolResult result = + call( + args -> { + assertNotNull(args, "logic must never receive null args"); + return args.size(); + }, + null); + + assertFalse(result.isError()); + assertEquals("0", text(result)); + } + + @Test + void missingActorLabelDoesNotBreakDispatch() { + final McpSyncServerExchange exchange = mock(McpSyncServerExchange.class); + when(exchange.transportContext()).thenReturn(McpTransportContext.EMPTY); + + final CallToolResult result = + support + .spec(TOOL, args -> "ok") + .callHandler() + .apply(exchange, new McpSchema.CallToolRequest(TOOL.name(), Map.of())); + + assertFalse(result.isError()); + assertEquals("\"ok\"", text(result)); + } + + // -- spec(): error mapping ---------------------------------------------- + + @Test + void illegalArgumentBecomesInvalidArgumentError() { + final CallToolResult result = + call( + args -> { + throw new IllegalArgumentException("id is required"); + }, + Map.of()); + + assertTrue(result.isError()); + assertEquals("Invalid argument: id is required", text(result)); + } + + @Test + void noSuchElementBecomesNotFoundErrorWithMessage() { + final CallToolResult result = + call( + args -> { + throw new NoSuchElementException("Company not found: 42"); + }, + Map.of()); + + assertTrue(result.isError()); + assertEquals("Company not found: 42", text(result)); + } + + @Test + void unavailableExceptionBecomesUnavailableErrorWithMessage() { + final CallToolResult result = + call( + args -> { + throw new McpUnavailableException("Search index is initializing; retry shortly."); + }, + Map.of()); + + assertTrue(result.isError()); + assertEquals("Search index is initializing; retry shortly.", text(result)); + } + + @Test + void unexpectedExceptionBecomesGenericInternalErrorWithoutLeakingDetails() { + final CallToolResult result = + call( + args -> { + throw new IllegalStateException("connection pool exhausted at jdbc://secret"); + }, + Map.of()); + + assertTrue(result.isError()); + assertEquals( + "Internal error executing tool demo", + text(result), + "internal errors must not leak the underlying message"); + } + + @Test + void payloadThatCannotBeSerializedBecomesGenericInternalError() { + // Jackson 3 reports this as the unchecked JacksonException (Jackson 2: checked + // JsonProcessingException); the client must see the same generic error either way. + final CallToolResult result = call(args -> new Unserializable(), Map.of()); + + assertTrue(result.isError()); + assertEquals("Internal error executing tool demo", text(result)); + } + + /** A payload whose only property fails while being serialized. */ + private static final class Unserializable { + public String getValue() { + throw new IllegalStateException("cannot be read"); + } + } + + // -- paginate() ---------------------------------------------------------- + + @Test + void paginateFirstPageSignalsMore() { + final McpPage page = support.paginate(List.of(0, 1, 2, 3, 4), 0, 2); + + assertEquals(List.of(0, 1), page.items()); + assertEquals(0, page.page()); + assertEquals(2, page.size()); + assertEquals(5, page.totalCount()); + assertTrue(page.hasMore()); + } + + @Test + void paginateLastPageSignalsNoMore() { + final McpPage page = support.paginate(List.of(0, 1, 2, 3, 4), 2, 2); + + assertEquals(List.of(4), page.items()); + assertFalse(page.hasMore()); + assertEquals(5, page.totalCount()); + } + + @Test + void paginateBeyondRangeReturnsEmptyPage() { + final McpPage page = support.paginate(List.of(0, 1, 2, 3, 4), 10, 2); + + assertTrue(page.items().isEmpty()); + assertFalse(page.hasMore()); + assertEquals(5, page.totalCount()); + } + + @Test + void paginateAppliesDefaultSizeWhenSizeOmitted() { + final McpPage page = support.paginate(List.of(0, 1, 2, 3, 4), null, null); + + assertEquals(5, page.items().size(), "default size (20) covers all 5 items"); + assertEquals(20, page.size()); + assertFalse(page.hasMore()); + } } diff --git a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpToolsTest.java b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpToolsTest.java index 14befb4..2e927df 100644 --- a/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpToolsTest.java +++ b/spring-services-mcp/src/test/java/com/openelements/spring/base/mcp/McpToolsTest.java @@ -1,150 +1,157 @@ package com.openelements.spring.base.mcp; -import io.modelcontextprotocol.spec.McpSchema; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import io.modelcontextprotocol.spec.McpSchema; import java.util.List; import java.util.Map; import java.util.UUID; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** - * Unit tests for the domain-agnostic schema builders and argument accessors in - * {@link McpTools}. No Spring context required. + * Unit tests for the domain-agnostic schema builders and argument accessors in {@link McpTools}. No + * Spring context required. */ class McpToolsTest { - private static final String VALID_UUID = "11111111-1111-1111-1111-111111111111"; - - // -- Schema builders ----------------------------------------------------- - - @Test - void toolBuildsObjectSchemaWithPropertiesAndRequired() { - final McpSchema.Tool tool = McpTools.tool( - "do_thing", "Does a thing.", - Map.of("id", McpTools.uuidProp("the id")), - List.of("id")); - - assertEquals("do_thing", tool.name()); - assertEquals("Does a thing.", tool.description()); - - // MCP SDK 2.x exposes the input schema as the JSON object it is sent as - final Map schema = tool.inputSchema(); - assertEquals("object", schema.get("type")); - assertTrue(((Map) schema.get("properties")).containsKey("id")); - assertIterableEquals(List.of("id"), (List) schema.get("required")); - assertEquals(Boolean.FALSE, schema.get("additionalProperties"), - "additionalProperties must be locked to false"); - } - - @Test - void paginationPropsExposesPageAndSizeAndIsMutable() { - final Map props = McpTools.paginationProps(); - - assertTrue(props.containsKey("page")); - assertTrue(props.containsKey("size")); - // callers add their own filters on top, so the map must be mutable - props.put("name", McpTools.prop("string", "filter")); - assertEquals(3, props.size()); - } - - @Test - void propBuildsTypeAndDescription() { - assertEquals(Map.of("type", "integer", "description", "count"), - McpTools.prop("integer", "count")); - } - - @Test - void uuidPropAndUuidArrayCarryUuidFormat() { - final Map single = McpTools.uuidProp("the id"); - assertEquals("string", single.get("type")); - assertEquals("uuid", single.get("format")); - - final Map array = McpTools.uuidArray("the ids"); - assertEquals("array", array.get("type")); - assertEquals(Map.of("type", "string", "format", "uuid"), array.get("items")); - } - - // -- String arguments ---------------------------------------------------- - - @Test - void stringReturnsValueOrNullAndCoercesNonStrings() { - assertEquals("hello", McpTools.string(Map.of("q", "hello"), "q")); - assertNull(McpTools.string(Map.of(), "q")); - assertEquals("42", McpTools.string(Map.of("q", 42), "q")); - } - - @Test - void requiredStringRejectsMissingAndBlank() { - assertEquals("x", McpTools.requiredString(Map.of("q", "x"), "q")); - assertThrows(IllegalArgumentException.class, () -> McpTools.requiredString(Map.of(), "q")); - assertThrows(IllegalArgumentException.class, () -> McpTools.requiredString(Map.of("q", " "), "q")); - } - - // -- Integer arguments --------------------------------------------------- - - @Test - void integerAcceptsNumbersAndNumericStrings() { - assertEquals(5, McpTools.integer(Map.of("n", 5), "n")); - assertEquals(7, McpTools.integer(Map.of("n", "7"), "n")); - assertEquals(3, McpTools.integer(Map.of("n", " 3 "), "n"), "surrounding whitespace is trimmed"); - } - - @Test - void integerReturnsNullWhenAbsentAndRejectsNonNumeric() { - assertNull(McpTools.integer(Map.of(), "n")); - assertThrows(IllegalArgumentException.class, () -> McpTools.integer(Map.of("n", "abc"), "n")); - } - - // -- Boolean arguments --------------------------------------------------- - - @Test - void boolAcceptsBooleanAndStringAndNull() { - assertTrue(McpTools.bool(Map.of("b", true), "b")); - assertTrue(McpTools.bool(Map.of("b", "true"), "b")); - assertFalse(McpTools.bool(Map.of("b", "false"), "b")); - assertNull(McpTools.bool(Map.of(), "b")); - } - - @Test - void boolTreatsNonBooleanTextAsFalse() { - assertFalse(McpTools.bool(Map.of("b", "yes"), "b"), - "Boolean.valueOf maps anything but \"true\" to false"); - } - - // -- UUID arguments ------------------------------------------------------ - - @Test - void uuidParsesValidValueAndNullsBlank() { - assertEquals(UUID.fromString(VALID_UUID), McpTools.uuid(Map.of("id", VALID_UUID), "id")); - assertNull(McpTools.uuid(Map.of(), "id")); - assertNull(McpTools.uuid(Map.of("id", " "), "id")); - } - - @Test - void uuidRejectsMalformedValue() { - assertThrows(IllegalArgumentException.class, () -> McpTools.uuid(Map.of("id", "not-a-uuid"), "id")); - } - - @Test - void requiredUuidRejectsMissing() { - assertEquals(UUID.fromString(VALID_UUID), McpTools.requiredUuid(Map.of("id", VALID_UUID), "id")); - assertThrows(IllegalArgumentException.class, () -> McpTools.requiredUuid(Map.of(), "id")); - } - - @Test - void uuidListParsesElementsAndNullsAbsent() { - final String other = "22222222-2222-2222-2222-222222222222"; - assertEquals(List.of(UUID.fromString(VALID_UUID), UUID.fromString(other)), - McpTools.uuidList(Map.of("ids", List.of(VALID_UUID, other)), "ids")); - assertNull(McpTools.uuidList(Map.of(), "ids")); - } - - @Test - void uuidListRejectsNonListAndMalformedElements() { - assertThrows(IllegalArgumentException.class, () -> McpTools.uuidList(Map.of("ids", VALID_UUID), "ids")); - assertThrows(IllegalArgumentException.class, - () -> McpTools.uuidList(Map.of("ids", List.of("nope")), "ids")); - } + private static final String VALID_UUID = "11111111-1111-1111-1111-111111111111"; + + // -- Schema builders ----------------------------------------------------- + + @Test + void toolBuildsObjectSchemaWithPropertiesAndRequired() { + final McpSchema.Tool tool = + McpTools.tool( + "do_thing", "Does a thing.", Map.of("id", McpTools.uuidProp("the id")), List.of("id")); + + assertEquals("do_thing", tool.name()); + assertEquals("Does a thing.", tool.description()); + + // MCP SDK 2.x exposes the input schema as the JSON object it is sent as + final Map schema = tool.inputSchema(); + assertEquals("object", schema.get("type")); + assertTrue(((Map) schema.get("properties")).containsKey("id")); + assertIterableEquals(List.of("id"), (List) schema.get("required")); + assertEquals( + Boolean.FALSE, + schema.get("additionalProperties"), + "additionalProperties must be locked to false"); + } + + @Test + void paginationPropsExposesPageAndSizeAndIsMutable() { + final Map props = McpTools.paginationProps(); + + assertTrue(props.containsKey("page")); + assertTrue(props.containsKey("size")); + // callers add their own filters on top, so the map must be mutable + props.put("name", McpTools.prop("string", "filter")); + assertEquals(3, props.size()); + } + + @Test + void propBuildsTypeAndDescription() { + assertEquals( + Map.of("type", "integer", "description", "count"), McpTools.prop("integer", "count")); + } + + @Test + void uuidPropAndUuidArrayCarryUuidFormat() { + final Map single = McpTools.uuidProp("the id"); + assertEquals("string", single.get("type")); + assertEquals("uuid", single.get("format")); + + final Map array = McpTools.uuidArray("the ids"); + assertEquals("array", array.get("type")); + assertEquals(Map.of("type", "string", "format", "uuid"), array.get("items")); + } + + // -- String arguments ---------------------------------------------------- + + @Test + void stringReturnsValueOrNullAndCoercesNonStrings() { + assertEquals("hello", McpTools.string(Map.of("q", "hello"), "q")); + assertNull(McpTools.string(Map.of(), "q")); + assertEquals("42", McpTools.string(Map.of("q", 42), "q")); + } + + @Test + void requiredStringRejectsMissingAndBlank() { + assertEquals("x", McpTools.requiredString(Map.of("q", "x"), "q")); + assertThrows(IllegalArgumentException.class, () -> McpTools.requiredString(Map.of(), "q")); + assertThrows( + IllegalArgumentException.class, () -> McpTools.requiredString(Map.of("q", " "), "q")); + } + + // -- Integer arguments --------------------------------------------------- + + @Test + void integerAcceptsNumbersAndNumericStrings() { + assertEquals(5, McpTools.integer(Map.of("n", 5), "n")); + assertEquals(7, McpTools.integer(Map.of("n", "7"), "n")); + assertEquals(3, McpTools.integer(Map.of("n", " 3 "), "n"), "surrounding whitespace is trimmed"); + } + + @Test + void integerReturnsNullWhenAbsentAndRejectsNonNumeric() { + assertNull(McpTools.integer(Map.of(), "n")); + assertThrows(IllegalArgumentException.class, () -> McpTools.integer(Map.of("n", "abc"), "n")); + } + + // -- Boolean arguments --------------------------------------------------- + + @Test + void boolAcceptsBooleanAndStringAndNull() { + assertTrue(McpTools.bool(Map.of("b", true), "b")); + assertTrue(McpTools.bool(Map.of("b", "true"), "b")); + assertFalse(McpTools.bool(Map.of("b", "false"), "b")); + assertNull(McpTools.bool(Map.of(), "b")); + } + + @Test + void boolTreatsNonBooleanTextAsFalse() { + assertFalse( + McpTools.bool(Map.of("b", "yes"), "b"), + "Boolean.valueOf maps anything but \"true\" to false"); + } + + // -- UUID arguments ------------------------------------------------------ + + @Test + void uuidParsesValidValueAndNullsBlank() { + assertEquals(UUID.fromString(VALID_UUID), McpTools.uuid(Map.of("id", VALID_UUID), "id")); + assertNull(McpTools.uuid(Map.of(), "id")); + assertNull(McpTools.uuid(Map.of("id", " "), "id")); + } + + @Test + void uuidRejectsMalformedValue() { + assertThrows( + IllegalArgumentException.class, () -> McpTools.uuid(Map.of("id", "not-a-uuid"), "id")); + } + + @Test + void requiredUuidRejectsMissing() { + assertEquals( + UUID.fromString(VALID_UUID), McpTools.requiredUuid(Map.of("id", VALID_UUID), "id")); + assertThrows(IllegalArgumentException.class, () -> McpTools.requiredUuid(Map.of(), "id")); + } + + @Test + void uuidListParsesElementsAndNullsAbsent() { + final String other = "22222222-2222-2222-2222-222222222222"; + assertEquals( + List.of(UUID.fromString(VALID_UUID), UUID.fromString(other)), + McpTools.uuidList(Map.of("ids", List.of(VALID_UUID, other)), "ids")); + assertNull(McpTools.uuidList(Map.of(), "ids")); + } + + @Test + void uuidListRejectsNonListAndMalformedElements() { + assertThrows( + IllegalArgumentException.class, () -> McpTools.uuidList(Map.of("ids", VALID_UUID), "ids")); + assertThrows( + IllegalArgumentException.class, + () -> McpTools.uuidList(Map.of("ids", List.of("nope")), "ids")); + } } diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/scim/ScimAutoConfiguration.java b/spring-services-scim/src/main/java/com/openelements/spring/base/scim/ScimAutoConfiguration.java index aeef1e3..5cabaa3 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/scim/ScimAutoConfiguration.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/scim/ScimAutoConfiguration.java @@ -8,12 +8,12 @@ /** * Auto-configuration for the optional SCIM 2.0 Users provider. * - *

          Registered through this module's - * {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}. Unlike - * the other feature modules it is gated on a property rather than a class: - * {@link ConditionalOnProperty @ConditionalOnProperty(openelements.scim.token)} keeps the entire - * feature — the isolated {@code /scim/v2/**} security chain, controllers and beans — inert unless a - * static SCIM token is configured, so a consumer that does not use SCIM ships nothing extra. + *

          Registered through this module's {@code + * META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}. Unlike the + * other feature modules it is gated on a property rather than a class: {@link + * ConditionalOnProperty @ConditionalOnProperty(openelements.scim.token)} keeps the entire feature — + * the isolated {@code /scim/v2/**} security chain, controllers and beans — inert unless a static + * SCIM token is configured, so a consumer that does not use SCIM ships nothing extra. * *

          Lives outside the {@code services.scim} package on purpose: {@link ScimConfig} declares a * {@code @ComponentScan} over its own package, and an auto-configuration co-located there would be diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimAuthenticationEntryPoint.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimAuthenticationEntryPoint.java index 6e09b71..a5dad16 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimAuthenticationEntryPoint.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimAuthenticationEntryPoint.java @@ -13,10 +13,10 @@ import tools.jackson.databind.ObjectMapper; /** - * SCIM-shaped authentication entry point: renders a {@code 401 Unauthorized} with an - * {@code application/scim+json} {@link ScimError} envelope and a {@code WWW-Authenticate: Bearer} - * header when a {@code /scim/v2/**} request is unauthenticated. Keeps the SCIM error surface - * consistent with RFC 7644 rather than leaking the default Spring Security HTML/JSON body. + * SCIM-shaped authentication entry point: renders a {@code 401 Unauthorized} with an {@code + * application/scim+json} {@link ScimError} envelope and a {@code WWW-Authenticate: Bearer} header + * when a {@code /scim/v2/**} request is unauthenticated. Keeps the SCIM error surface consistent + * with RFC 7644 rather than leaking the default Spring Security HTML/JSON body. */ @Component public class ScimAuthenticationEntryPoint implements AuthenticationEntryPoint { diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimConfig.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimConfig.java index 71cf5ff..572592a 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimConfig.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimConfig.java @@ -9,8 +9,8 @@ * *

          Component-scans this package so the SCIM security chain, token filter, controllers, service, * error advice, content-type converter, and the service-principal initializer are all registered, - * and binds {@link ScimProperties}. Activated by {@code ScimAutoConfiguration} only when - * {@code openelements.scim.token} is set; consumers may also {@code @Import} it explicitly. + * and binds {@link ScimProperties}. Activated by {@code ScimAutoConfiguration} only when {@code + * openelements.scim.token} is set; consumers may also {@code @Import} it explicitly. */ @Configuration(proxyBeanMethods = false) @ComponentScan(basePackageClasses = ScimConfig.class) diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimDiscoveryController.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimDiscoveryController.java index 760c0bd..bc57ecc 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimDiscoveryController.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimDiscoveryController.java @@ -74,27 +74,38 @@ public List> resourceTypes() { public List> schemas() { return List.of( Map.of( - "id", ScimSchemas.USER, - "name", "User", - "description", "SCIM core User", + "id", + ScimSchemas.USER, + "name", + "User", + "description", + "SCIM core User", "attributes", - List.of( - attribute("userName", "string", true), - attribute("externalId", "string", false), - attribute("displayName", "string", false), - attribute("active", "boolean", false)))); + List.of( + attribute("userName", "string", true), + attribute("externalId", "string", false), + attribute("displayName", "string", false), + attribute("active", "boolean", false)))); } private static Map attribute( final String name, final String type, final boolean required) { return Map.of( - "name", name, - "type", type, - "multiValued", false, - "required", required, - "caseExact", false, - "mutability", "readWrite", - "returned", "default", - "uniqueness", "userName".equals(name) ? "server" : "none"); + "name", + name, + "type", + type, + "multiValued", + false, + "required", + required, + "caseExact", + false, + "mutability", + "readWrite", + "returned", + "default", + "uniqueness", + "userName".equals(name) ? "server" : "none"); } } diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimNotImplementedException.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimNotImplementedException.java index 1d0b436..3048b28 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimNotImplementedException.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimNotImplementedException.java @@ -3,8 +3,8 @@ import org.springframework.http.HttpStatus; /** - * Thrown for SCIM operations this slice deliberately does not implement (group writes, user - * {@code PATCH}). Maps to {@code 501 Not Implemented}. + * Thrown for SCIM operations this slice deliberately does not implement (group writes, user {@code + * PATCH}). Maps to {@code 501 Not Implemented}. */ public class ScimNotImplementedException extends ScimException { diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimProperties.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimProperties.java index 6667ce6..81d283f 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimProperties.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimProperties.java @@ -3,8 +3,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** - * Configuration properties for the SCIM 2.0 service provider, bound from the - * {@code openelements.scim} prefix. + * Configuration properties for the SCIM 2.0 service provider, bound from the {@code + * openelements.scim} prefix. * *

          The whole SCIM feature is gated on {@link #getToken()} being present: without a configured * token the module's auto-configuration does not activate, so {@code /scim/v2/**} is not served. diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimSecurityConfig.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimSecurityConfig.java index 3bd93fb..fac2cb7 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimSecurityConfig.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimSecurityConfig.java @@ -11,9 +11,9 @@ /** * Registers the isolated SCIM security filter chain. * - *

          Following the spec-006 discipline of strictly separated chains, this adds a third - * {@link SecurityFilterChain} that matches {@code /scim/v2/**} and authenticates it with the static - * SCIM token ({@link ScimTokenAuthenticationFilter}) — never JWT or API-key. It is ordered + *

          Following the spec-006 discipline of strictly separated chains, this adds a third {@link + * SecurityFilterChain} that matches {@code /scim/v2/**} and authenticates it with the static SCIM + * token ({@link ScimTokenAuthenticationFilter}) — never JWT or API-key. It is ordered * ahead of the default JWT chain (which has no matcher and is the fallback), so SCIM * requests are claimed here and never reach the JWT resource-server chain. A leaked SCIM token * therefore cannot be used against {@code /api/**} and vice versa. diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimServicePrincipal.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimServicePrincipal.java index 97d0600..feba5ba 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimServicePrincipal.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimServicePrincipal.java @@ -4,8 +4,8 @@ /** * Constants identifying the reserved SCIM service principal — a synthetic, permanently - * inactive {@link com.openelements.spring.base.services.user.UserEntity} row used as the audit actor - * for every write performed over the SCIM API. + * inactive {@link com.openelements.spring.base.services.user.UserEntity} row used as the audit + * actor for every write performed over the SCIM API. * *

          It mirrors the System user of spec 008 but is distinct from it, so that SCIM-driven audit * entries are unambiguously attributable to "SCIM" and told apart from internal System actions and @@ -14,7 +14,9 @@ */ public final class ScimServicePrincipal { - /** Reserved fixed UUID of the SCIM service principal (distinct from the System user's nil UUID). */ + /** + * Reserved fixed UUID of the SCIM service principal (distinct from the System user's nil UUID). + */ public static final UUID ID = UUID.fromString("00000000-0000-0000-0000-0000000000cf"); /** Reserved {@code userName} of the SCIM service principal. */ diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimServicePrincipalInitializer.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimServicePrincipalInitializer.java index 3e3e9ab..f34d0ab 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimServicePrincipalInitializer.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimServicePrincipalInitializer.java @@ -13,15 +13,15 @@ import org.springframework.transaction.annotation.Transactional; /** - * Ensures the reserved {@link ScimServicePrincipal SCIM service principal} row exists in the - * {@code users} table on startup, so SCIM writes can be attributed to it in the audit log. + * Ensures the reserved {@link ScimServicePrincipal SCIM service principal} row exists in the {@code + * users} table on startup, so SCIM writes can be attributed to it in the audit log. * - *

          Mirrors {@code SystemUserInitializer} (spec 008): the row carries a pre-assigned reserved UUID, - * so it is inserted through {@link JdbcTemplate} (a direct SQL {@code INSERT}) rather than + *

          Mirrors {@code SystemUserInitializer} (spec 008): the row carries a pre-assigned reserved + * UUID, so it is inserted through {@link JdbcTemplate} (a direct SQL {@code INSERT}) rather than * {@code UserRepository#save}, which would treat the pre-assigned id as a detached-entity update. - * The insert is idempotent — guarded by an {@code existsById} check and a - * {@link DataIntegrityViolationException} catch for the concurrent-startup race. The principal is - * created {@code active = false} so it can never authenticate interactively. + * The insert is idempotent — guarded by an {@code existsById} check and a {@link + * DataIntegrityViolationException} catch for the concurrent-startup race. The principal is created + * {@code active = false} so it can never authenticate interactively. */ @Component public class ScimServicePrincipalInitializer implements ApplicationRunner { @@ -58,7 +58,9 @@ public void run(final ApplicationArguments args) { } try { jdbcTemplate.update( - INSERT_SQL, ScimServicePrincipal.ID, ScimServicePrincipal.USER_NAME, + INSERT_SQL, + ScimServicePrincipal.ID, + ScimServicePrincipal.USER_NAME, ScimServicePrincipal.NAME); LOG.info("Created SCIM service principal row (id={})", ScimServicePrincipal.ID); } catch (final DataIntegrityViolationException e) { diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimTokenAuthenticationFilter.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimTokenAuthenticationFilter.java index e96c8af..557960d 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimTokenAuthenticationFilter.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimTokenAuthenticationFilter.java @@ -24,9 +24,9 @@ *

          Extracts the {@code Authorization: Bearer } header and compares it to the configured * token with a constant-time comparison ({@link MessageDigest#isEqual} over UTF-8 * bytes) to avoid leaking the secret through a timing side channel. On a match it authenticates the - * request as the reserved {@link ScimServicePrincipal SCIM service principal}; on a missing or wrong - * token it leaves the context unauthenticated, so the chain's {@code authenticated()} rule triggers - * the SCIM {@code 401} entry point. + * request as the reserved {@link ScimServicePrincipal SCIM service principal}; on a missing or + * wrong token it leaves the context unauthenticated, so the chain's {@code authenticated()} rule + * triggers the SCIM {@code 401} entry point. */ @Component public class ScimTokenAuthenticationFilter extends OncePerRequestFilter { diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUniquenessException.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUniquenessException.java index fcc79f5..516a745 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUniquenessException.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUniquenessException.java @@ -3,9 +3,8 @@ import org.springframework.http.HttpStatus; /** - * Thrown when a SCIM {@code POST} would violate the uniqueness of {@code externalId} or - * {@code userName}. Maps to {@code 409 Conflict} with {@code scimType: "uniqueness"} (RFC 7644 - * §3.3). + * Thrown when a SCIM {@code POST} would violate the uniqueness of {@code externalId} or {@code + * userName}. Maps to {@code 409 Conflict} with {@code scimType: "uniqueness"} (RFC 7644 §3.3). */ public class ScimUniquenessException extends ScimException { diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUserController.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUserController.java index 32752d4..ce86b4c 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUserController.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUserController.java @@ -17,14 +17,16 @@ /** * SCIM 2.0 Users resource endpoints (RFC 7644 §3.2–§3.6) under {@code /scim/v2/Users}, all speaking - * {@code application/scim+json}. Delegates business rules to {@link ScimUserService}; SCIM errors are - * rendered by {@link ScimExceptionHandler}. + * {@code application/scim+json}. Delegates business rules to {@link ScimUserService}; SCIM errors + * are rendered by {@link ScimExceptionHandler}. */ @RestController @RequestMapping(path = "/scim/v2/Users", produces = ScimMediaType.SCIM_JSON) public class ScimUserController { - /** Default page size when the client does not supply {@code count} (matches the advertised max). */ + /** + * Default page size when the client does not supply {@code count} (matches the advertised max). + */ private static final int DEFAULT_COUNT = 200; private final ScimUserService scimUserService; diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUserService.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUserService.java index 425caae..e7e0fdf 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUserService.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/ScimUserService.java @@ -120,7 +120,8 @@ public ScimUser getById(final UUID id) { * @throws ScimValidationException if a non-empty filter is not a supported {@code eq} expression */ @Transactional(readOnly = true) - public ScimListResponse list(final String filter, final int startIndex, final int count) { + public ScimListResponse list( + final String filter, final int startIndex, final int count) { final List matches = applyFilter(filter).stream() .filter(u -> !u.isDeleted()) @@ -130,13 +131,14 @@ public ScimListResponse list(final String filter, final int startIndex final int effectiveStart = Math.max(startIndex, 1); final int fromIndex = Math.min(effectiveStart - 1, matches.size()); final int toIndex = Math.min(fromIndex + Math.max(count, 0), matches.size()); - final List page = matches.subList(fromIndex, toIndex).stream().map(this::toScim).toList(); + final List page = + matches.subList(fromIndex, toIndex).stream().map(this::toScim).toList(); return ScimListResponse.of(page, matches.size(), effectiveStart); } /** - * Full-replace update of a user's mutable fields (RFC 7644 §3.5.1). A {@code PUT} carrying - * {@code active:true} on a soft-deleted row undeletes it. {@code sub} is never written. + * Full-replace update of a user's mutable fields (RFC 7644 §3.5.1). A {@code PUT} carrying {@code + * active:true} on a soft-deleted row undeletes it. {@code sub} is never written. * * @param id the user id * @param request the replacement SCIM representation @@ -224,7 +226,8 @@ private static String requireUserName(final ScimUser request) { } private static String resolveName(final ScimUser request, final String fallback) { - if (request.name() != null && request.name().formatted() != null + if (request.name() != null + && request.name().formatted() != null && !request.name().formatted().isBlank()) { return request.name().formatted(); } @@ -248,9 +251,7 @@ private static String resolvePrimaryEmail(final ScimUser request) { private ScimUser toScim(final UserEntity entity) { final String id = entity.id().toString(); final List emails = - entity.getEmail() == null - ? null - : List.of(new ScimEmail(entity.getEmail(), true, null)); + entity.getEmail() == null ? null : List.of(new ScimEmail(entity.getEmail(), true, null)); return new ScimUser( List.of(ScimSchemas.USER), id, diff --git a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/model/ScimName.java b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/model/ScimName.java index 59b49cc..c4deb10 100644 --- a/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/model/ScimName.java +++ b/spring-services-scim/src/main/java/com/openelements/spring/base/services/scim/model/ScimName.java @@ -3,9 +3,9 @@ import com.fasterxml.jackson.annotation.JsonInclude; /** - * SCIM {@code name} complex attribute (RFC 7643 §4.1.1). Only {@code formatted} is persisted by this - * slice (mapped to {@code UserEntity.name}); {@code givenName}/{@code familyName} are accepted on - * input but not stored separately. + * SCIM {@code name} complex attribute (RFC 7643 §4.1.1). Only {@code formatted} is persisted by + * this slice (mapped to {@code UserEntity.name}); {@code givenName}/{@code familyName} are accepted + * on input but not stored separately. * * @param formatted the full display name * @param givenName the given (first) name, accepted but not persisted separately diff --git a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimAuthenticationEntryPointMapperTest.java b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimAuthenticationEntryPointMapperTest.java index edf2263..e31f4fe 100644 --- a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimAuthenticationEntryPointMapperTest.java +++ b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimAuthenticationEntryPointMapperTest.java @@ -17,8 +17,9 @@ * mapper. * *

          Since Spring Boot 4 that mapper is a Jackson 3 {@code JsonMapper}; the entry point must - * receive Boot's bean — including the application's customisations — rather than a mapper of its own. A - * customisation that is visible in every body ({@code indent-output}) proves which mapper wrote it. + * receive Boot's bean — including the application's customisations — rather than a mapper of its + * own. A customisation that is visible in every body ({@code indent-output}) proves which mapper + * wrote it. * *

          Mock-Audit. No mocks; Spring's servlet test doubles stand in for the container. */ diff --git a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimAutoConfigurationTest.java b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimAutoConfigurationTest.java index 58738af..1f24d2b 100644 --- a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimAutoConfigurationTest.java +++ b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimAutoConfigurationTest.java @@ -24,7 +24,6 @@ class ScimAutoConfigurationTest { @DisplayName("Stays inert (no SCIM beans) when openelements.scim.token is not set") void inertWithoutToken() { contextRunner.run( - context -> - assertThat(context).hasNotFailed().doesNotHaveBean(ScimUserService.class)); + context -> assertThat(context).hasNotFailed().doesNotHaveBean(ScimUserService.class)); } } diff --git a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimTestApp.java b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimTestApp.java index 0e7b0fd..121eeed 100644 --- a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimTestApp.java +++ b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimTestApp.java @@ -7,7 +7,8 @@ * Minimal boot application for the SCIM integration tests. Relies entirely on auto-configuration: * the core starter registers the library packages/entities and the SCIM starter activates because * {@code openelements.scim.token} is set in the test profile. OAuth2 resource-server auto-config is - * excluded (a stub {@code JwtDecoder} is supplied by the test configuration for the core JWT chain). + * excluded (a stub {@code JwtDecoder} is supplied by the test configuration for the core JWT + * chain). */ @SpringBootApplication(exclude = OAuth2ResourceServerAutoConfiguration.class) public class ScimTestApp {} diff --git a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimTestConfiguration.java b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimTestConfiguration.java index 314d3d2..6c1f1e8 100644 --- a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimTestConfiguration.java +++ b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimTestConfiguration.java @@ -7,7 +7,9 @@ import org.springframework.security.oauth2.jwt.JwtDecoder; import org.testcontainers.postgresql.PostgreSQLContainer; -/** Test infrastructure: a PostgreSQL Testcontainer and a stub {@link JwtDecoder} for the JWT chain. */ +/** + * Test infrastructure: a PostgreSQL Testcontainer and a stub {@link JwtDecoder} for the JWT chain. + */ @TestConfiguration(proxyBeanMethods = false) public class ScimTestConfiguration { diff --git a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimUsersIntegrationTest.java b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimUsersIntegrationTest.java index 14c70f4..f35bfbe 100644 --- a/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimUsersIntegrationTest.java +++ b/spring-services-scim/src/test/java/com/openelements/spring/base/scim/ScimUsersIntegrationTest.java @@ -56,8 +56,9 @@ class ScimUsersIntegrationTest { void configureMockMvc(final WebApplicationContext context) { this.mvc = MockMvcBuilders.webAppContextSetup(context) - .apply(org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers - .springSecurity()) + .apply( + org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers + .springSecurity()) .build(); } @@ -79,10 +80,11 @@ void validTokenAccepted() throws Exception { } /** - * Spec 024 made every other error response in the library an RFC 9457 problem and deliberately left - * SCIM alone: RFC 7644 defines its own error envelope, and a SCIM client is entitled to it. The - * content type and the absence of any problem member are asserted explicitly, because a regression - * here would still produce a {@code 401} and would only be noticed by an IdP's provisioning run. + * Spec 024 made every other error response in the library an RFC 9457 problem and deliberately + * left SCIM alone: RFC 7644 defines its own error envelope, and a SCIM client is entitled to it. + * The content type and the absence of any problem member are asserted explicitly, because a + * regression here would still produce a {@code 401} and would only be noticed by an IdP's + * provisioning run. */ @Test @DisplayName("A missing bearer token is rejected with a SCIM 401, not an RFC 9457 problem") @@ -143,8 +145,7 @@ void resourceTypesAndSchemas() throws Exception { @DisplayName("POST creates a brand-new user with a server-assigned id and sub = NULL") void createUser() throws Exception { final String location = - mvc.perform( - post("/scim/v2/Users").header(AUTH, TOKEN).contentType(SCIM).content(alice())) + mvc.perform(post("/scim/v2/Users").header(AUTH, TOKEN).contentType(SCIM).content(alice())) .andExpect(status().isCreated()) .andExpect(header().exists("Location")) .andExpect(jsonPath("$.id").exists()) @@ -193,7 +194,10 @@ void createDuplicateUserName() throws Exception { @DisplayName("POST without userName returns 400 invalidValue") void createMissingUserName() throws Exception { mvc.perform( - post("/scim/v2/Users").header(AUTH, TOKEN).contentType(SCIM).content("{\"active\":true}")) + post("/scim/v2/Users") + .header(AUTH, TOKEN) + .contentType(SCIM) + .content("{\"active\":true}")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.scimType", is("invalidValue"))); } @@ -230,20 +234,23 @@ void listExcludesDeletedAndReserved() throws Exception { seed("gone", "ext-3", false, true); mvc.perform(get("/scim/v2/Users").header(AUTH, TOKEN)) .andExpect(status().isOk()) - .andExpect(jsonPath("$.schemas[0]", is("urn:ietf:params:scim:api:messages:2.0:ListResponse"))) + .andExpect( + jsonPath("$.schemas[0]", is("urn:ietf:params:scim:api:messages:2.0:ListResponse"))) .andExpect(jsonPath("$.totalResults", is(2))) .andExpect(jsonPath("$.Resources", hasSize(2))); } @Test - @DisplayName("Filter by userName eq and externalId eq resolve exactly one user; no match is empty") + @DisplayName( + "Filter by userName eq and externalId eq resolve exactly one user; no match is empty") void filter() throws Exception { seed("alice", "ext-1", true, false); seed("bob", "ext-2", true, false); mvc.perform(get("/scim/v2/Users").param("filter", "userName eq \"alice\"").header(AUTH, TOKEN)) .andExpect(jsonPath("$.totalResults", is(1))) .andExpect(jsonPath("$.Resources[0].userName", is("alice"))); - mvc.perform(get("/scim/v2/Users").param("filter", "externalId eq \"ext-2\"").header(AUTH, TOKEN)) + mvc.perform( + get("/scim/v2/Users").param("filter", "externalId eq \"ext-2\"").header(AUTH, TOKEN)) .andExpect(jsonPath("$.totalResults", is(1))) .andExpect(jsonPath("$.Resources[0].userName", is("bob"))); mvc.perform(get("/scim/v2/Users").param("filter", "userName eq \"ghost\"").header(AUTH, TOKEN)) @@ -257,7 +264,8 @@ void pagination() throws Exception { for (int i = 1; i <= 5; i++) { seed("user" + i, "ext-" + i, true, false); } - mvc.perform(get("/scim/v2/Users").param("startIndex", "3").param("count", "2").header(AUTH, TOKEN)) + mvc.perform( + get("/scim/v2/Users").param("startIndex", "3").param("count", "2").header(AUTH, TOKEN)) .andExpect(jsonPath("$.totalResults", is(5))) .andExpect(jsonPath("$.startIndex", is(3))) .andExpect(jsonPath("$.itemsPerPage", is(2))) @@ -299,14 +307,18 @@ void putReplace() throws Exception { void putDeactivateAndUndelete() throws Exception { final UUID id = seed("alice", "ext-1", true, false); mvc.perform( - put("/scim/v2/Users/" + id).header(AUTH, TOKEN).contentType(SCIM) + put("/scim/v2/Users/" + id) + .header(AUTH, TOKEN) + .contentType(SCIM) .content("{\"userName\":\"alice\",\"active\":false}")) .andExpect(status().isOk()); assertThat(userRepository.findById(id).orElseThrow().isActive()).isFalse(); final UUID deleted = seed("bob", "ext-2", false, true); mvc.perform( - put("/scim/v2/Users/" + deleted).header(AUTH, TOKEN).contentType(SCIM) + put("/scim/v2/Users/" + deleted) + .header(AUTH, TOKEN) + .contentType(SCIM) .content("{\"userName\":\"bob\",\"active\":true}")) .andExpect(status().isOk()); final UserEntity revived = userRepository.findById(deleted).orElseThrow(); @@ -320,7 +332,8 @@ void putDeactivateAndUndelete() throws Exception { @Test @DisplayName("DELETE soft-deletes, distinguishes from deactivation, and 404s on unknown id") void softDelete() throws Exception { - final UUID deactivated = seed("a", "ext-a", false, false); // PUT active:false earlier (deactivated) + final UUID deactivated = + seed("a", "ext-a", false, false); // PUT active:false earlier (deactivated) final UUID id = seed("b", "ext-b", true, false); mvc.perform(delete("/scim/v2/Users/" + id).header(AUTH, TOKEN)) .andExpect(status().isNoContent()); @@ -346,11 +359,15 @@ void auditAttribution() throws Exception { UUID.fromString( lastPathSegment( mvc.perform( - post("/scim/v2/Users").header(AUTH, TOKEN).contentType(SCIM).content(alice())) + post("/scim/v2/Users") + .header(AUTH, TOKEN) + .contentType(SCIM) + .content(alice())) .andReturn() .getResponse() .getHeader("Location"))); - mvc.perform(delete("/scim/v2/Users/" + id).header(AUTH, TOKEN)).andExpect(status().isNoContent()); + mvc.perform(delete("/scim/v2/Users/" + id).header(AUTH, TOKEN)) + .andExpect(status().isNoContent()); final List actions = jdbcTemplate.queryForList( @@ -394,7 +411,11 @@ private static String alice() { } private static String user(final String userName, final String externalId) { - return "{\"userName\":\"" + userName + "\",\"externalId\":\"" + externalId + "\",\"active\":true}"; + return "{\"userName\":\"" + + userName + + "\",\"externalId\":\"" + + externalId + + "\",\"active\":true}"; } private static String lastPathSegment(final String path) { diff --git a/spring-services-search/src/main/java/com/openelements/spring/base/search/SearchAutoConfiguration.java b/spring-services-search/src/main/java/com/openelements/spring/base/search/SearchAutoConfiguration.java index 1a47163..e0be4de 100644 --- a/spring-services-search/src/main/java/com/openelements/spring/base/search/SearchAutoConfiguration.java +++ b/spring-services-search/src/main/java/com/openelements/spring/base/search/SearchAutoConfiguration.java @@ -7,12 +7,12 @@ /** * Auto-configuration for the optional Meilisearch-backed search feature. * - *

          Registered through this module's - * {@code META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the - * feature self-activates when {@code spring-services-search} is on the classpath. The module carries - * no extra third-party dependency (it talks to Meilisearch over Spring's {@code RestClient}), so - * there is no heavy-dependency class to guard on; runtime opt-in is governed by - * {@link SearchConfig}'s existing {@code @ConditionalOnProperty(openelements.meilisearch.enabled)}. + *

          Registered through this module's {@code + * META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports}, so the feature + * self-activates when {@code spring-services-search} is on the classpath. The module carries no + * extra third-party dependency (it talks to Meilisearch over Spring's {@code RestClient}), so there + * is no heavy-dependency class to guard on; runtime opt-in is governed by {@link SearchConfig}'s + * existing {@code @ConditionalOnProperty(openelements.meilisearch.enabled)}. * *

          Lives outside the {@code services.search} package on purpose: {@link SearchConfig} declares a * {@code @ComponentScan} over its own package, and an auto-configuration co-located there would be diff --git a/spring-services-search/src/main/java/com/openelements/spring/base/services/search/MeilisearchClient.java b/spring-services-search/src/main/java/com/openelements/spring/base/services/search/MeilisearchClient.java index e33720a..65e59b8 100644 --- a/spring-services-search/src/main/java/com/openelements/spring/base/services/search/MeilisearchClient.java +++ b/spring-services-search/src/main/java/com/openelements/spring/base/services/search/MeilisearchClient.java @@ -61,8 +61,8 @@ public void useApiKey(final String key) { /** * Returns true if Meilisearch reports {@code status == "available"}. * - * @return {@code true} if the {@code /health} endpoint reports the instance as available, - * {@code false} if it is unhealthy or unreachable + * @return {@code true} if the {@code /health} endpoint reports the instance as available, {@code + * false} if it is unhealthy or unreachable */ public boolean isHealthy() { try { diff --git a/spring-services-search/src/main/java/com/openelements/spring/base/services/search/MeilisearchProperties.java b/spring-services-search/src/main/java/com/openelements/spring/base/services/search/MeilisearchProperties.java index ad1cc7b..2f9d3df 100644 --- a/spring-services-search/src/main/java/com/openelements/spring/base/services/search/MeilisearchProperties.java +++ b/spring-services-search/src/main/java/com/openelements/spring/base/services/search/MeilisearchProperties.java @@ -10,9 +10,9 @@ * application properties. * *

          The search feature is opt-in: it is disabled by default and only activates - * when {@code openelements.meilisearch.enabled=true} (see {@link SearchConfig}). When the feature is - * enabled, {@code host} is required — there is no default. A blank or missing host - * fails context startup with a binding/validation error rather than silently pointing at + * when {@code openelements.meilisearch.enabled=true} (see {@link SearchConfig}). When the feature + * is enabled, {@code host} is required — there is no default. A blank or missing + * host fails context startup with a binding/validation error rather than silently pointing at * {@code localhost}, so a misconfiguration surfaces immediately instead of at first use. * *

          This type is app-agnostic: it carries only the connection data and the index-prefix resolution @@ -33,7 +33,9 @@ public record MeilisearchProperties( @NotBlank String host, String masterKey, String indexPrefix, Duration requestTimeout) { - /** Applies defaults for optional components: empty index prefix and a 5-second request timeout. */ + /** + * Applies defaults for optional components: empty index prefix and a 5-second request timeout. + */ public MeilisearchProperties { if (indexPrefix == null) { indexPrefix = ""; diff --git a/spring-services-search/src/main/java/com/openelements/spring/base/services/search/SearchConfig.java b/spring-services-search/src/main/java/com/openelements/spring/base/services/search/SearchConfig.java index 7de665d..b9f17c0 100644 --- a/spring-services-search/src/main/java/com/openelements/spring/base/services/search/SearchConfig.java +++ b/spring-services-search/src/main/java/com/openelements/spring/base/services/search/SearchConfig.java @@ -28,10 +28,10 @@ * fails startup rather than defaulting to {@code localhost}. * *

          Once enabled, the feature is still inert unless a Meilisearch sidecar is reachable: when it is - * not, the startup runners log a warning and flip readiness to ready without indexing. The consuming - * application supplies what the lib indexes — an optional {@link ScopedKeySpec} bean, one {@link - * IndexSettings} bean per index, and one {@link SearchIndexBootstrapStep} bean per index — plus, for - * asynchronous bootstrap, {@code @EnableAsync} and a {@code searchIndexExecutor} bean. + * not, the startup runners log a warning and flip readiness to ready without indexing. The + * consuming application supplies what the lib indexes — an optional {@link ScopedKeySpec} bean, one + * {@link IndexSettings} bean per index, and one {@link SearchIndexBootstrapStep} bean per index — + * plus, for asynchronous bootstrap, {@code @EnableAsync} and a {@code searchIndexExecutor} bean. */ @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "openelements.meilisearch", name = "enabled", havingValue = "true") diff --git a/spring-services-search/src/test/java/com/openelements/spring/base/services/search/HighlighterTest.java b/spring-services-search/src/test/java/com/openelements/spring/base/services/search/HighlighterTest.java index 5b000c6..9c3d29f 100644 --- a/spring-services-search/src/test/java/com/openelements/spring/base/services/search/HighlighterTest.java +++ b/spring-services-search/src/test/java/com/openelements/spring/base/services/search/HighlighterTest.java @@ -16,8 +16,8 @@ * user-typed text are escaped (angle brackets, ampersands, single and double quotes); the * private-use Unicode boundary markers Meilisearch wraps around matches are converted to literal * {@code } / {@code } tags after escaping, so a hostile match like {@code - *