diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fd00d92 --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..43f0454 --- /dev/null +++ b/README.md @@ -0,0 +1,233 @@ +# Spring Security Exception Handler + +A flexible library for handling Spring Security exceptions with customizable response formats, supporting both REST and GraphQL APIs. + +--- + +## Table of Contents + +1. [Overview](#overview) +2. [Project Structure](#project-structure) +3. [Getting Started](#getting-started) + - [Installation](#installation) + - [Basic Usage](#basic-usage) +4. [Implementation Details](#implementation-details) + +--- + +## Overview + +By default, Spring Security uses its own `ExceptionTranslationFilter` which converts `AuthenticationException` and `AccessDeniedException` into empty responses with 401 and 403 status codes respectively. While this behavior is sufficient for many applications, there are cases when such behavior is not desired. + +For example, in a microservice GraphQL federation environment, there is more value in returning JSON in a GraphQL-compatible format, allowing you to see access denied errors rather than just internal server errors. + +**Spring Security Exception Handler** provides a clean and flexible way to handle security exceptions in Spring applications. It allows you to customize how authentication and authorization exceptions are handled and presented to clients, with built-in support for both standard REST APIs and GraphQL endpoints. + +### Key Features + +- Custom handling of Spring Security exceptions (`AuthenticationException` and `AccessDeniedException`) +- URL pattern-based routing of exceptions to appropriate handlers +- Built-in support for REST and GraphQL response formats +- Flexible builder API for creating custom exception handlers +- Spring Boot auto-configuration with sensible defaults +- Fully customizable through application properties + +--- + +## Project Structure + +This project consists of two main libraries: + +- **`spring-security-exception-handler`** - Core library with exception handling logic and builder API +- **`spring-security-exception-handler-starter`** - Spring Boot starter with auto-configuration and property support + +--- + +## Getting Started + +### Installation + +Add the starter dependency to your Spring Boot project: + +#### Gradle +```kotlin +implementation("dev.clutcher.spring-security:spring-security-exception-handler-starter:1.0.0") +``` + +#### Maven +```xml + + dev.clutcher.spring-security + spring-security-exception-handler-starter + 1.0.0 + +``` + +### Basic Usage + +The library provides auto-configuration that automatically sets up default exception handlers for both REST and GraphQL endpoints. Simply add the starter dependency to your project and the library will automatically inject a preconfigured instance of `SpringSecurityExceptionFilterConfigurer` through Spring Boot's auto-configuration mechanism. + +The auto-configuration is enabled through `spring.factories` and `SpringSecurityExceptionHandlerAutoConfiguration`, which automatically registers the necessary components without requiring any manual configuration. + +That's it! The library will automatically handle Spring Security exceptions with sensible defaults - no additional configuration required. + +#### Manual Filter Configuration + +If you need more control over the filter configuration or prefer explicit setup, you can manually create and configure the `SpringSecurityExceptionFilter` bean: + +```java +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + @Autowired + private List exceptionHandlers; + + @Bean + public SpringSecurityExceptionFilter springSecurityExceptionFilter() { + return new SpringSecurityExceptionFilter(exceptionHandlers); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http, + SpringSecurityExceptionFilter exceptionFilter) throws Exception { + return http + .authorizeHttpRequests(authorize -> authorize + .requestMatchers("/public/**").permitAll() + .anyRequest().authenticated() + ) + .addFilterBefore(exceptionFilter, ExceptionTranslationFilter.class) + .formLogin(withDefaults()) + .build(); + } +} +``` + +This approach gives you full control over when and how the filter is added to the security filter chain. + +#### Property-Based Configuration + +Configure exception handlers through application properties: + +```yaml +dev: + clutcher: + security: + handlers: + default: + enabled: true + urls: ["/**"] + order: 100 + graphql: + enabled: true + urls: ["/graphql"] + order: 0 + custom: + enabled: true + urls: ["/api/v2/**"] + order: 50 +``` + +#### Custom Exception Handler + +Create custom exception handlers for specific URL patterns: + +```java +@Configuration +public class CustomExceptionHandlerConfig { + + @Bean + public SpringSecurityExceptionHandler apiV2ExceptionHandler() { + return SpringSecurityExceptionHandlerBuilder.builder() + .canHandle(new UrlMatchingPredicate(List.of("/api/v2/**"))) + .handle(new ErrorResponseWritingConsumer(exception -> { + if (exception instanceof AuthenticationException) { + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_UNAUTHORIZED, + "{\"error\":\"Authentication required\",\"code\":\"AUTH_REQUIRED\"}" + ); + } + if (exception instanceof AccessDeniedException) { + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_FORBIDDEN, + "{\"error\":\"Access denied\",\"code\":\"ACCESS_DENIED\"}" + ); + } + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "{\"error\":\"Internal server error\"}" + ); + })) + .order(50) + .build(); + } +} +``` + +## Implementation Details + +The Spring Security Exception Handler library is built around several key components that work together to provide flexible exception handling for Spring Security applications. + +### Core Components + +The library consists of the following main interfaces and classes: + +- **`SpringSecurityExceptionFilter`** - Servlet filter that intercepts Spring Security exceptions and delegates to registered handlers. +- **`SpringSecurityExceptionHandler`** - Main interface for handling security exceptions. Implements `Ordered` to support priority-based handler selection. +- **`SpringSecurityExceptionHandlerBuilder`** - Fluent builder API for creating custom exception handlers with predicates and response writers. +- **`UrlMatchingPredicate`** - Predicate implementation for URL pattern matching using Spring's `AntPathMatcher`. +- **`ErrorResponseWritingConsumer`** - Consumer for writing structured error responses with customizable status codes and content. +- **`ExceptionMappingFunctions`** - Utility class providing pre-built exception mapping functions for common use cases. + +### Exception Handling Flow + +The exception handling process follows this sequence: + +1. Spring Security's authentication or authorization mechanisms throw an `AuthenticationException` or `AccessDeniedException` +2. `SpringSecurityExceptionFilter` intercepts the exception before it reaches Spring Security's default `ExceptionTranslationFilter` +3. The filter iterates through all registered `SpringSecurityExceptionHandler` beans in priority order (based on the `getOrder()` method) +4. The first handler that returns `true` from its `canHandle(HttpServletRequest)` method processes the exception +5. The selected handler writes a custom response to the `HttpServletResponse` using its configured response writer +6. If no handler can process the request, the exception continues to Spring Security's default behavior + +### Auto-Configuration + +The Spring Boot starter provides auto-configuration through `SpringSecurityExceptionHandlerAutoConfiguration`, which: + +- Registers default exception handlers for common scenarios (REST APIs, GraphQL endpoints) +- Configures handlers based on application properties under the `dev.clutcher.security` namespace +- Uses conditional beans to avoid conflicts with custom handler configurations +- Integrates seamlessly with Spring Security's filter chain through `SpringSecurityExceptionFilterConfigurer` + +### Property-Based Configuration + +The library supports comprehensive configuration through application properties: + +```yaml +dev: + clutcher: + security: + handlers: + default: + enabled: true # Enable/disable the handler + urls: ["/**"] # URL patterns to match + order: 100 # Handler priority (lower = higher priority) + graphql: + enabled: true + urls: ["/graphql", "/graphiql"] + order: 0 +``` + +Each handler configuration supports: +- **enabled** - Boolean flag to enable/disable the handler +- **urls** - List of URL patterns using Ant-style matching +- **order** - Integer defining handler priority (lower values have higher priority) + +### Extensibility + +The library is designed for extensibility through several extension points: + +- **Custom Predicates** - Implement custom logic for determining when a handler should process a request +- **Custom Response Writers** - Create specialized response formats (XML, custom JSON structures, etc.) +- **Handler Composition** - Combine multiple handlers with different priorities and URL patterns +- **Integration Points** - Leverage Spring Boot's conditional configuration to adapt to different application contexts diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..3e20856 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,162 @@ +import org.jreleaser.gradle.plugin.JReleaserExtension +import org.jreleaser.model.Http + +plugins { + id("java") + id("io.spring.dependency-management") version "1.1.7" + + id("maven-publish") + id("signing") + id("org.jreleaser") version "1.17.0" +} + +extra["springBootVersion"] = "3.5.3" + +allprojects { + group = "dev.clutcher.spring-security" + version = "1.0.0" +} + +configureJReleaser() + +subprojects { + apply(plugin = "java") + apply(plugin = "io.spring.dependency-management") + + apply(plugin = "maven-publish") + apply(plugin = "signing") + + java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } + + withSourcesJar() + withJavadocJar() + } + + repositories { + mavenCentral() + } + + dependencies { + testImplementation("org.junit.jupiter:junit-jupiter") + } + + dependencyManagement { + imports { + mavenBom("org.springframework.boot:spring-boot-dependencies:${property("springBootVersion")}") + } + } + + configurePublishing() + + signing { + useGpgCmd() + sign(publishing.publications["default"]) + } + + tasks.test { + useJUnitPlatform() + } +} + +fun Project.configurePublishing() { + publishing { + publications { + create("default") { + + from(components["java"]) + + pom { + name.set(project.name) + description.set(provider { project.description }) + + url.set("https://github.com/clutcher/spring-modulith-module-archunit") + + licenses { + license { + name.set("MIT License") + url.set("https://github.com/clutcher/spring-modulith-module-archunit/blob/main/LICENSE") + distribution.set("repo") + } + } + + developers { + developer { + id.set("clutcher") + name.set("Igor Zarvanskyi") + email.set("iclutcher@gmail.com") + } + } + + scm { + connection.set("scm:git:git://github.com/clutcher/spring-modulith-module-archunit.git") + developerConnection.set("scm:git:ssh://github.com/clutcher/spring-modulith-module-archunit.git") + url.set("https://github.com/clutcher/spring-modulith-module-archunit") + } + } + } + } + + repositories { + maven { + name = "RootStaging" + url = uri(rootProject.layout.buildDirectory.dir("staging-deploy")) + } + } + + } +} + +fun Project.configureJReleaser() { + configure { + + release { + github { + repoOwner = "clutcher" + } + } + + deploy { + maven { + mavenCentral { + create("sonatype") { + setActive("ALWAYS") + sign.set(false) + + url.set("https://central.sonatype.com/api/v1/publisher") + authorization.set(Http.Authorization.BEARER) + + username.set(System.getenv("MAVENCENTRAL_USERNAME")) + password.set(System.getenv("MAVENCENTRAL_PASSWORD")) + + stagingRepository("build/staging-deploy") + } + } + } + } + } + + tasks.named("publish") { + // Add dependencies on each subproject's publish task + subprojects.forEach { subproject -> + dependsOn(subproject.tasks.named("publish")) + } + } + + tasks.named("publishToMavenLocal") { + // Add dependencies on each subproject's publish task + subprojects.forEach { subproject -> + dependsOn(subproject.tasks.named("publishToMavenLocal")) + } + } + + tasks.named("jreleaserFullRelease").configure { + dependsOn("publish") + } + + tasks.named("jreleaserDeploy").configure { + dependsOn("publish") + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..6074fb8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase = GRADLE_USER_HOME +distributionPath = wrapper/dists +distributionUrl = https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip +networkTimeout = 10000 +validateDistributionUrl = true +zipStoreBase = GRADLE_USER_HOME +zipStorePath = wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..b26d411 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" \ No newline at end of file diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f46bb52 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..c194569 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,5 @@ +rootProject.name = "spring-security-exception-handler" +include( + "spring-security-exception-handler", + "spring-security-exception-handler-starter" +) \ No newline at end of file diff --git a/spring-security-exception-handler-starter/build.gradle.kts b/spring-security-exception-handler-starter/build.gradle.kts new file mode 100644 index 0000000..d9102c5 --- /dev/null +++ b/spring-security-exception-handler-starter/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + id("java") + id("java-library") +} + +dependencies { + api(project(":spring-security-exception-handler")) + implementation("org.springframework.boot:spring-boot-starter-security") + implementation("org.springframework.boot:spring-boot-autoconfigure") + + implementation("jakarta.servlet:jakarta.servlet-api") +} \ No newline at end of file diff --git a/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SecurityExceptionHandlerProperties.java b/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SecurityExceptionHandlerProperties.java new file mode 100644 index 0000000..6eabd55 --- /dev/null +++ b/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SecurityExceptionHandlerProperties.java @@ -0,0 +1,75 @@ +package dev.clutcher.security.starter; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@ConfigurationProperties(prefix = "dev.clutcher.security") +public class SecurityExceptionHandlerProperties { + + private Map handlers = createDefaultHandlers(); + + public Map getHandlers() { + return handlers; + } + + public void setHandlers(Map handlers) { + Map mergedHandlers = createDefaultHandlers(); + if (handlers != null) { + mergedHandlers.putAll(handlers); + } + this.handlers = mergedHandlers; + } + + private Map createDefaultHandlers() { + Map defaults = new HashMap<>(); + + //Default handler + HandlerConfig defaultHandler = new HandlerConfig(); + defaultHandler.setEnabled(true); + defaultHandler.setUrls(List.of("/**")); + defaultHandler.setOrder(100); + defaults.put("default", defaultHandler); + + //GraphQL handler + HandlerConfig graphqlHandler = new HandlerConfig(); + graphqlHandler.setEnabled(true); + graphqlHandler.setUrls(List.of("/graphql")); + graphqlHandler.setOrder(0); + defaults.put("graphql", graphqlHandler); + + return defaults; + } + + public static class HandlerConfig { + private boolean enabled = false; + private List urls = List.of(); + private int order = 100; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public List getUrls() { + return urls; + } + + public void setUrls(List urls) { + this.urls = urls; + } + + public int getOrder() { + return order; + } + + public void setOrder(int order) { + this.order = order; + } + } +} \ No newline at end of file diff --git a/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SpringSecurityExceptionFilterConfigurer.java b/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SpringSecurityExceptionFilterConfigurer.java new file mode 100644 index 0000000..559cb7e --- /dev/null +++ b/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SpringSecurityExceptionFilterConfigurer.java @@ -0,0 +1,15 @@ +package dev.clutcher.security.starter; + +import dev.clutcher.security.filter.SpringSecurityExceptionFilter; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.web.access.ExceptionTranslationFilter; + +public class SpringSecurityExceptionFilterConfigurer extends AbstractHttpConfigurer { + + @Override + public void configure(HttpSecurity http) { + SpringSecurityExceptionFilter springSecurityExceptionFilter = new SpringSecurityExceptionFilter(); + http.addFilterAfter(this.postProcess(springSecurityExceptionFilter), ExceptionTranslationFilter.class); + } +} diff --git a/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SpringSecurityExceptionHandlerAutoConfiguration.java b/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SpringSecurityExceptionHandlerAutoConfiguration.java new file mode 100644 index 0000000..7fb70cd --- /dev/null +++ b/spring-security-exception-handler-starter/src/main/java/dev/clutcher/security/starter/SpringSecurityExceptionHandlerAutoConfiguration.java @@ -0,0 +1,64 @@ +package dev.clutcher.security.starter; + +import dev.clutcher.security.handler.SpringSecurityExceptionHandler; +import dev.clutcher.security.handler.SpringSecurityExceptionHandlerBuilder; +import dev.clutcher.security.handler.functions.ErrorResponseWritingConsumer; +import dev.clutcher.security.handler.functions.ExceptionMappingFunctions; +import dev.clutcher.security.handler.functions.UrlMatchingPredicate; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; + +@AutoConfiguration +@AutoConfigureAfter(SecurityAutoConfiguration.class) +@EnableConfigurationProperties(SecurityExceptionHandlerProperties.class) +public class SpringSecurityExceptionHandlerAutoConfiguration { + + @Bean + @ConditionalOnMissingBean(name = "defaultSecurityExceptionHandler") + public SpringSecurityExceptionHandler defaultSecurityExceptionHandler(SecurityExceptionHandlerProperties properties) { + SecurityExceptionHandlerProperties.HandlerConfig config = properties.getHandlers().get("default"); + + if (isEnabledHandler(config)) { + return null; + } + + return SpringSecurityExceptionHandlerBuilder.builder() + .canHandle(new UrlMatchingPredicate(config.getUrls())) + .handle( + new ErrorResponseWritingConsumer( + ExceptionMappingFunctions.jsonBodyExceptionMapping() + ) + ) + .order(config.getOrder()) + .build(); + } + + @Bean + @ConditionalOnMissingBean(name = "graphqlSecurityExceptionHandler") + public SpringSecurityExceptionHandler graphqlSecurityExceptionHandler(SecurityExceptionHandlerProperties properties) { + SecurityExceptionHandlerProperties.HandlerConfig config = properties.getHandlers().get("graphql"); + + if (isEnabledHandler(config)) { + return null; + } + + return SpringSecurityExceptionHandlerBuilder.builder() + .canHandle(new UrlMatchingPredicate(config.getUrls())) + .handle( + new ErrorResponseWritingConsumer( + ExceptionMappingFunctions.graphqlJsonBodyExceptionMapping() + ) + ) + .order(config.getOrder()) + .build(); + } + + private boolean isEnabledHandler(SecurityExceptionHandlerProperties.HandlerConfig config) { + return config == null || !config.isEnabled(); + } + +} \ No newline at end of file diff --git a/spring-security-exception-handler-starter/src/main/resources/META-INF/spring.factories b/spring-security-exception-handler-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000..dcff23e --- /dev/null +++ b/spring-security-exception-handler-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1 @@ +org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = dev.clutcher.security.starter.SpringSecurityExceptionFilterConfigurer \ No newline at end of file diff --git a/spring-security-exception-handler-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/spring-security-exception-handler-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000..e542c52 --- /dev/null +++ b/spring-security-exception-handler-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.clutcher.security.starter.SpringSecurityExceptionHandlerAutoConfiguration \ No newline at end of file diff --git a/spring-security-exception-handler/build.gradle.kts b/spring-security-exception-handler/build.gradle.kts new file mode 100644 index 0000000..6773267 --- /dev/null +++ b/spring-security-exception-handler/build.gradle.kts @@ -0,0 +1,19 @@ +plugins { + id("java") +} + +dependencies { + compileOnly(platform("org.springframework.security:spring-security-bom:6.4.4")) + + compileOnly("org.springframework.security:spring-security-core") + compileOnly("org.springframework.security:spring-security-web") + + compileOnly("jakarta.servlet:jakarta.servlet-api:6.0.0") + + testImplementation("org.springframework.security:spring-security-core") + testImplementation("org.springframework.security:spring-security-web") + testImplementation("jakarta.servlet:jakarta.servlet-api:6.0.0") + testImplementation("org.mockito:mockito-junit-jupiter:5.18.0") + + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} \ No newline at end of file diff --git a/spring-security-exception-handler/src/main/java/dev/clutcher/security/filter/SpringSecurityExceptionFilter.java b/spring-security-exception-handler/src/main/java/dev/clutcher/security/filter/SpringSecurityExceptionFilter.java new file mode 100644 index 0000000..3cc9156 --- /dev/null +++ b/spring-security-exception-handler/src/main/java/dev/clutcher/security/filter/SpringSecurityExceptionFilter.java @@ -0,0 +1,50 @@ +package dev.clutcher.security.filter; + +import dev.clutcher.security.handler.SpringSecurityExceptionHandler; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class SpringSecurityExceptionFilter extends OncePerRequestFilter { + + private List handlers; + + public SpringSecurityExceptionFilter(List handlers) { + this.handlers = new ArrayList<>(handlers); + } + + public SpringSecurityExceptionFilter() { + this.handlers = new ArrayList<>(); + } + + @Autowired + public void setHandlers(List handlers) { + this.handlers = new ArrayList<>(handlers); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + try { + filterChain.doFilter(request, response); + } catch (AuthenticationException | AccessDeniedException ex) { + for (SpringSecurityExceptionHandler handler : handlers) { + if (handler.canHandle(request)) { + handler.handle(ex, response); + return; + } + } + throw ex; + } + } +} \ No newline at end of file diff --git a/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/SpringSecurityExceptionHandler.java b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/SpringSecurityExceptionHandler.java new file mode 100644 index 0000000..997b60c --- /dev/null +++ b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/SpringSecurityExceptionHandler.java @@ -0,0 +1,15 @@ +package dev.clutcher.security.handler; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.core.Ordered; + +import java.io.IOException; + +public interface SpringSecurityExceptionHandler extends Ordered { + + boolean canHandle(HttpServletRequest request); + + void handle(RuntimeException exception, HttpServletResponse response) throws IOException; + +} diff --git a/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/SpringSecurityExceptionHandlerBuilder.java b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/SpringSecurityExceptionHandlerBuilder.java new file mode 100644 index 0000000..f520ff4 --- /dev/null +++ b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/SpringSecurityExceptionHandlerBuilder.java @@ -0,0 +1,56 @@ +package dev.clutcher.security.handler; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import java.io.IOException; +import java.util.function.BiConsumer; +import java.util.function.Predicate; + +public class SpringSecurityExceptionHandlerBuilder { + + private Predicate canHandlePredicate; + private BiConsumer handleFunction; + private int order = 0; + + private SpringSecurityExceptionHandlerBuilder() { + } + + public static SpringSecurityExceptionHandlerBuilder builder() { + return new SpringSecurityExceptionHandlerBuilder(); + } + + public SpringSecurityExceptionHandlerBuilder canHandle(Predicate canHandlePredicate) { + this.canHandlePredicate = canHandlePredicate; + return this; + } + + public SpringSecurityExceptionHandlerBuilder handle(BiConsumer handleFunction) { + this.handleFunction = handleFunction; + return this; + } + + public SpringSecurityExceptionHandlerBuilder order(int order) { + this.order = order; + return this; + } + + public SpringSecurityExceptionHandler build() { + return new SpringSecurityExceptionHandler() { + @Override + public boolean canHandle(HttpServletRequest request) { + return canHandlePredicate.test(request); + } + + @Override + public void handle(RuntimeException exception, HttpServletResponse response) { + handleFunction.accept(exception, response); + } + + @Override + public int getOrder() { + return order; + } + }; + } +} diff --git a/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/ErrorResponseWritingConsumer.java b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/ErrorResponseWritingConsumer.java new file mode 100644 index 0000000..39dabc7 --- /dev/null +++ b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/ErrorResponseWritingConsumer.java @@ -0,0 +1,37 @@ +package dev.clutcher.security.handler.functions; + +import jakarta.servlet.http.HttpServletResponse; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.function.BiConsumer; +import java.util.function.Function; + +public class ErrorResponseWritingConsumer implements BiConsumer { + + private final Function exceptionMapper; + + public ErrorResponseWritingConsumer(Function exceptionMapper) { + this.exceptionMapper = exceptionMapper; + } + + + @Override + public void accept(RuntimeException exception, HttpServletResponse response) { + ErrorResponse errorResponse = exceptionMapper.apply(exception); + + response.setStatus(errorResponse.status()); + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + + try (PrintWriter writer = response.getWriter()) { + writer.write(errorResponse.body()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public record ErrorResponse(int status, String body) { + } + +} diff --git a/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/ExceptionMappingFunctions.java b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/ExceptionMappingFunctions.java new file mode 100644 index 0000000..7f1867f --- /dev/null +++ b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/ExceptionMappingFunctions.java @@ -0,0 +1,54 @@ +package dev.clutcher.security.handler.functions; + +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; + +import java.util.function.Function; + +public class ExceptionMappingFunctions { + + public static Function jsonBodyExceptionMapping() { + return exception -> { + if (exception instanceof AuthenticationException) { + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_UNAUTHORIZED, + "{\"code\":\"AUTHENTICATION_ERROR\",\"message\":\"Authentication required\"}" + ); + } + if (exception instanceof AccessDeniedException) { + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_FORBIDDEN, + "{\"code\":\"ACCESS_DENIED\",\"message\":\"Access denied\"}" + ); + } + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "{\"code\":\"INTERNAL_ERROR\",\"message\":\"Internal server error\"}" + ); + }; + } + + public static Function graphqlJsonBodyExceptionMapping() { + return exception -> { + if (exception instanceof AuthenticationException) { + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_UNAUTHORIZED, + "{\"errors\":[{\"message\":\"Authentication required\",\"extensions\":{\"errorType\":\"AUTHENTICATION_REQUIRED\",\"classification\":\"UNAUTHENTICATED\",\"code\":\"AUTHENTICATION_ERROR\"}}]}" + ); + } + if (exception instanceof AccessDeniedException) { + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_FORBIDDEN, + "{\"errors\":[{\"message\":\"Access denied\",\"extensions\":{\"errorType\":\"ACCESS_DENIED\",\"classification\":\"FORBIDDEN\",\"code\":\"ACCESS_DENIED\"}}]}" + ); + } + return new ErrorResponseWritingConsumer.ErrorResponse( + HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "{\"errors\":[{\"message\":\"Internal server error\",\"extensions\":{\"errorType\":\"INTERNAL_SERVER_ERROR\",\"classification\":\"INTERNAL_ERROR\",\"code\":\"INTERNAL_ERROR\"}}]}" + ); + }; + } + + +} diff --git a/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/UrlMatchingPredicate.java b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/UrlMatchingPredicate.java new file mode 100644 index 0000000..cd48880 --- /dev/null +++ b/spring-security-exception-handler/src/main/java/dev/clutcher/security/handler/functions/UrlMatchingPredicate.java @@ -0,0 +1,25 @@ +package dev.clutcher.security.handler.functions; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.util.AntPathMatcher; +import org.springframework.util.PathMatcher; + +import java.util.List; +import java.util.function.Predicate; + +public class UrlMatchingPredicate implements Predicate { + + private static final PathMatcher PATH_MATCHER = new AntPathMatcher(); + + private final List urlPatterns; + + public UrlMatchingPredicate(List urlPatterns) { + this.urlPatterns = urlPatterns; + } + + public boolean test(HttpServletRequest request) { + String requestUri = request.getRequestURI(); + return urlPatterns.stream().anyMatch(pattern -> PATH_MATCHER.match(pattern, requestUri)); + } + +} diff --git a/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/SpringSecurityExceptionHandlerBuilderTest.java b/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/SpringSecurityExceptionHandlerBuilderTest.java new file mode 100644 index 0000000..b3cb301 --- /dev/null +++ b/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/SpringSecurityExceptionHandlerBuilderTest.java @@ -0,0 +1,50 @@ +package dev.clutcher.security.handler; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.IOException; +import java.util.function.BiConsumer; +import java.util.function.Predicate; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class SpringSecurityExceptionHandlerBuilderTest { + + @Mock + private HttpServletRequest request; + + @Mock + private Predicate canHandlePredicate; + + @Mock + private BiConsumer handleFunction; + + @Test + void shouldCreateHandlerInstance() { + // Given + when(canHandlePredicate.test(request)).thenReturn(true); + + // When + SpringSecurityExceptionHandler handler = SpringSecurityExceptionHandlerBuilder.builder() + .canHandle(canHandlePredicate) + .handle(handleFunction) + .order(42) + .build(); + + // Then + boolean canHandle = handler.canHandle(request); + assertTrue(canHandle); + + int order = handler.getOrder(); + assertEquals(42, order); + } + +} diff --git a/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/GraphqlJsonBodyExceptionMappingTest.java b/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/GraphqlJsonBodyExceptionMappingTest.java new file mode 100644 index 0000000..9f67a7f --- /dev/null +++ b/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/GraphqlJsonBodyExceptionMappingTest.java @@ -0,0 +1,59 @@ +package dev.clutcher.security.handler.functions; + +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.Test; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.AuthenticationException; + +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GraphqlJsonBodyExceptionMappingTest { + + @Test + void shouldConvertAuthenticationException() { + // Given + Function mapper = + ExceptionMappingFunctions.graphqlJsonBodyExceptionMapping(); + AuthenticationException exception = new BadCredentialsException("Invalid credentials"); + + // When + ErrorResponseWritingConsumer.ErrorResponse response = mapper.apply(exception); + + // Then + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.status()); + assertEquals("{\"errors\":[{\"message\":\"Authentication required\",\"extensions\":{\"errorType\":\"AUTHENTICATION_REQUIRED\",\"classification\":\"UNAUTHENTICATED\",\"code\":\"AUTHENTICATION_ERROR\"}}]}", response.body()); + } + + @Test + void shouldConvertAccessDeniedException() { + // Given + Function mapper = + ExceptionMappingFunctions.graphqlJsonBodyExceptionMapping(); + AccessDeniedException exception = new AccessDeniedException("Access denied"); + + // When + ErrorResponseWritingConsumer.ErrorResponse response = mapper.apply(exception); + + // Then + assertEquals(HttpServletResponse.SC_FORBIDDEN, response.status()); + assertEquals("{\"errors\":[{\"message\":\"Access denied\",\"extensions\":{\"errorType\":\"ACCESS_DENIED\",\"classification\":\"FORBIDDEN\",\"code\":\"ACCESS_DENIED\"}}]}", response.body()); + } + + @Test + void shouldConvertNonSpringSecurityException() { + // Given + Function mapper = + ExceptionMappingFunctions.graphqlJsonBodyExceptionMapping(); + RuntimeException exception = new RuntimeException("Some error"); + + // When + ErrorResponseWritingConsumer.ErrorResponse response = mapper.apply(exception); + + // Then + assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.status()); + assertEquals("{\"errors\":[{\"message\":\"Internal server error\",\"extensions\":{\"errorType\":\"INTERNAL_SERVER_ERROR\",\"classification\":\"INTERNAL_ERROR\",\"code\":\"INTERNAL_ERROR\"}}]}", response.body()); + } +} \ No newline at end of file diff --git a/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/JsonBodyExceptionMappingTest.java b/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/JsonBodyExceptionMappingTest.java new file mode 100644 index 0000000..a06cc1a --- /dev/null +++ b/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/JsonBodyExceptionMappingTest.java @@ -0,0 +1,59 @@ +package dev.clutcher.security.handler.functions; + +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.Test; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.AuthenticationException; + +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class JsonBodyExceptionMappingTest { + + @Test + void shouldConvertAuthenticationException() { + // Given + Function mapper = + ExceptionMappingFunctions.jsonBodyExceptionMapping(); + AuthenticationException exception = new BadCredentialsException("Invalid credentials"); + + // When + ErrorResponseWritingConsumer.ErrorResponse response = mapper.apply(exception); + + // Then + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.status()); + assertEquals("{\"code\":\"AUTHENTICATION_ERROR\",\"message\":\"Authentication required\"}", response.body()); + } + + @Test + void shouldConvertAccessDeniedException() { + // Given + Function mapper = + ExceptionMappingFunctions.jsonBodyExceptionMapping(); + AccessDeniedException exception = new AccessDeniedException("Access denied"); + + // When + ErrorResponseWritingConsumer.ErrorResponse response = mapper.apply(exception); + + // Then + assertEquals(HttpServletResponse.SC_FORBIDDEN, response.status()); + assertEquals("{\"code\":\"ACCESS_DENIED\",\"message\":\"Access denied\"}", response.body()); + } + + @Test + void shouldConvertNonSpringSecurityException() { + // Given + Function mapper = + ExceptionMappingFunctions.jsonBodyExceptionMapping(); + RuntimeException exception = new RuntimeException("Some error"); + + // When + ErrorResponseWritingConsumer.ErrorResponse response = mapper.apply(exception); + + // Then + assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.status()); + assertEquals("{\"code\":\"INTERNAL_ERROR\",\"message\":\"Internal server error\"}", response.body()); + } +} \ No newline at end of file diff --git a/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/UrlMatchingPredicateTest.java b/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/UrlMatchingPredicateTest.java new file mode 100644 index 0000000..793b69a --- /dev/null +++ b/spring-security-exception-handler/src/test/java/dev/clutcher/security/handler/functions/UrlMatchingPredicateTest.java @@ -0,0 +1,92 @@ +package dev.clutcher.security.handler.functions; + +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UrlMatchingPredicateTest { + + @Mock + private HttpServletRequest request; + + @Test + void shouldNotMatchAnyUrlWhenNoPatternsAreGiven() { + // Given + UrlMatchingPredicate predicate = new UrlMatchingPredicate(Collections.emptyList()); + when(request.getRequestURI()).thenReturn("/api/users"); + + // When + boolean result = predicate.test(request); + + // Then + assertFalse(result); + } + + @Test + void shouldMatchWhenExactPatternIsUsed() { + // Given + UrlMatchingPredicate predicate = new UrlMatchingPredicate(List.of("/api/users")); + when(request.getRequestURI()).thenReturn("/api/users"); + + // When + boolean result = predicate.test(request); + + // Then + assertTrue(result); + } + + @Test + void shouldMatchWhenWildcardPatternIsUsed() { + // Given + UrlMatchingPredicate predicate = new UrlMatchingPredicate(List.of("/api/**")); + when(request.getRequestURI()).thenReturn("/api/users/123"); + + // When + boolean result = predicate.test(request); + + // Then + assertTrue(result); + } + + @Test + void shouldMatchWhenMultipleMatchersProvided() { + // Given + UrlMatchingPredicate predicate = new UrlMatchingPredicate( + Arrays.asList("/api/users/**", "/api/products/**", "/graphql") + ); + when(request.getRequestURI()).thenReturn("/graphql"); + + // When + boolean result = predicate.test(request); + + // Then + assertTrue(result); + } + + @Test + void shouldNotMatch() { + // Given + UrlMatchingPredicate predicate = new UrlMatchingPredicate( + Arrays.asList("/api/users/**", "/api/products/**", "/graphql") + ); + when(request.getRequestURI()).thenReturn("/api/orders/789"); + + // When + boolean result = predicate.test(request); + + // Then + assertFalse(result); + } + +}