From b7372c54a6cc323ccae3a8135a5ff0d22fa57d62 Mon Sep 17 00:00:00 2001 From: hamdirahalpartner-del Date: Wed, 18 Nov 2026 14:26:37 +0100 Subject: [PATCH] refactor(idp-core)!: migrate API errors to RFC 7807 ProblemDetail Signed-off-by: hamdirahalpartner-del --- .../scripts/check_flyway_migration_order.sh | 24 +- .github/scripts/check_navigation.sh | 6 +- .github/scripts/extract_specs.sh | 8 +- .github/scripts/summarize_owasp.sh | 8 +- .github/workflows/basic_code_checks.yml | 28 +- .github/workflows/build_and_push.yml | 4 +- .github/workflows/copilot-setup-steps.yml | 6 +- .github/workflows/deploy_docs.yml | 4 +- .github/workflows/lint_pull_request_title.yml | 2 +- .github/workflows/zap_security_check.yml | 4 +- .github/workflows/zap_security_report.yml | 2 +- .gitignore | 2 +- .mvn/wrapper/maven-wrapper.properties | 7 +- Dockerfile | 19 +- docs/src/concepts/authentication.md | 1028 ++++---------- docs/src/concepts/entities.md | 24 + docs/src/concepts/entity-filtering.md | 8 +- docs/src/concepts/entity-templates.md | 3 + docs/src/concepts/relations.md | 8 + .../src/contributing/code/code-conventions.md | 19 +- .../code/domain-infrastructure.md | 6 +- .../contributing/code/exception-handling.md | 50 +- docs/src/deployment/configuration.md | 50 +- docs/src/deployment/docker.md | 108 +- docs/src/deployment/observability.md | 366 ++--- docs/src/features/data-integration.md | 8 +- docs/src/features/entity-dynamic-mapping.md | 15 + docs/src/features/webhooks.md | 51 +- docs/src/getting-started/configuration.md | 14 +- docs/src/static/swagger.yaml | 917 +++++++------ docs/uv.lock | 25 +- flyway-migration-order-report.md | 0 mvnw | 8 +- mvnw.cmd | 412 +++--- pom.xml | 66 +- .../domain/constant/JsltConstraints.java | 21 + .../domain/constant/SearchConstraints.java | 10 +- .../domain/constant/ValidationMessages.java | 14 +- .../PrincipalNotAuthorizedException.java | 22 + .../authorization/AuthorizationAction.java | 6 + .../authorization/AuthorizationMode.java | 6 + .../authorization/AuthorizationPolicy.java | 23 + .../authorization/AuthorizationRequest.java | 26 + .../authorization/AuthorizationResource.java | 28 + .../enums/RelationTargetValidationMode.java | 10 + .../webhook/WebhookSecurity.java | 5 +- .../WebhookSecurityValidationPolicy.java | 7 + .../model/search/PaginationCriteria.java | 28 + .../domain/model/search/SortCriteria.java | 9 + .../port/audit/AuditIdentityProviderPort.java | 15 + .../GlobalAuthorizationService.java | 84 ++ .../service/entity/EntityAuditService.java | 2 - .../domain/service/entity/EntityService.java | 63 +- .../entity/EntityValidationService.java | 26 +- .../entity_graph/EntityGraphService.java | 28 +- .../PrincipalProvisioningService.java | 53 +- .../relation/RelationValidationService.java | 263 +++- .../service/search/SortParameterParser.java | 58 + .../webhook/WebhookConnectorService.java | 14 +- .../WebhookConnectorValidationService.java | 6 +- .../WebhookSecurityValidationService.java | 19 +- .../api/auth/AuthorizationRequestFactory.java | 114 ++ .../adapters/api/auth/AuthorizedResource.java | 25 + .../api/auth/GlobalAuthorizationFilter.java | 130 ++ .../api/auth/JitProvisioningFilter.java | 128 +- .../api/auth/ProvisionedPrincipalContext.java | 13 + .../adapters/api/auth/RequestAuthorizer.java | 63 + .../api/auth/UnifiedUserProvider.java | 44 +- .../api/auth/UserIdentityProvider.java | 6 - .../AuthenticationProperties.java | 85 +- .../AuthorizationConfiguration.java | 43 + .../AuthorizationProperties.java | 24 + .../api/configuration/JwtConfiguration.java | 59 +- .../PrincipalExtractionProperties.java | 43 + .../PrincipalProvisioningMode.java | 6 + .../PrincipalProvisioningProperties.java | 12 + .../RelationValidationConfiguration.java | 24 + .../RelationValidationProperties.java | 12 + .../api/configuration/SearchProperties.java | 20 + .../configuration/SecurityConfiguration.java | 15 +- .../configuration/SecurityRoleProperties.java | 20 - .../configuration/SwaggerConfiguration.java | 31 + .../api/configuration/SwaggerDescription.java | 25 +- .../ValidatingPageableArgumentResolver.java | 63 + .../api/configuration/WebConfiguration.java | 19 + .../FallbackDenyAllFilterChainConfig.java | 67 + .../security/chains/JwtFilterChainConfig.java | 7 +- .../chains/MockFilterChainConfig.java | 27 +- .../chains/OAuth2LoginFilterChainConfig.java | 9 +- .../api/controller/AuditController.java | 16 +- .../api/controller/EntityController.java | 109 +- .../EntityDynamicMappingController.java | 59 +- .../api/controller/EntityGraphController.java | 9 +- .../controller/EntityTemplateController.java | 33 +- ...InboundWebhookConfigurationController.java | 17 +- .../api/controller/PrincipalController.java | 16 +- .../api/dto/in/EntitySearchRequestDtoIn.java | 7 +- .../InboundWebhookSecurityContractDtoIn.java | 13 +- .../api/dto/out/entity/EntitySummaryDto.java | 20 +- .../MissingPrincipalIdentifierException.java | 22 + .../api/handler/ApiErrorResponseWriter.java | 55 + .../api/handler/ApiExceptionHandler.java | 839 ++++-------- .../webhook/InboundWebhookMapper.java | 17 +- .../EntityDtoOutFromEntityNodeMapper.java | 56 +- .../entity_template/EntityTemplateMapper.java | 1 - .../api/principal/PrincipalExtractor.java | 22 +- .../JwtPrincipalExtractionStrategy.java | 214 +-- ...OAuth2UserPrincipalExtractionStrategy.java | 22 +- .../entity_mapping/jslt/JsltEngine.java | 53 +- .../jslt/JsltMappingEngineAdapter.java | 47 +- .../configuration/IngestionConstants.java | 11 +- .../WebhookExceptionHandlerHelper.java | 54 +- .../processor/IngestionProcessor.java | 33 +- .../processor/SecurityProcessor.java | 34 +- .../security/JwtBearerSecurityValidator.java | 55 +- .../WebhookSecurityConfiguration.java | 11 +- .../security/WebhookSecurityProperties.java | 6 +- .../persistence/PostgresEntityAdapter.java | 32 +- .../audit/UserIdentityProviderHolder.java | 14 +- src/main/resources/application-local.yml | 28 +- src/main/resources/application.yml | 102 +- ...add_entity_relations_relation_id_index.sql | 6 + .../idp_core/AbstractIntegrationTest.java | 21 +- .../idp_core/SecurityConfigurationTest.java | 23 +- .../HexagonalArchitectureTest.java | 2 +- .../MaintainabilityArchitectureTest.java | 39 + .../GlobalAuthorizationServiceTest.java | 367 +++++ .../service/entity/EntityServiceTest.java | 116 +- .../entity/EntityValidationServiceTest.java | 40 +- .../entity_graph/EntityGraphServiceTest.java | 29 + .../principal/PrincipalExtractorTest.java | 361 ++--- .../PrincipalProvisioningServiceTest.java | 54 +- .../RelationValidationServiceTest.java | 216 ++- .../search/SortParameterParserTest.java | 65 + .../webhook/WebhookConnectorServiceTest.java | 7 +- ...WebhookConnectorValidationServiceTest.java | 35 +- .../WebhookSecurityValidationServiceTest.java | 70 +- .../auth/AuthorizationRequestFactoryTest.java | 96 ++ .../auth/GlobalAuthorizationFilterTest.java | 222 +++ .../api/auth/JitProvisioningFilterTest.java | 224 ++- .../api/auth/TestHandlerMappings.java | 40 + .../api/auth/UnifiedUserProviderTest.java | 97 +- .../AuthenticationPropertiesTest.java | 30 + .../AuthorizationConfigurationTest.java | 49 + .../configuration/JwtConfigurationTest.java | 73 + .../PrincipalExtractionPropertiesTest.java | 49 + .../RelationValidationConfigurationTest.java | 47 + .../SecurityRolePropertiesTest.java | 34 - .../SwaggerConfigurationTest.java | 163 +++ .../FallbackDenyAllFilterChainConfigTest.java | 62 + .../chains/JwtFilterChainConfigTest.java | 22 + .../chains/MockFilterChainConfigTest.java | 23 +- .../OAuth2LoginFilterChainConfigTest.java | 23 + .../chains/PublicFilterChainConfigTest.java | 5 +- .../api/controller/AuditControllerTest.java | 21 +- .../api/controller/EntityControllerTest.java | 298 +++- .../EntityDynamicMappingControllerTest.java | 177 ++- ...namicMappingDeletionAuthorizationTest.java | 97 ++ .../EntityTemplateControllerTest.java | 187 ++- ...nboundWebhookManagementControllerTest.java | 181 ++- .../controller/PrincipalControllerTest.java | 18 +- .../handler/ApiErrorResponseWriterTest.java | 47 + .../api/handler/ApiExceptionHandlerTest.java | 1213 +++++++++-------- .../EntityDtoOutFromEntityNodeMapperTest.java | 67 + .../webhook/InboundWebhookMapperTest.java | 100 +- .../entity_mapping/jslt/JsltEngineTest.java | 97 ++ .../jslt/JsltMappingEngineAdapterTest.java | 45 + .../InboundWebhookIngestionRouteTest.java | 61 +- .../WebhookExceptionHandlerHelperTest.java | 65 + .../processor/IngestionProcessorTest.java | 41 + .../JwtBearerSecurityValidatorTest.java | 53 +- .../WebhookJwtDecoderProviderTest.java | 4 +- .../PostgresEntityAdapterTest.java | 23 + .../audit/CustomRevisionListenerTest.java | 4 +- .../audit/UserIdentityProviderHolderTest.java | 45 +- src/test/resources/application-test.yml | 21 +- .../db/test/R__1_Insert_test_data.sql | 6 +- .../R__6_insert_principal_user_for_test.sql | 52 + ...ity_optional_missing_relation_target.json} | 0 179 files changed, 8538 insertions(+), 4412 deletions(-) delete mode 100644 flyway-migration-order-report.md create mode 100644 src/main/java/com/decathlon/idp_core/domain/constant/JsltConstraints.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/exception/authorization/PrincipalNotAuthorizedException.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationAction.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationMode.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationPolicy.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationRequest.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationResource.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/model/enums/RelationTargetValidationMode.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/model/inbound_connectors/webhook/WebhookSecurityValidationPolicy.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/model/search/SortCriteria.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/port/audit/AuditIdentityProviderPort.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/service/authorization/GlobalAuthorizationService.java create mode 100644 src/main/java/com/decathlon/idp_core/domain/service/search/SortParameterParser.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizationRequestFactory.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizedResource.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilter.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/ProvisionedPrincipalContext.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/RequestAuthorizer.java delete mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UserIdentityProvider.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationConfiguration.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationProperties.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalExtractionProperties.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalProvisioningMode.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalProvisioningProperties.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationConfiguration.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationProperties.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SearchProperties.java delete mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityRoleProperties.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/ValidatingPageableArgumentResolver.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/FallbackDenyAllFilterChainConfig.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/exception/MissingPrincipalIdentifierException.java create mode 100644 src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiErrorResponseWriter.java create mode 100644 src/main/resources/db/migration/V7_2__add_entity_relations_relation_id_index.sql create mode 100644 src/test/java/com/decathlon/idp_core/domain/service/authorization/GlobalAuthorizationServiceTest.java create mode 100644 src/test/java/com/decathlon/idp_core/domain/service/search/SortParameterParserTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizationRequestFactoryTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilterTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/TestHandlerMappings.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthenticationPropertiesTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationConfigurationTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/JwtConfigurationTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalExtractionPropertiesTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationConfigurationTest.java delete mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityRolePropertiesTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerConfigurationTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/FallbackDenyAllFilterChainConfigTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingDeletionAuthorizationTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiErrorResponseWriterTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity/EntityDtoOutFromEntityNodeMapperTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltEngineTest.java create mode 100644 src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/exception_handler/WebhookExceptionHandlerHelperTest.java create mode 100644 src/test/resources/db/test/R__6_insert_principal_user_for_test.sql rename src/test/resources/integration_test/json/entity/v1/{postEntity_400_relation_target_entity_does_not_exist.json => postEntity_optional_missing_relation_target.json} (100%) diff --git a/.github/scripts/check_flyway_migration_order.sh b/.github/scripts/check_flyway_migration_order.sh index b8a7a019..349ddd24 100755 --- a/.github/scripts/check_flyway_migration_order.sh +++ b/.github/scripts/check_flyway_migration_order.sh @@ -58,7 +58,7 @@ MODIFIED_FILES=$(git diff --name-only --diff-filter=M "$BASE_REF" HEAD -- "$MIGR BASE_MAX_FILE="" BASE_MAX_KEY="0" while IFS= read -r file; do - [ -z "$file" ] && continue + [[ -z "$file" ]] && continue if [[ ! $(basename "$file") =~ $NAME_PATTERN ]]; then continue fi @@ -69,13 +69,13 @@ while IFS= read -r file; do fi done <<< "$BASE_FILES" -if [ -n "$BASE_MAX_FILE" ]; then +if [[ -n "$BASE_MAX_FILE" ]]; then printf -- "Highest migration on %s: %s (version %s)\n" "$BASE_REF" "$(basename "$BASE_MAX_FILE")" "$(version_label "$BASE_MAX_FILE")" else printf -- "No migration found on %s\n" "$BASE_REF" fi -if [ -z "$ADDED_FILES" ] && [ -z "$DELETED_FILES" ] && [ -z "$MODIFIED_FILES" ]; then +if [[ -z "$ADDED_FILES" ]] && [[ -z "$DELETED_FILES" ]] && [[ -z "$MODIFIED_FILES" ]]; then printf -- "No migration change detected in this pull request.\n" : > "$REPORT_FILE" exit 0 @@ -83,13 +83,13 @@ fi # Rule 1: an already merged migration must never be modified or deleted while IFS= read -r file; do - [ -z "$file" ] && continue + [[ -z "$file" ]] && continue ERRORS+=("\`$file\` is modified. A migration already merged on \`$BASE_REF\` has been applied on running environments: its checksum is frozen. Create a new migration instead.") EXIT_CODE=1 done <<< "$MODIFIED_FILES" while IFS= read -r file; do - [ -z "$file" ] && continue + [[ -z "$file" ]] && continue ERRORS+=("\`$file\` is deleted or renamed. A migration already merged on \`$BASE_REF\` must be kept as is. Create a new migration instead.") EXIT_CODE=1 done <<< "$DELETED_FILES" @@ -97,7 +97,7 @@ done <<< "$DELETED_FILES" # Rule 2: added migrations must be well named and strictly above the highest merged version SEEN_KEYS=() while IFS= read -r file; do - [ -z "$file" ] && continue + [[ -z "$file" ]] && continue name=$(basename "$file") if [[ ! $name =~ $NAME_PATTERN ]]; then @@ -109,14 +109,14 @@ while IFS= read -r file; do key=$(version_key "$file") label=$(version_label "$file") - if [ -n "$BASE_MAX_FILE" ] && awk -v a="$key" -v b="$BASE_MAX_KEY" 'BEGIN { exit !(a <= b) }'; then + if [[ -n "$BASE_MAX_FILE" ]] && awk -v a="$key" -v b="$BASE_MAX_KEY" 'BEGIN { exit !(a <= b) }'; then ERRORS+=("\`$name\` (version \`$label\`) is lower than or equal to \`$(basename "$BASE_MAX_FILE")\` (version \`$(version_label "$BASE_MAX_FILE")\`) already merged on \`$BASE_REF\`. Renumber it above \`$(version_label "$BASE_MAX_FILE")\` so Flyway applies it on every environment.") EXIT_CODE=1 continue fi for seen in ${SEEN_KEYS[@]+"${SEEN_KEYS[@]}"}; do - if [ "${seen%%:*}" = "$key" ]; then + if [[ "${seen%%:*}" = "$key" ]]; then ERRORS+=("\`$name\` uses version \`$label\` already used by \`${seen#*:}\` in this pull request. Flyway versions must be unique.") EXIT_CODE=1 fi @@ -128,11 +128,11 @@ done <<< "$ADDED_FILES" # Build the markdown report { - if [ "$EXIT_CODE" -eq 0 ]; then + if [[ "$EXIT_CODE" -eq 0 ]]; then printf -- "No Flyway migration ordering issue detected.\n\n" printf -- "| Added migration | Version |\n|---|---|\n" while IFS= read -r file; do - [ -z "$file" ] && continue + [[ -z "$file" ]] && continue printf -- "| \`%s\` | \`%s\` |\n" "$(basename "$file")" "$(version_label "$file")" done <<< "$ADDED_FILES" else @@ -141,7 +141,7 @@ done <<< "$ADDED_FILES" printf -- "- %s\n" "$error" done printf -- "\nHighest migration currently on \`%s\`: " "$BASE_REF" - if [ -n "$BASE_MAX_FILE" ]; then + if [[ -n "$BASE_MAX_FILE" ]]; then printf -- "\`%s\`\n" "$(basename "$BASE_MAX_FILE")" else printf -- "none\n" @@ -151,7 +151,7 @@ done <<< "$ADDED_FILES" cat "$REPORT_FILE" -if [ "$EXIT_CODE" -ne 0 ]; then +if [[ "$EXIT_CODE" -ne 0 ]]; then for error in "${ERRORS[@]}"; do printf -- "::error:: %s\n" "$(printf -- '%s' "$error" | tr -d '`')" done diff --git a/.github/scripts/check_navigation.sh b/.github/scripts/check_navigation.sh index 0af04906..47c2d3e5 100755 --- a/.github/scripts/check_navigation.sh +++ b/.github/scripts/check_navigation.sh @@ -12,7 +12,7 @@ echo "🔍 Checking for broken navigation links in ${SITE_DIR}..." # Find files with 'none' placeholders in navigation while IFS= read -r file; do - if [ -n "$file" ]; then + if [[ -n "$file" ]]; then # Get line numbers where 'none' appears in md-ellipsis context line_nums=$(grep -n "^\s*none\s*$" "$file" | cut -d: -f1 2>/dev/null || true) @@ -39,7 +39,7 @@ while IFS= read -r file; do fi done < <(find "$SITE_DIR" -name "*.html" -type f) -if [ $EXIT_CODE -eq 0 ]; then +if [[ $EXIT_CODE -eq 0 ]]; then echo "✅ No broken navigation links found" else echo "" @@ -54,7 +54,7 @@ else # Try to find it in the source directory found_files=$(find "$SRC_DIR" -name "$filename" 2>/dev/null || true) - if [ -n "$found_files" ]; then + if [[ -n "$found_files" ]]; then echo "$found_files" | while read -r found; do echo " ❌ $found" done diff --git a/.github/scripts/extract_specs.sh b/.github/scripts/extract_specs.sh index 5ad8dea4..62cf84fd 100755 --- a/.github/scripts/extract_specs.sh +++ b/.github/scripts/extract_specs.sh @@ -13,7 +13,7 @@ PR_BRANCH=$(git rev-parse --abbrev-ref HEAD) git fetch origin main git checkout origin/main # 1. Check if the static swagger file exists on the 'main' branch -if [ -f "$MAIN_SWAGGER" ]; then +if [[ -f "$MAIN_SWAGGER" ]]; then # If it exists, copy it as the reference spec cp "$MAIN_SWAGGER" "specs/static-swagger-main.yaml" else @@ -22,7 +22,7 @@ else mvn clean package -B JAR_PATH=$(find target -maxdepth 1 -name "*.jar" | head -n 1) - if [ -z "$JAR_PATH" ]; then + if [[ -z "$JAR_PATH" ]]; then printf -- "::error:: No JAR found in target/ folder.\n" exit 1 fi @@ -39,7 +39,7 @@ else printf -- "Waiting for API endpoint (%s) to be reachable...\n" "$API_URL" - while [ "$ATTEMPT" -lt "$MAX_ATTEMPTS" ]; do + while [[ "$ATTEMPT" -lt "$MAX_ATTEMPTS" ]]; do # Use curl with --fail and --silent to check for a successful connection (HTTP 2xx response) if curl --fail --silent -o /dev/null "$API_URL"; then printf -- "API is up after %d seconds.\n" "$((ATTEMPT * SLEEP_TIME))" @@ -50,7 +50,7 @@ else ATTEMPT=$((ATTEMPT + 1)) done # Check if the maximum number of attempts was reached (timeout) - if [ "$ATTEMPT" -eq "$MAX_ATTEMPTS" ]; then + if [[ "$ATTEMPT" -eq "$MAX_ATTEMPTS" ]]; then printf -- "::error:: Application failed to start and expose Swagger endpoint after %d attempts.\n" "$MAX_ATTEMPTS" printf -- "Swagger endpoint unreachable. Dumping logs:\n" pgrep -a java || printf -- "No Java process found\n" diff --git a/.github/scripts/summarize_owasp.sh b/.github/scripts/summarize_owasp.sh index 561bc043..e2d740d6 100755 --- a/.github/scripts/summarize_owasp.sh +++ b/.github/scripts/summarize_owasp.sh @@ -6,19 +6,19 @@ SUMMARY_FILE="${GITHUB_STEP_SUMMARY:-/dev/stdout}" echo "### OWASP Dependency Check Summary" >> "$SUMMARY_FILE" SARIF_REPORT="" -if [ -f "$PWD/target/security-reports/dependency-check-report.sarif" ]; then +if [[ -f "$PWD/target/security-reports/dependency-check-report.sarif" ]]; then SARIF_REPORT="$PWD/target/security-reports/dependency-check-report.sarif" -elif [ -f "$PWD/target/dependency-check-report.sarif" ]; then +elif [[ -f "$PWD/target/dependency-check-report.sarif" ]]; then SARIF_REPORT="$PWD/target/dependency-check-report.sarif" fi -if [ -n "$SARIF_REPORT" ]; then +if [[ -n "$SARIF_REPORT" ]]; then echo "| Vulnerability | CVSS | Package |" >> "$SUMMARY_FILE" echo "|:--|:--:|:--|" >> "$SUMMARY_FILE" if command -v jq >/dev/null 2>&1; then VULN_COUNT=$(jq '.runs[].results | length' "$SARIF_REPORT" | awk '{s+=$1} END {print s}') - if [ "$VULN_COUNT" -gt 0 ]; then + if [[ "$VULN_COUNT" -gt 0 ]]; then jq -r '.runs[].results[] | [.ruleId, (.properties.cvssScore // "N/A"), (.message.text | split("\n")[0])] | @tsv' "$SARIF_REPORT" | while IFS=$'\t' read -r ruleId cvss message; do printf "| %s | %s | %s |\n" "$ruleId" "$cvss" "$message" >> "$SUMMARY_FILE" diff --git a/.github/workflows/basic_code_checks.yml b/.github/workflows/basic_code_checks.yml index 945ff648..0d0d63fb 100644 --- a/.github/workflows/basic_code_checks.yml +++ b/.github/workflows/basic_code_checks.yml @@ -24,7 +24,7 @@ jobs: - name: Lint GitHub Actions Workflows if: github.event_name == 'pull_request' - uses: reviewdog/action-actionlint@13465d022aa41c282f730be17574b5ce692d0186 # v1.78.1 + uses: reviewdog/action-actionlint@7abf25e1607ec65838b73d0484ff31f8e9499d80 # v1.81.2 with: github_token: ${{ secrets.GITHUB_TOKEN }} reporter: github-pr-review @@ -46,7 +46,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Java 25 - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: temurin java-version: 25 @@ -78,7 +78,7 @@ jobs: ${{ runner.os }}-maven- - name: Setup Java 25 - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: temurin java-version: 25 @@ -108,7 +108,7 @@ jobs: label: code-coverage/jacoco - name: Upload built jar - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: idp-core-jar path: target/ @@ -130,13 +130,13 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Download built jar - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: idp-core-jar path: target - name: Setup Java 25 - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: temurin java-version: 25 @@ -158,7 +158,7 @@ jobs: ${{ runner.os }}-owasp-dc-data- - name: Upload SpotBugs XML - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: spotbugs-report path: target/spotbugsXml.xml @@ -192,13 +192,13 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Download built jar - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: idp-core-jar path: target - name: Setup Java 25 - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: temurin java-version: 25 @@ -213,7 +213,7 @@ jobs: SPRING_JPA_DATABASE_PLATFORM: 'org.hibernate.dialect.H2Dialect' SPRING_FLYWAY_ENABLED: 'false' SPRING_JPA_HIBERNATE_DDL_AUTO: 'none' - SPRING_DATASOURCE_URL: 'jdbc:h2:mem' + SPRING_DATASOURCE_URL: 'jdbc:h2:mem:idp_core;DB_CLOSE_DELAY=-1' SPRING_DATASOURCE_DRIVER_CLASS_NAME: 'org.h2.Driver' run: | mkdir -p specs @@ -231,7 +231,7 @@ jobs: kill "$API_PID" - name: Upload static swagger declared by developer - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: swagger-declared path: specs @@ -261,14 +261,14 @@ jobs: fetch-depth: 0 - name: Setup Java 25 - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: temurin java-version: 25 cache: maven - name: Download swagger declared artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: swagger-declared path: specs @@ -452,7 +452,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Download built jar - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: idp-core-jar path: target diff --git a/.github/workflows/build_and_push.yml b/.github/workflows/build_and_push.yml index f2df7fc0..a3dbfd3a 100644 --- a/.github/workflows/build_and_push.yml +++ b/.github/workflows/build_and_push.yml @@ -24,7 +24,7 @@ jobs: fetch-depth: 0 ref: ${{ github.event.release.tag_name || github.event.inputs.tag_name }} - name: Set up JDK 25 - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: 'temurin' java-version: 25 @@ -34,7 +34,7 @@ jobs: id: compile run: mvn clean verify - name: Login to Docker Hub - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index e0553814..b7843ebb 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -23,19 +23,19 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Java 25 - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: temurin java-version: 25 cache: maven - name: Set up Python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.14' - name: Install uv - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: enable-cache: false diff --git a/.github/workflows/deploy_docs.yml b/.github/workflows/deploy_docs.yml index 703d137a..21d99134 100644 --- a/.github/workflows/deploy_docs.yml +++ b/.github/workflows/deploy_docs.yml @@ -35,12 +35,12 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up Python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.14' - name: Install uv - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: enable-cache: false diff --git a/.github/workflows/lint_pull_request_title.yml b/.github/workflows/lint_pull_request_title.yml index 993b1c34..62a0e7b3 100644 --- a/.github/workflows/lint_pull_request_title.yml +++ b/.github/workflows/lint_pull_request_title.yml @@ -20,7 +20,7 @@ jobs: steps: - name: Check PR title convention - uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6.1.1 + uses: amannn/action-semantic-pull-request@2252a14e810aa9b85c2d560bd7070c802206ecf6 # v6.1.2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: diff --git a/.github/workflows/zap_security_check.yml b/.github/workflows/zap_security_check.yml index 5bc080a0..5642399c 100644 --- a/.github/workflows/zap_security_check.yml +++ b/.github/workflows/zap_security_check.yml @@ -56,7 +56,7 @@ jobs: # Step B: Setup JDK - name: Setup Java 25 - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: 'temurin' java-version: '25' @@ -78,7 +78,7 @@ jobs: echo "${{ github.event.issue.number }}" > target/zap-reports/pr_number.txt - name: Upload ZAP Report Artifact if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: zap-scan-report path: target/zap-reports/ diff --git a/.github/workflows/zap_security_report.yml b/.github/workflows/zap_security_report.yml index aabe6a60..f1d8c964 100644 --- a/.github/workflows/zap_security_report.yml +++ b/.github/workflows/zap_security_report.yml @@ -20,7 +20,7 @@ jobs: steps: - name: Download ZAP Report Artifact if: github.event.workflow_run.event == 'issue_comment' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: zap-scan-report path: zap-reports diff --git a/.gitignore b/.gitignore index fee3e653..46a6e700 100644 --- a/.gitignore +++ b/.gitignore @@ -44,7 +44,7 @@ buildNumber.properties .env application-secret.* - +flyway-migration-order-report.md # BlueJ files *.ctxt diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 308007b5..c179c80b 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,2 +1,5 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar +wrapperVersion=3.3.4 +distributionType=bin +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.10.0/apache-maven-3.10.0-bin.zip +distributionSha256Sum=1f6d9909266510f039f59aa0e13dcd2c66da85f043e56276e41f2918f8bddaff +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar diff --git a/Dockerfile b/Dockerfile index 7dd4bd05..e36042e2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,15 +1,18 @@ -FROM eclipse-temurin:25-jre-alpine +FROM eclipse-temurin:25-jre-jammy -ENV PORT=8080 +ENV SERVER_PORT=8080 \ + PORT=8080 -RUN apk add --no-cache shadow && \ - groupadd -r idp-core-group && \ - useradd --no-log-init -r -g idp-core-group idp-core-user && \ - apk del shadow +WORKDIR /opt -USER idp-core-user:idp-core-group +RUN groupadd -r -g 1001 idp-core-group && \ + useradd -r -u 1001 -g idp-core-group -s /bin/false idp-core-user -WORKDIR /opt COPY ./target/idp-core*.jar /opt/app.jar +USER 1001:1001 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=25s --retries=3 \ + CMD wget -q --spider "http://localhost:${SERVER_PORT}/actuator/health" || exit 1 + ENTRYPOINT ["java", "-jar", "/opt/app.jar"] diff --git a/docs/src/concepts/authentication.md b/docs/src/concepts/authentication.md index 15de6cf7..5a841b3a 100644 --- a/docs/src/concepts/authentication.md +++ b/docs/src/concepts/authentication.md @@ -1,897 +1,405 @@ --- -title: Authentication and Security Filters -description: Learn how authentication, security filters, and JWT claim mappings work in IDP-Core. Understand the filter chain architecture and how to add custom authentication methods. +title: Authentication and Authorization +description: Supported authentication modes, how to enable them, what a principal is, how principals are provisioned, and how authorization works. --- -IDP-Core implements a flexible, modular authentication system based on Spring Security's filter chain architecture. This -document explains how the system works, how to configure it for different Identity Providers, and how to extend it with -custom authentication methods. - -## Architecture Overview - -The authentication system consists of four main components working together: +IDP-Core separates three concerns. **Authentication** proves who calls the API. **Principal provisioning** turns that +identity into a catalog record. **Authorization** decides what that principal can do. ```mermaid -graph LR - A["HTTP Request"] --> B["Security Filter Chain"] - B --> C["Authentication Filter
JWT/API Key/Mock"] - C --> D["PrincipalExtractor
Strategy Pattern"] - D --> E["JitProvisioningFilter
Auto-Provisioning"] - E --> F["Domain Service
Authorization"] - F --> G["Controller
Business Logic"] -``` - -- **Security Filter Chain**: Routes requests through configured authentication mechanisms in order -- **Authentication Filters**: Extract credentials (JWT tokens, API keys, etc.) and create `Authentication` objects -- **Principal Extractor**: Converts authentication tokens into domain `PrincipalInfo` objects -- **JIT Provisioning Filter**: Automatically creates principals in the database on first authentication -- **Domain Services**: Enforce business rules and authorization checks - -## Filter Chain Architecture - -IDP-Core uses a **multi-chain architecture** where each authentication mechanism has its own dedicated -`SecurityFilterChain` with a specific `@Order`. This allows: - -- **Independent configuration** of each mechanism without interference -- **Environment-specific activation** using `@ConditionalOnProperty` -- **Clear precedence rules** via ordering (lower numbers evaluate first) -- **Flexible extensibility** for adding new mechanisms - -### Filter Chain Ordering - -Chains are evaluated in strict order of `@Order` value: - -| Order | Chain | Purpose | -|-------|-----------------------------------------|-------------------------------------------------------------------------| -| 1 | `PublicFilterChainConfig` | Permits public paths without authentication (actuator, swagger, health) | -| 2 | `JwtFilterChainConfig` | OAuth2 resource server with JWT validation | -| 3 | `ApiKeyFilterChainConfig` | Simple API key authentication for webhooks and service-to-service | -| 4+ | Future / Other authentication mechanism | Your custom authentication mechanisms | -| last | `MockFilterChainConfig` | Local development only - generates mock JWT tokens | - -When a request arrives, Spring Security evaluates chains in order. The first chain whose `securityMatcher` matches the -request path handles that request. If no `securityMatcher` is specified, the chain protects all remaining unmatched -paths. - -### Public Filter Chain (Order 1) - -```java - -@Configuration -@Order(1) -public class PublicFilterChainConfig { - @Bean - public SecurityFilterChain publicFilterChain(HttpSecurity http) throws Exception { - http.securityMatcher("/", "/actuator/**", "/swagger-ui/**", "/v3/api-docs/**") - .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) - .csrf(csrf -> csrf.disable()); - return http.build(); - } -} +flowchart LR + A[HTTP request] --> B[Authentication mode
JWT / OAuth2 login / Mock] + B --> C[Principal extraction
PrincipalInfo] + C --> D[Provisioning
JIT or LINK_ONLY] + D --> E[Global authorization
policy] + E --> F[Controller] ``` -The public chain explicitly permits these paths without any authentication. All other paths fall through to subsequent -chains. - -### JWT Filter Chain (Order 2) - -The JWT chain provides OAuth2 resource server authentication: - -- Expects JWT tokens in the `Authorization: Bearer ` header -- Validates token signature using the configured JWKS endpoint -- Extracts claims and creates `JwtAuthenticationToken` -- Invokes claim mapping to standardize different IdP claim names -- Applies service account detection to classify M2M vs. human users +## Authentication modes -## JWT Claim Mappings +Each mode has its own `SecurityFilterChain` that you enable with a property. Public paths (health, Swagger, API docs) +bypass authentication. -Different Identity Providers (IdPs) use different claim names in their JWT tokens for the same semantic meaning. The -claim mapping system allows you to configure these differences without code changes. +| Mode | Enable with | Use for | +| ------------------------------------------- | -------------------------------------------------- | --------------------------------- | +| [JWT resource server](#jwt-resource-server) | `app.security.authentication.jwt.enabled` | Production API calls (users, M2M) | +| [OAuth2 login](#oauth2-login) | `app.security.authentication.oauth2-login.enabled` | Browser login, for example GitHub | +| [Mock](#mock-authentication) | `app.security.authentication.mock.enabled` | Local development only | +| [API key](#api-key) | `app.security.authentication.api-key.enabled` | Not usable yet (placeholder) | -### Optional Claim Mapping Configuration - -Configure claim mappings in `application.yml` under `app.security.authentication.user-claim-mappings`: -When JWT authentication is enabled, only these two pieces of information are -mandatory: +> [!WARNING] +> Never enable mock authentication in production. It skips all token validation. -- spring.security.oauth2.resourceserver.jwt.jwk-set-uri required for signature validation. -- A valid JWT signature and standard sub claim, sub is effectively required for JIT provisioning because it is the final identifier fallback. +### JWT resource server -When `app.security.authentication.jwt.enabled` is `false`, the JWT decoder and -JWT filter chain are not created, so `OAUTH_JWK_URI` is not required. Swagger -can be disabled independently with `app.security.swagger.enabled=false`; when -enabled without OAuth configuration, it publishes only the available security -schemes. +The JWT chain validates `Authorization: Bearer ` requests as an OAuth2 resource server. It validates the +signature against the identity provider (IdP) JWKS endpoint, then hands the token to principal extraction. -```yaml -app: +```yaml title="application.yml" +spring: security: - authentication: - user-claim-mappings: - sub: "sub" # Unique user identifier - Mandatory - preferred_username: "preferred_username" # Human-readable username - name: "name" # Display name - email: "email" # Email address - groups: "groups" # Group memberships - client_id: "client_id" # OAuth2 client identifier - azp: "azp" # Authorized party (alternative client ID) - grant_type: "grant_type" # OAuth2 grant type - gty: "gty" # Grant type variant - service_name: "service_name" # Custom M2M service identifier -``` - -### Common IdP Configurations - -=== "Auth0" + oauth2: + resourceserver: + jwt: + jwk-set-uri: ${OAUTH_JWK_URI} -```yaml app: security: authentication: - user-claim-mappings: - sub: "sub" - preferred_username: "preferred_username" - name: "name" - email: "email" - groups: "groups" - client_id: "client_id" - azp: "azp" - grant_type: "grant_type" - gty: "gty" - service_name: "service_name" + jwt: + enabled: true + issuer-uri: ${OAUTH_ISSUER_URI:} + audiences: ${OAUTH_AUDIENCES:} ``` -=== "Keycloak" +A valid signature only proves that the token comes from your identity provider. Set `OAUTH_ISSUER_URI` to the expected +`iss` claim and `OAUTH_AUDIENCES` to a comma-separated list of accepted `aud` values so that IDP-Core rejects tokens +issued for other applications of the same provider. Both settings are optional; IDP-Core logs a warning at startup +for each one that's missing. -```yaml +When `jwt.enabled` is `false`, IDP-Core creates neither the JWT decoder nor the JWT chain, so `OAUTH_JWK_URI` isn't +required. When no authentication mode is enabled at all (`jwt`, `oauth2-login`, `api-key`, and `mock` are all +`false`), IDP-Core denies every request outside the public paths and the webhook entry point. You can disable Swagger independently with `app.security.swagger.enabled=false`. When you enable Swagger +without OAuth configuration, it publishes only the available security schemes. -app: - security: - authentication: - user-claim-mappings: - sub: "sub" - preferred_username: "preferred_username" - name: "name" - email: "email" - groups: "groups" - client_id: "clientId" # Note: camelCase in Keycloak - azp: "azp" - grant_type: "grant_type" - gty: "gty" - service_name: "service_name" -``` +#### Map IdP claims -=== "Azure AD" - -```yaml -app: - security: - authentication: - user-claim-mappings: - sub: "oid" # Object ID in Azure - preferred_username: "unique_name" - name: "name" - email: "email" - groups: "groups" - client_id: "appid" - azp: "appid" - grant_type: "grant_type" - gty: "gty" - service_name: "custom_service_name" -``` +Identity providers name the same claim differently. Map them under `app.security.authentication.user-claim-mappings`: -When a JWT is received, the `PrincipalExtractor` uses these mappings to extract the actual claim values from the token, -ensuring that regardless of IdP differences, your application always receives standardized `PrincipalInfo` objects. +=== "Auth0" -### How Claim Mappings Work + ```yaml + app: + security: + authentication: + user-claim-mappings: + preferred_username: "preferred_username" + name: "name" + email: "email" + groups: "groups" + ``` -While the examples above cover standard configurations, understanding the extraction engine's fallback logic is crucial -when dealing with custom claims or missing data. +=== "Keycloak" -The extraction strategy doesn't just rename claims; it applies specific fallback rules if a mapped claim is missing from -the token: + ```yaml + app: + security: + authentication: + user-claim-mappings: + preferred_username: "preferred_username" + name: "name" + email: "email" + groups: "groups" + client_id: "clientId" # camelCase in Keycloak + ``` -| Principal field | Mapping key | Fallback when the mapped claim is absent | -|--------------------|----------------------|------------------------------------------| -| `identifier` | `preferred_username` | Original JWT `sub` | -| `name` | `name` | Extracted `identifier` | -| `attributes.email` | `email` | Attribute omitted | -| `groups` | `groups` | Empty list | +=== "Azure AD" -> [!WARNING] -> The current JWT extraction strategy ignores the `sub` mapping and reads the -> original JWT subject directly. Setting `sub: uuid` alone does not select -> `uuid` as the principal identifier. Use `preferred_username: uuid` for human -> principals to select that claim with the current implementation. -> Service accounts use different rules: mapped `client_id`, then mapped `azp`, -> then the original JWT `sub`. + ```yaml + app: + security: + authentication: + user-claim-mappings: + preferred_username: "unique_name" + name: "name" + email: "email" + groups: "groups" + client_id: "appid" + ``` -### Example: UUID Identifier and Subject as Display Name +#### Classify human and machine tokens -The following decoded JWT payload contains only fictional values. -It illustrates claim extraction, not a complete token for authentication. - -```json -{ - "sub": "demo-user", - "uuid": "00000000-0000-4000-8000-000000000001", - "email": "demo-user@example.com" -} -``` - -To use `uuid` as the human principal identifier and `sub` as its display name, -configure: +IDP-Core must decide whether a token represents a person or a service. Configure claims that only human tokens carry, +plus the identifier claim for each kind: ```yaml app: security: authentication: - user-claim-mappings: - preferred_username: uuid - name: sub - email: email + principal-extraction: + human-indicator-claims: + - email + human: + id-claim: email + machine: + id-claim: client_id + id-prefix: "machine:" ``` -For a token classified as human, the extracted `PrincipalInfo` contains: - -- `identifier`: `00000000-0000-4000-8000-000000000001` -- `kind`: `HUMAN` -- `name`: `demo-user` -- `attributes.email`: `demo-user@example.com` -- `groups`: `[]` - -> [!WARNING] -> Changing the identifier mapping can provision a separate catalog principal. -> Plan how to handle existing principals and their references before changing it. +A token is human when at least one indicator claim has a non-blank value. Otherwise, IDP-Core treats it as a machine +principal (`SERVICE_ACCOUNT`). The selected identifier claim must be non-blank, or IDP-Core rejects the request with +HTTP 401. `machine.id-prefix` is optional and only affects the machine identifier. -## Service Account Detection - -Service accounts are **machine-to-machine (M2M) credentials** used for service-to-service authentication (for example, -API clients, automation tools). Identifying them correctly is important for: - -- Applying different authorization rules for services vs. humans -- Audit logging and security monitoring -- Rate limiting and quota management +> [!IMPORTANT] +> Use indicators that your provider sets only on human tokens. IDP-Core doesn't infer the kind from `scope`, +> `client_id`, `grant_type`, or `token_type`. -IDP-Core supports two detection modes: +### OAuth2 login -### Strict Mode (Recommended) +OAuth2 login runs the browser authorization-code flow through Spring Security. It's the closest local equivalent of +real user authentication. The following example uses GitHub: -In strict mode, a single **definitive claim** unambiguously identifies M2M tokens: +```yaml title="src/main/resources/application-local.yml" +spring: + security: + oauth2: + client: + registration: + github: + client-id: ${GITHUB_CLIENT_ID} + client-secret: ${GITHUB_CLIENT_SECRET} + scope: + - read:user + - user:email -```yaml app: + idp-core-prefix-url: http://localhost:8084 security: authentication: - service-account-detection: + jwt: + enabled: false + oauth2-login: enabled: true - mode: "strict" - definitive-claim-name: "token_type" - definitive-claim-value: "m2m" + mock: + enabled: false + user-claim-mappings: + preferred_username: login + name: name + email: email ``` -The system checks if the token contains `token_type=m2m`. If it does, the principal is classified as a -`SERVICE_ACCOUNT`; otherwise, it's a `HUMAN_USER`. +Create a GitHub OAuth App with these settings: -**Benefits:** +- Homepage URL: `http://localhost:8084` +- Authorization callback URL: `http://localhost:8084/login/oauth2/code/github` -- Prevents false positives (human users misidentified as services) -- More secure - reduces risk of access control bypass -- Clear, deterministic behavior +Start the application, then open `http://localhost:8084/oauth2/authorization/github`: -**Requirements:** +```bash +export SPRING_PROFILE=local +export GITHUB_CLIENT_ID=your-github-client-id +export GITHUB_CLIENT_SECRET=your-github-client-secret +./mvnw spring-boot:run +``` -- Your IdP or API gateway must inject the definitive claim -- May require custom configuration at the IdP level +After the callback succeeds, the next authenticated request to `/api/v1/**` provisions the GitHub user. -### Legacy Mode (Backwards Compatibility) +### Mock authentication -In legacy mode, the system checks multiple optional claims with OR logic: +Mock authentication injects a fixed JWT for every request, so you can work without an IdP: ```yaml app: security: authentication: - service-account-detection: + mock: enabled: true - mode: "legacy" - legacy-fallback-claims: - - "grant_type" - - "service_name" - - "client_id" ``` -In legacy mode, IDP-Core classifies a token as a `SERVICE_ACCOUNT` when **any** of -the following conditions is true: - -- The claim mapped to `grant_type` or `gty` has the value - `client_credentials`. -- The claim mapped to `service_name` is present. -- The claim mapped to `client_id` or `azp` has the same value as `sub`. +The token has `sub` and `preferred_username` set to `local-developer`, `email` set to `developer@local.dev`, and the +`ROLE_USER` and `ROLE_API_CLIENT` authorities. The mock principal passes through the same extraction, provisioning, and +authorization steps as a real token. Include your configured human indicator claim in the mock token if you need a +human principal. -If none of these conditions is met, the token is classified as a `HUMAN_USER`. +### API key -**Benefits:** +The `app.security.authentication.api-key` chain is a placeholder. It doesn't validate credentials or establish a +principal, so don't enable it. Inbound webhook delivery uses connector-level validation instead. See +[Webhook Security](webhooks.md#security-strategies). -- Works immediately without IdP reconfiguration -- Maintains backwards compatibility with existing deployments +### Chain ordering -**Drawbacks:** +Spring Security uses the first chain whose `securityMatcher` matches the request. Lower `@Order` values run first: +`PublicFilterChainConfig` (1), `JwtFilterChainConfig` (2), `ApiKeyFilterChainConfig` (3), and +`MockFilterChainConfig` (4). Keep the paths excluded from provisioning in sync with the public chain. -- Prone to false positives (for example, human user with `client_id` present) -- Less secure - may misclassify humans as services -- Will be deprecated in future versions +## Principals and provisioning -> [!WARNING] -> Migrate from legacy to strict mode is really encouraged for the systems meeting the prerequisites. Legacy mode is only recommended for existing systems -that cannot immediately reconfigure their Identity Provider configuration. +### What is a principal -## Principal Extraction - -Once a JWT is validated and claims are mapped, the `PrincipalExtractor` converts the token into a domain `PrincipalInfo` -object. - -### Extraction Strategy Pattern - -The extraction system uses the **Strategy pattern** to support multiple token types: - -```java -public PrincipalInfo extractPrincipalInfo(Authentication authentication) { - if (authentication instanceof JwtAuthenticationToken jwtToken) { - return extractFromJwt(jwtToken); - } - - // Fallback for other authentication types - return createFallbackPrincipal(authentication); -} -``` - -Each strategy: - -1. Reads the configured claim mappings from `AuthenticationProperties` -2. Extracts values from the token using mapped claim names -3. Classifies the principal as `HUMAN_USER` or `SERVICE_ACCOUNT` using service account detection -4. Returns a unified `PrincipalInfo` domain object - -### PrincipalInfo Domain Model +A principal is the authenticated caller, stored in the catalog as an entity of the `principal` template. It's the key +for provisioning, audit records, and authorization. IDP-Core represents it in code as `PrincipalInfo`: ```java public record PrincipalInfo( - String identifier, // Unique ID (for example, email, username) + String identifier, // Stable unique ID PrincipalKind kind, // HUMAN or SERVICE_ACCOUNT String name, // Display name - Map attributes, // Additional attributes + Map attributes, // For example, email List groups // Group memberships ) { } ``` -## Just-In-Time (JIT) Provisioning - -After successful authentication, the `JitProvisioningFilter` automatically creates a principal record in the database if -it doesn't exist. This enables: - -- **Self-service access**: Users don't need manual provisioning before first login -- **Automatic sync**: User data stays in sync with the IdP -- **Reduced overhead**: No need to pre-populate users before they access the system - -### How JIT Provisioning Works +| Kind | Represents | +| ----------------- | ------------------------------------ | +| `HUMAN` | A person who signs in through an IdP | +| `SERVICE_ACCOUNT` | A machine-to-machine (M2M) client | -1. Request passes through an authentication filter successfully -2. `JitProvisioningFilter` extracts the `PrincipalInfo` from Spring Security Context -3. Checks if the principal exists in the database (by identifier) -4. If not found, creates a new principal record with the extracted information -5. Continues to the controller +### Choose the identifier -### Excluding Paths +The identifier is never guessed or substituted. A missing or blank identifier returns HTTP 401. -Not all authenticated requests should trigger provisioning (for example, public paths, health checks). Configure -excluded paths in `application.yml`: +| Authentication mode | Identifier source | +| --------------------------- | ------------------------------------------------------------- | +| JWT human token | `principal-extraction.human.id-claim` | +| JWT machine token | `principal-extraction.machine.id-claim`, plus optional prefix | +| OAuth2 login | Provider-configured principal name (GitHub uses numeric `id`) | +| OpenID Connect (OIDC) login | Standard `sub` claim | +| Mock | `sub` (`local-developer`) | -```yaml -app: - security: - authentication: - jit-provisioning-excluded-paths: - - "/" - - "/actuator/**" - - "/swagger-ui/**" - - "/swagger-ui.html" - - "/v3/api-docs/**" -``` +IDP-Core has no setting to override the OAuth2 or OIDC identifier. -> [!IMPORTANT] -> Keep the JIT excluded paths in sync with the `PublicFilterChainConfig` permission mechanism. If you add a public path -to one, add it to both. - -## API Key Authentication +> [!WARNING] +> Changing an identifier mapping provisions a new principal. IDP-Core doesn't rename, merge, or look up principals that +> it provisioned earlier. Choose a stable, globally unique claim such as a UUID. -For webhook receivers and service-to-service calls that don't use OAuth2, IDP-Core supports simple API key -authentication. +### Extract the other fields -### Enabling API Key Authentication +The other fields use limited fallbacks: -```yaml -app: - security: - authentication: - api-key: - enabled: true -``` +| Principal field | Mapping key | Fallback when absent | +| ------------------ | ----------- | ------------------------------------- | +| `name` | `name` | `preferred_username`, then identifier | +| `attributes.email` | `email` | Attribute omitted | +| `groups` | `groups` | Empty list | -API keys are provided via the `X-API-Key` header: +For example, with `human.id-claim: uuid` and `user-claim-mappings.name: sub`, this fictional payload: -```bash -curl -H "X-API-Key: your-secret-key" https://api.example.com/api/v1/webhooks +```json +{ + "sub": "demo-user", + "uuid": "00000000-0000-4000-8000-000000000001", + "email": "demo-user@example.com" +} ``` -The `ApiKeyFilterChainConfig` validates the key and creates an authenticated principal without requiring JIT -provisioning (API keys are pre-configured, not JIT-provisioned). +produces a `HUMAN` principal with identifier `00000000-0000-4000-8000-000000000001`, name `demo-user`, and +`attributes.email` set to `demo-user@example.com`. -## Mock Authentication (Local Development) +### Provisioning modes -For local development and testing, enable mock authentication to generate tokens without an IdP: +After authentication, `JitProvisioningFilter` links the caller to a `principal` entity. The +`app.security.principal-provisioning.mode` flag controls what happens when no principal exists for the identifier: ```yaml app: security: - authentication: - mock: - enabled: true + principal-provisioning: + mode: ${IDP_PRINCIPAL_PROVISIONING_MODE:LINK_ONLY} ``` -The `MockFilterChainConfig` generates a mock JWT token with configurable claims via request parameters: +| Mode | Missing principal | Use for | +| ----------- | ------------------------------------------------------------------ | ------------------------------------------------ | +| `JIT` | IDP-Core creates it from the token, so first login self-provisions | Open access where the IdP is the source of truth | +| `LINK_ONLY` | IDP-Core rejects the request with HTTP 401 | Controlled access: principals exist beforehand | -```bash -curl -H "Authorization: Bearer mock?sub=test-user&email=test@example.com" \ - http://localhost:8080/api/v1/entities -``` +The flag defaults to `JIT` when you leave it unset, but `application.yml` sets `LINK_ONLY`. Set +`IDP_PRINCIPAL_PROVISIONING_MODE` to change it. -> [!WARNING] -> Mock authentication must never be enabled in production. It bypasses all JWT validation and should only be used in -`local` or `test` Spring profiles. +#### JIT mode -## GitHub Authentication for Local Development +1. `PrincipalExtractor` converts the `Authentication` to `PrincipalInfo`. +2. `PrincipalProvisioningService` creates the principal when it's missing. +3. IDP-Core looks the principal up again and continues the request. If no principal matches, it returns HTTP 401. -If you want to exercise the real user authentication path locally, use GitHub as the OAuth2 provider instead of the -mock filter. This setup exercises the same JIT provisioning flow as production-style authenticated requests: +#### LINK_ONLY mode -1. Spring Security completes the OAuth2 login with GitHub. -2. `OAuth2LoginFilterChainConfig` stores the authenticated `OAuth2User` in the security context. -3. `JitProvisioningFilter` extracts a `PrincipalInfo` through `PrincipalExtractor`. -4. `PrincipalProvisioningService` creates or refreshes the `principal` entity on the first authenticated request. +IDP-Core never creates principals from token data. A principal must exist already, for example from an ingestion +webhook or an administrator. -### Local Profile Configuration +1. `PrincipalExtractor` converts the `Authentication` to `PrincipalInfo`. +2. IDP-Core looks up the linked principal by identifier. +3. If found, the request continues. +4. If missing and the identifier isn't a [break-glass identifier](#break-glass-identifiers), IDP-Core returns HTTP 401 + with `No linked principal matches the authenticated identity`. +5. If missing and the identifier is a break-glass identifier, IDP-Core creates the principal with `is_admin: true`. -The `local` profile now expects a GitHub OAuth App and enables browser-based OAuth2 login. +A failure in provisioning itself, such as a database error, is logged and the request continues. A missing or blank +identifier always returns HTTP 401 in both modes. -```yaml title="src/main/resources/application-local.yml" -spring: - security: - oauth2: - client: - registration: - github: - client-id: ${GITHUB_CLIENT_ID} - client-secret: ${GITHUB_CLIENT_SECRET} - scope: - - read:user - - user:email +#### Excluded paths +Exclude public paths from provisioning in either mode: + +```yaml app: - idp-core-prefix-url: http://localhost:8084 security: authentication: - jwt: - enabled: false - oauth2-login: - enabled: true - mock: - enabled: false - user-claim-mappings: - sub: id - preferred_username: login - name: name - email: email + jit-provisioning-excluded-paths: + - "/" + - "/actuator/**" + - "/swagger-ui/**" + - "/swagger-ui.html" + - "/v3/api-docs/**" ``` -### GitHub OAuth App Setup - -Create a GitHub OAuth App and configure: - -- Homepage URL: `http://localhost:8084` -- Authorization callback URL: `http://localhost:8084/login/oauth2/code/github` - -Export the client credentials before you start the app: - -```bash -export SPRING_PROFILE=local -export GITHUB_CLIENT_ID=your-github-client-id -export GITHUB_CLIENT_SECRET=your-github-client-secret -./mvnw spring-boot:run -``` +JIT provisioning always creates the principal with `is_admin: false`. It ignores `is_admin` and `kind` from extracted +attributes, and it doesn't overwrite existing principal data. -Then open `http://localhost:8084/oauth2/authorization/github` in your browser. After the callback succeeds, the next -authenticated request to `/api/v1/**` provisions the GitHub user in the catalog automatically. +> [!WARNING] +> Don't map an untrusted identity claim to `is_admin`. Only an authorized administrator or a trusted ingestion webhook +> should change it. ---- +## Authorization -## Adding a Custom Authentication Method +The JWT, mock, and OAuth2 login chains apply the authorization policy after provisioning. Webhook ingestion uses its +own chain and the security configured on each connector. -This section explains how to add a new authentication mechanism to IDP-Core while respecting the existing architecture. +### Global mode -### Why Custom Authentication? +`GLOBAL` is the only available mode. The `RBAC` and `ABAC` modes fail closed until their policies exist. -You might need custom authentication for: +| Principal | Read access | Create, update, delete | +| ---------------------------------------------------- | --------------------------------------------------------------------------- | ----------------------- | +| Global identifier in `global-principal-identifiers` | All supported resources | All supported resources | +| Catalog admin (`is_admin: true`) | All supported resources, including audit | All supported resources | +| Service account | Entities, entity search, entity templates, `/api/v1/entities/principals/me` | Denied | +| Human with gate disabled or required property `true` | Same as service account | Denied | +| Human with required property missing or `false` | Denied | Denied | -- Cloud provider authentication (AWS IAM, Google Cloud) -- Enterprise SSO protocols (SAML, OpenID Connect with custom flows) -- Mutual TLS (mTLS) for service-to-service authentication -- Legacy authentication systems that must coexist with OAuth2 -- Custom corporate authentication mechanisms +The policy classifies `GET`, `HEAD`, and `OPTIONS` as reads. It also treats `POST /api/v1/entities/search` and +`POST /api/v1/entity_dynamic_mappings/dry-run` as reads. Resource rules still decide access, so non-admins can search +entities but can't call the dry-run endpoint. Audit history, dynamic-mapping management, and inbound webhook +configuration are admin-only. Unsupported HTTP methods are denied. -### Step 1: Define Configuration Properties +### Break-glass identifiers -Add your mechanism toggle to `application.yml` under `app.security.authentication`: +Configure root identifiers that bypass catalog and human-property checks: ```yaml app: security: - authentication: - custom-auth: - enabled: false - # Custom mechanism-specific properties - some-setting: "value" + authorization: + mode: GLOBAL + global-principal-identifiers: ${IDP_SUPER_ADMIN_IDENTIFIER:},${IDP_PLATFORM_ADMIN_IDENTIFIER:} + required-principal-property: ${IDP_REQUIRED_PRINCIPAL_PROPERTY:} ``` -Update `AuthenticationProperties.java` to include your configuration: +Values must match the resulting principal identifier exactly, and the allow-list doesn't scope entries by issuer. Use +an immutable, globally unique identifier. In `LINK_ONLY` mode, IDP-Core creates a missing principal for a global +identifier with `is_admin: true`. It never changes an existing principal. In `JIT` mode, the principal is created as +non-admin, but the identifier still bypasses authorization. See +[Provisioning modes](#provisioning-modes). -```java -public record AuthenticationProperties( - // ... existing fields ... +### Require a human property - /// Your custom authentication mechanism configuration - CustomAuthConfig customAuth -) { -} +Set `required-principal-property` (for example, `IDP_REQUIRED_PRINCIPAL_PROPERTY=is_idp_user`) to require that a human +principal has the property set to `true` for any non-admin access, including reads. An empty value disables the gate. +Service accounts, catalog admins, and global identifiers skip it. -public record CustomAuthConfig( - boolean enabled, - String someSetting -) { -} -``` - -### Step 2: Create the Filter Chain Configuration +Add the property as an optional Boolean on the `principal` template before you enable the gate. A trusted ingestion +webhook can then populate it. JIT never derives it from token claims. Restrict webhook mappings to authoritative +sources. -Create a new configuration class in `infrastructure/adapters/api/configuration/security/chains/`: +### What comes next -```java -package com.decathlon.idp_core.infrastructure.adapters.api.configuration.security.chains; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; - -import static org.springframework.security.config.Customizer.withDefaults; - -import com.decathlon.idp_core.infrastructure.adapters.api.auth.JitProvisioningFilter; - -/** - * Security filter chain for custom authentication mechanism. - * - * This chain handles authentication for all requests matching the specified paths. - * Custom authentication credentials are extracted from request headers/body and - * validated before creating an Authentication object in the security context. - * - * The JitProvisioningFilter is appended to ensure authenticated principals are - * automatically provisioned in the database (if not already present). - * - * @see CustomAuthenticationFilter - * @see JitProvisioningFilter - */ -@Configuration -@ConditionalOnProperty(prefix = "app.security.authentication.custom-auth", name = "enabled", havingValue = "true") -public class CustomAuthFilterChainConfig { - - private final JitProvisioningFilter jitProvisioningFilter; - private final CustomAuthenticationFilter customAuthFilter; - - public CustomAuthFilterChainConfig( - JitProvisioningFilter jitProvisioningFilter, - CustomAuthenticationFilter customAuthFilter) { - this.jitProvisioningFilter = jitProvisioningFilter; - this.customAuthFilter = customAuthFilter; - } - - /** - * Security filter chain for custom authentication. - * - * Order: 4 (after JWT at 2, API Key at 3, and Mock at the last position) - * - * Specifies: - * 1. Which paths this chain protects (via securityMatcher) - * 2. Authorization rules (authenticated or specific roles) - * 3. Custom authentication filter to extract credentials - * 4. JIT provisioning filter for automatic principal creation - */ - @Bean - @Order(4) - public SecurityFilterChain customAuthSecurityFilterChain(HttpSecurity http) throws Exception { - http - // Optional: Specify which paths this chain handles - // Omit to protect all remaining paths not handled by other chains - .securityMatcher("/api/v1/custom/**") - - // Require authentication for all matched paths - .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) - - // Enable CORS with default settings - .cors(withDefaults()) - - // Disable CSRF (stateless API, tokens provide their own protection) - .csrf(csrf -> csrf.disable()); - - // Add your custom authentication filter - // Place it before AbstractPreAuthenticatedProcessingFilter - http.addFilterBefore(customAuthFilter, AbstractPreAuthenticatedProcessingFilter.class); - - // Add JIT provisioning filter to create principals in database - http.addFilterAfter(jitProvisioningFilter, AbstractPreAuthenticatedProcessingFilter.class); - - return http.build(); - } -} -``` +The authorization request already identifies the principal, action, and resource. A later stage can add configurable +access profiles and resource/action permissions without changing that shape. JWT authorities don't grant platform +permissions. -### Step 3: Create the Custom Authentication Filter - -Create your filter in `infrastructure/adapters/api/auth/`: - -```java -package com.decathlon.idp_core.infrastructure.adapters.api.auth; - -import java.io.IOException; - -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Component; -import org.springframework.web.filter.OncePerRequestFilter; - -/** - * Extracts custom authentication credentials from the request and creates - * an Authentication object in the Spring Security context. - * - * This filter is invoked before the principal extractor and JIT provisioning. - * It must: - * 1. Extract credentials from request (header, cookie, body, etc.) - * 2. Validate credentials against your custom mechanism - * 3. Create an Authentication object representing the validated identity - * 4. Store it in SecurityContextHolder for downstream filters - * - * If credentials are missing or invalid, leave the SecurityContext empty - * and let the request proceed to the next filter (may be rejected at the - * authorization step or fallback to another authentication method). - */ -@Component -@Slf4j -public class CustomAuthenticationFilter extends OncePerRequestFilter { - - @Override - protected void doFilterInternal( - HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain) throws ServletException, IOException { - - try { - // 1. Extract credentials from request - String credentials = extractCredentials(request); - - if (credentials != null) { - // 2. Validate credentials (your custom logic) - CustomAuthenticationToken token = validateAndCreateToken(credentials); - - // 3. Store authentication in Spring Security context - SecurityContextHolder.getContext().setAuthentication(token); - - log.debug("Custom authentication successful"); - } - } catch (Exception e) { - log.debug("Custom authentication failed: {}", e.getMessage()); - // Leave SecurityContext empty; authorization filter will reject if needed - } - - // Continue filter chain - filterChain.doFilter(request, response); - } - - private String extractCredentials(HttpServletRequest request) { - // Extract from X-Custom-Auth header (example) - return request.getHeader("X-Custom-Auth"); - } - - private CustomAuthenticationToken validateAndCreateToken(String credentials) { - // Validate credentials and extract principal info - // Return authenticated token with principal details - return new CustomAuthenticationToken(credentials, true); - } -} -``` - -### Step 4: Create a Custom Authentication Token Class - -Create your token class representing the authenticated principal: - -```java -package com.decathlon.idp_core.infrastructure.adapters.api.auth; - -import java.util.Collection; -import java.util.List; - -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; - -import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; - -/** - * Authentication token for custom authentication mechanism. - * - * This class represents an authenticated principal from your custom mechanism. - * Spring Security uses this to track the currently authenticated user. - * - * The PrincipalExtractor will recognize this token type and extract the principal - * information into a domain PrincipalInfo object. - * - * @see PrincipalExtractor - */ -public class CustomAuthenticationToken extends AbstractAuthenticationToken { - - private final String credentials; - private final String principal; // identifier/username - - public CustomAuthenticationToken(String credentials, boolean authenticated) { - // Pass authorities to the superclass - super(List.of(new SimpleGrantedAuthority("ROLE_USER"))); - this.credentials = credentials; - this.principal = extractPrincipal(credentials); - // Let AbstractAuthenticationToken handle the authenticated state securely - super.setAuthenticated(authenticated); - } - - private String extractPrincipal(String credentials) { - return credentials.split(":")[1]; - } - - @Override - public Object getCredentials() { - return credentials; - } - - @Override - public Object getPrincipal() { - return principal; - } -} -``` - -### Step 5: Update the Principal Extractor - -The `PrincipalExtractor` must recognize your custom authentication token and convert it to a `PrincipalInfo` domain -object. - -You should create a new Spring `@Component` that implements `PrincipalExtractionStrategy`. Spring will automatically -inject it into `PrincipalExtractor`. - -```java -package com.decathlon.idp_core.infrastructure.adapters.api.principal; - -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; - -import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; -import com.decathlon.idp_core.domain.model.principal.PrincipalKind; -import com.decathlon.idp_core.infrastructure.adapters.api.auth.CustomAuthenticationToken; - -@Component -public class CustomAuthenticationExtractionStrategy implements PrincipalExtractionStrategy { - - @Override - public boolean supports(Authentication authentication) { - return authentication instanceof CustomAuthenticationToken; - } - - @Override - public PrincipalInfo extract(Authentication authentication) { - CustomAuthenticationToken token = (CustomAuthenticationToken) authentication; - String principal = token.getName(); - - return new PrincipalInfo( - principal, // identifier - PrincipalKind.HUMAN, // kind (or SERVICE_ACCOUNT) - principal, // name - Map.of(), // attributes - List.of() // roles/groups - ); - } -} -``` - -### Step 6: Verification Checklist - -After implementing your custom authentication method: - -- [ ] Configuration toggle in `application.yml` under `app.security.authentication.custom-auth.enabled` -- [ ] `AuthenticationProperties.java` updated with your configuration record -- [ ] Filter chain configuration class created with `@Order(5)` or next available -- [ ] Filter chain uses `@ConditionalOnProperty` to load only when enabled -- [ ] Custom authentication filter extracts and validates credentials -- [ ] Custom authentication filter stores `Authentication` in security context -- [ ] Custom authentication token class implements Spring `Authentication` -- [ ] `PrincipalExtractor` recognizes your token type -- [ ] `PrincipalExtractor` extracts required fields: `identifier`, `sub`, `name`, `email`, `groups`, `type` -- [ ] `JitProvisioningFilter` is appended to the chain -- [ ] No overlapping `securityMatcher` paths with existing chains -- [ ] Request paths are not in the JIT provisioning excluded paths list (unless they should be public) -- [ ] Tests verify authentication flow end-to-end -- [ ] Documentation in `application.yml` explains the new mechanism - -### Step 7: Testing Your Implementation - -Create an integration test to verify the end-to-end flow: +--- -```java +## Next Steps -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -class CustomAuthenticationIntegrationTest { - - @Autowired - private TestRestTemplate restTemplate; - - @Test - void testCustomAuthenticationSuccess() { - // Create a request with your custom credentials - HttpHeaders headers = new HttpHeaders(); - headers.set("X-Custom-Auth", "your:test:credentials"); - - HttpEntity request = new HttpEntity<>(headers); - - // Execute request - ResponseEntity response = restTemplate.exchange( - "/api/v1/entities", - HttpMethod.GET, - request, - String.class - ); - - // Verify successful authentication - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - } - - @Test - void testCustomAuthenticationFailure() { - // Test with missing/invalid credentials - ResponseEntity response = restTemplate.getForEntity( - "/api/v1/entities", - String.class - ); - - // Should fail (401 or 403 depending on your config) - assertThat(response.getStatusCode()).isIn( - HttpStatus.UNAUTHORIZED, - HttpStatus.FORBIDDEN - ); - } -} -``` - ---- +- **[Webhook Security](../features/data-integration.md##Security)** - Connector-level security for inbound webhooks diff --git a/docs/src/concepts/entities.md b/docs/src/concepts/entities.md index 1eb4f429..0106f5db 100644 --- a/docs/src/concepts/entities.md +++ b/docs/src/concepts/entities.md @@ -274,6 +274,8 @@ Retrieve a paginated list of entities for a given template: GET /api/v1/entities/{templateIdentifier}?page=0&size=20&sort=identifier,asc ``` +`size` must be between 1 and the configured maximum (default 500, set with `MAX_PAGE_SIZE`), values outside this range return `400 Bad Request`. + ### Get Entity by Identifier Retrieve a specific entity using its template and entity identifiers: @@ -282,6 +284,28 @@ Retrieve a specific entity using its template and entity identifiers: GET /api/v1/entities/{templateIdentifier}/{entityIdentifier} ``` +By default, relation objects include only the related entity's identifier, name, and template identifier. Add +`include_relations_properties=true` to include each related entity's typed properties. The root entity's properties are +returned as usual, and omitting the flag keeps the existing relation response shape. + +```text +GET /api/v1/entities/{templateIdentifier}/{entityIdentifier}?include_relations_properties=true +``` + +With the flag enabled, a relation object also includes a `properties` map: + +```json +{ + "identifier": "web-api-1", + "name": "Web API 1", + "template_identifier": "web-service", + "properties": { + "port": 8080, + "is_public": true + } +} +``` + --- ## Updating an Entity diff --git a/docs/src/concepts/entity-filtering.md b/docs/src/concepts/entity-filtering.md index c0987c46..e434ad3f 100644 --- a/docs/src/concepts/entity-filtering.md +++ b/docs/src/concepts/entity-filtering.md @@ -174,7 +174,7 @@ Request shape (`EntitySearchRequestDtoIn`): }, "page": 0, "size": 20, - "sort": "identifier:asc" + "sort": "identifier,asc" } ``` @@ -183,7 +183,7 @@ Request shape (`EntitySearchRequestDtoIn`): - `filter` is a tree of group nodes and criterion nodes. A group node has `connector` (one of `AND`,`OR`) and a non-empty `criteria` array. A criterion node must include `field`, `operation` and `value`. - Supported `operation` values: `EQ`, `NEQ`, `CONTAINS`, `NOT_CONTAINS`, `STARTS_WITH`, `ENDS_WITH`, `GT`, `GTE`, `LT`, `LTE`. - Free-text `query` (optional) performs a case-insensitive contains search across identifier, name, template identifier and all property values. -- Pagination: `page` is zero-based, `size` defaults to 20. Maximum allowed `size` is 500. +- Pagination: `page` is zero-based, `size` defaults to 20. Maximum allowed `size` is 500 by default (configurable with `MAX_PAGE_SIZE`). ### What it does @@ -202,7 +202,7 @@ curl -sS -X POST "http://localhost:8084/api/v1/entities/search" \ - `query` (optional): free-text string (max 255 chars) searched case-insensitively in `identifier`, `name`, `templateIdentifier`, and property values. - `filter` (optional): nested `FilterNodeDtoIn` JSON structure. Use a `template` criterion to scope results to a specific template when needed. -- `page` / `size`: pagination (zero-based `page`). `size` defaults to 20 and the server enforces a maximum of 500. +- `page` / `size`: pagination (zero-based `page`). `size` defaults to 20 and the server enforces a maximum of 500 by default (configurable with `MAX_PAGE_SIZE`). - `sort`: `field:asc|desc`. Allowed sort fields: `identifier`, `name`, `templateIdentifier`. ### Operator semantics @@ -221,7 +221,7 @@ curl -sS -X POST "http://localhost:8084/api/v1/entities/search" \ - Maximum filter nesting depth: 5 levels. Requests exceeding this fail with `400 Bad Request` and a descriptive error message. - Maximum total criterion count across the tree: 50. Requests exceeding this fail with `400 Bad Request`. - Maximum `query` length: 255 characters. -- Maximum `size` (page size): 500. +- Maximum `size` (page size): 500 by default, configurable with `MAX_PAGE_SIZE`. ## Next Steps diff --git a/docs/src/concepts/entity-templates.md b/docs/src/concepts/entity-templates.md index 77db63d4..fa7cdeff 100644 --- a/docs/src/concepts/entity-templates.md +++ b/docs/src/concepts/entity-templates.md @@ -13,6 +13,9 @@ An Entity Template defines: - **Properties** - Data fields with types and validation rules - **Relations** - Connections to other entity templates +The `principal` template is protected because its entities determine access to IDP-Core. Only catalog administrators can +create it. + ```mermaid classDiagram class EntityTemplate { diff --git a/docs/src/concepts/relations.md b/docs/src/concepts/relations.md index 37d36690..e9e7e770 100644 --- a/docs/src/concepts/relations.md +++ b/docs/src/concepts/relations.md @@ -112,6 +112,14 @@ Each entity can link to **multiple** target entities. --- +## Unresolved identifiers for relations + +The platform validates relation targets on every entity create, update, and patch, whether you use the REST API or webhook ingestion. Set `APP_RELATIONS_TARGET_VALIDATION_MODE` to choose how it handles unresolved targets. The default, `STRICT`, rejects any non-blank target identifier that does not resolve to an entity. In `TOLERANT` mode, the platform filters unresolved identifiers from optional relations, keeps resolved targets, and omits the relation if none resolve. + +Both modes enforce required relations, target-template compatibility for resolved targets, and the existing `required` and `to_many` cardinality constraints. Tolerant mode checks cardinality after filtering unresolved optional targets. REST entity writes return `400 Bad Request` for validation failures, while webhook ingestion returns `422 Unprocessable Content`. + +--- + ## Example: Complete Data Model Here's a complete example with multiple templates and relations: diff --git a/docs/src/contributing/code/code-conventions.md b/docs/src/contributing/code/code-conventions.md index faade886..f683a859 100644 --- a/docs/src/contributing/code/code-conventions.md +++ b/docs/src/contributing/code/code-conventions.md @@ -122,18 +122,25 @@ public class InvalidIdentifierException extends DomainException { public class GlobalExceptionHandler { @ExceptionHandler(EntityNotFoundException.class) - public ResponseEntity handleNotFound(EntityNotFoundException ex) { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(new ErrorResponse(ex.getCode(), ex.getMessage())); + public ProblemDetail handleNotFound(EntityNotFoundException ex) { + return buildProblemDetail(HttpStatus.NOT_FOUND, ex.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity handleValidation(MethodArgumentNotValidException ex) { + public ProblemDetail handleValidation(MethodArgumentNotValidException ex) { var errors = ex.getBindingResult().getFieldErrors().stream() .map(e -> e.getField() + ": " + e.getDefaultMessage()) .toList(); - return ResponseEntity.badRequest() - .body(new ErrorResponse("VALIDATION_ERROR", String.join(", ", errors))); + return buildProblemDetail(HttpStatus.BAD_REQUEST, String.join(", ", errors)); + } + + private ProblemDetail buildProblemDetail(HttpStatus status, String detail) { + var problem = ProblemDetail.forStatusAndDetail(status, detail); + problem.setTitle(status.getReasonPhrase()); + problem.setProperty("error", status.name()); + problem.setProperty("error_description", detail); + problem.setProperty("timestamp", Instant.now()); + return problem; } } ``` diff --git a/docs/src/contributing/code/domain-infrastructure.md b/docs/src/contributing/code/domain-infrastructure.md index ad1dbf92..38570d34 100644 --- a/docs/src/contributing/code/domain-infrastructure.md +++ b/docs/src/contributing/code/domain-infrastructure.md @@ -185,9 +185,13 @@ sequenceDiagram sequenceDiagram participant DomainService participant ApiExceptionHandler + participant CamelRoute + participant WebhookExceptionHandlerHelper participant Client DomainService->>ApiExceptionHandler: Throw domain exception - ApiExceptionHandler->>Client: Map to HTTP status + ErrorResponse DTO + ApiExceptionHandler->>Client: Return RFC 7807 ProblemDetail + legacy extensions + CamelRoute->>WebhookExceptionHandlerHelper: Map ingestion exception + WebhookExceptionHandlerHelper->>Client: Return RFC 7807 ProblemDetail + legacy extensions ``` --- diff --git a/docs/src/contributing/code/exception-handling.md b/docs/src/contributing/code/exception-handling.md index 72a9aae2..c9f89612 100644 --- a/docs/src/contributing/code/exception-handling.md +++ b/docs/src/contributing/code/exception-handling.md @@ -6,28 +6,52 @@ description: Global exception handling strategy and error response formats for I ## Strategy 1. **Domain**: Throw specific business exceptions, for example `EntityTemplateNotFoundException`. -2. **Infrastructure**: Catch exceptions in `ApiExceptionHandler` with `@ControllerAdvice` annotation. -3. **API**: Return consistent JSON error responses. +2. **Infrastructure**: Catch exceptions in `ApiExceptionHandler` with `@RestControllerAdvice`. +3. **API**: Return RFC 7807 `ProblemDetail` responses with legacy extension fields. ## Exception Mapping -| Exception Type | HTTP Status | Description | -| -------------------------------------- | ------------------ | -------------------- | -| `EntityTemplateNotFoundException` | 404 Not Found | Entity not found | -| `EntityTemplateAlreadyExistsException` | 409 Conflict | Duplicate identifier | -| `ConstraintViolationException` | 400 Bad Request | Validation failed | -| `MethodArgumentNotValidException` | 400 Bad Request | Invalid request body | -| `HttpMessageNotReadableException` | 400 Bad Request | JSON parsing error | -| `Exception` | 500 Internal Error | Unexpected error | +| Exception Type | HTTP Status | Description | +| -------------------------------------- | ------------------ | ---------------------------- | +| `EntityTemplateNotFoundException` | 404 Not Found | Entity not found | +| `EntityTemplateAlreadyExistsException` | 409 Conflict | Duplicate identifier | +| `ConstraintViolationException` | 400 Bad Request | Validation failed | +| `MethodArgumentNotValidException` | 400 Bad Request | Invalid request body | +| `HttpMessageNotReadableException` | 400 Bad Request | Framework JSON parsing error | +| `Exception` | 500 Internal Error | Unexpected error | ## Error Response Format -At API level, always follow the same error response structure: +Spring MVC endpoints and the Camel `/webhooks/{webhookIdentifier}` ingestion route return +`application/problem+json` responses. Standard RFC 7807 fields appear alongside legacy +compatibility fields: ```json { + "type": "about:blank", + "title": "Not Found", + "status": 404, + "detail": "Template with ID 'invalid-id' not found", + "instance": "/api/v1/entity-templates/invalid-id", "error": "NOT_FOUND", - "error_description": "Template with ID 'invalid-id' not found", - "timestamp": "2025-11-28T10:30:00Z" + "error_description": "Template with ID 'invalid-id' not found" } ``` + +The `error` and `error_description` fields preserve the legacy contract for existing +clients. `timestamp` is included as an `Instant` for traceability. + +> [!WARNING] +> Strict clients may reject the new media type or the extra extension fields. They should +> be updated to parse `application/problem+json` and tolerate RFC 7807 extensions. + +### Intentional differences + +- Spring MVC validation and JSON parsing errors now use the framework's native problem detail handling. +- The manual JSON parsing logic was removed, so some malformed payload messages may differ from the previous custom wording. + +### Migration note + +Communicate the response shape change to API consumers before they depend on the new contract. +Keep compatibility tests in place while clients migrate, and verify both the standard +ProblemDetail fields and the legacy extension properties. diff --git a/docs/src/deployment/configuration.md b/docs/src/deployment/configuration.md index 276b89b6..bd769394 100644 --- a/docs/src/deployment/configuration.md +++ b/docs/src/deployment/configuration.md @@ -190,21 +190,47 @@ spring: ```yaml management: tracing: - enabled: true sampling: - probability: 1.0 - -otel: - exporter: - otlp: - endpoint: http://otel-collector:4317 - service: - name: idp-core - resource: - attributes: - deployment.environment: production + probability: ${OTEL_TRACES_SAMPLER_ARG:0.1} + export: + enabled: ${OTEL_TRACING_ENABLED:false} + + otlp: + metrics: + export: + url: ${OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:${OTEL_EXPORTER_OTLP_ENDPOINT:http://localhost:4318}/v1/metrics} + enabled: ${OTEL_METRICS_EXPORT_ENABLED:false} + transport: ${OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:${OTEL_EXPORTER_OTLP_PROTOCOL:http/protobuf}} + + opentelemetry: + tracing: + export: + otlp: + endpoint: ${OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:${OTEL_EXPORTER_OTLP_ENDPOINT:http://localhost:4318}/v1/traces} + transport: ${OTEL_EXPORTER_OTLP_TRACES_TRANSPORT:${OTEL_EXPORTER_OTLP_PROTOCOL:http}} + resource-attributes: + deployment.environment: ${OTEL_ENV:local} + service.namespace: ${OTEL_SERVICE_NAMESPACE:idp-core} + service.name: ${OTEL_SERVICE_NAME:internal-developer-platform} ``` +The signal-specific OpenTelemetry variables win over the generic fallback, so you can set the standard OpenTelemetry environment variables without hard-coding vendor-specific values. + +### Common environment variables + +| Variable | Description | +| --- | --- | +| `OTEL_TRACING_ENABLED` | Enables tracing export | +| `OTEL_METRICS_EXPORT_ENABLED` | Enables OTLP metrics export | +| `OTEL_TRACES_SAMPLER_ARG` | Trace sampling ratio | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | Base OTLP endpoint | +| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Full traces URL | +| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | Full metrics URL | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | Generic OTLP protocol fallback | +| `OTEL_EXPORTER_OTLP_TRACES_TRANSPORT` | Trace transport override | +| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Metrics transport override | +| `OTEL_RESOURCE_ATTRIBUTES` | Resource metadata for the service | + --- ### OAuth 2.0 diff --git a/docs/src/deployment/docker.md b/docs/src/deployment/docker.md index e6254a3c..64e5b69b 100644 --- a/docs/src/deployment/docker.md +++ b/docs/src/deployment/docker.md @@ -224,77 +224,43 @@ ENTRYPOINT ["java", "-jar", "app.jar"] ### Observability -| Variable | Description | Default | -| ----------------------------- | -------------- | ---------- | -| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP endpoint | - | -| `OTEL_SERVICE_NAME` | Service name | `idp-core` | -| `LOG_LEVEL` | Root log level | `INFO` | - ---- - -## Docker Compose Commands - -### Start Services - -```bash -# Start all -docker compose up -d - -# Start specific service -docker compose up -d idp-core - -# View logs -docker compose logs -f idp-core -``` - -### Stop Services - -```bash -# Stop all -docker compose down - -# Stop and remove volumes -docker compose down -v -``` - -### Update - -```bash -# Pull latest images -docker compose pull - -# Recreate containers -docker compose up -d --force-recreate -``` - -### Scale - -```bash -# Run 3 instances -docker compose up -d --scale idp-core=3 -``` - ---- - -## Database Management - -### Initialize Database - -The database schema is managed by Flyway and applies automatically on startup. - -### Backup - -```bash -docker exec postgres pg_dump -U idp idp > backup.sql -``` - -### Restore - -```bash -cat backup.sql | docker exec -i postgres psql -U idp idp -``` - ---- +IDP-Core follows the standard OpenTelemetry environment variables. Tracing and metrics export are opt-in, and the application keeps the usual OpenTelemetry fallbacks so you can set the standard variables without hard-coding a vendor-specific configuration. + +The effective precedence is: + +- `OTEL_EXPORTER_OTLP_TRACES_TRANSPORT` > `OTEL_EXPORTER_OTLP_PROTOCOL` > `http` +- `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` > `OTEL_EXPORTER_OTLP_PROTOCOL` > `http/protobuf` + +This means the application can work in local Docker, in Kubernetes, or in a managed platform while still honoring the standard OpenTelemetry variables set by the operator or deployment pipeline. + +| Variable | Description | Default | +|---------------------------------------|----------------------------------------------------------|------------------------------------------------| +| `OTEL_TRACING_ENABLED` | Enables OpenTelemetry tracing (opt-in) | `false` | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | Base OTLP endpoint for all signals | `http://localhost:4318` | +| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Full traces URL. It wins over the base endpoint | `/v1/traces` | +| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | Full metrics URL. It wins over the base endpoint | `/v1/metrics` | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | OTLP protocol used as the generic fallback | `http/protobuf` for metrics, `http` for traces | +| `OTEL_EXPORTER_OTLP_TRACES_TRANSPORT` | Transport for traces. It wins over the generic protocol | `OTEL_EXPORTER_OTLP_PROTOCOL` or `http` | +| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Transport for metrics. It wins over the generic protocol | `OTEL_EXPORTER_OTLP_PROTOCOL` | +| `OTEL_METRICS_EXPORT_ENABLED` | Enables OTLP metrics export (opt-in) | `false` | +| `OTEL_TRACES_SAMPLER_ARG` | Fraction of traces kept, from `0.0` to `1.0` | `0.1` | +| `OTEL_SERVICE_NAME` | Service name | `internal-developer-platform` | +| `OTEL_SERVICE_NAMESPACE` | Service namespace | `idp-core` | +| `OTEL_ENV` | Value of the `deployment.environment` attribute | `local` | +| `OTEL_RESOURCE_ATTRIBUTES` | Extra resource attributes (`key=value,key=value`) | - | +| `LOG_LEVEL` | Root log level | `INFO` | + +The signal-specific variable wins over the generic one, so the image works in the common deployments: + +- **Docker Compose or a simple container:** set `OTEL_EXPORTER_OTLP_ENDPOINT` +- **Kubernetes with the OpenTelemetry Operator:** the platform injects `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` +- **Datadog or another OTLP collector:** set the standard OpenTelemetry endpoint and resource attributes +- **Local development:** leave the variables unset and use the built-in `localhost:4318` fallback + +> Note: Lower `OTEL_TRACES_SAMPLER_ARG` in high-throughput production. Capturing 100% of the traces increases CPU overhead +> and vendor costs. For example, `0.1` keeps 10% of the traces. + +`OTEL_RESOURCE_ATTRIBUTES` is the right place to pass Datadog tags such as `env`, `service`, and `version`. The application does not need hard-coded Datadog values; it just emits the standard OpenTelemetry resource metadata. ## Troubleshooting diff --git a/docs/src/deployment/observability.md b/docs/src/deployment/observability.md index ccbea54a..e0d179e4 100644 --- a/docs/src/deployment/observability.md +++ b/docs/src/deployment/observability.md @@ -3,336 +3,124 @@ title: Observability description: Monitoring, logging, and tracing for the Internal Developer Platform --- -The Internal Developer Platform provides comprehensive observability through metrics, logs, and distributed tracing using OpenTelemetry. - -## Overview +The Internal Developer Platform emits metrics, logs, and traces through Spring Boot and OpenTelemetry, with Camel instrumentation enabled for the webhook ingestion flow. ```mermaid flowchart LR - subgraph "Internal Developer Platform" - M[Metrics] - L[Logs] - T[Traces] + subgraph "Application" + APP[IDP-Core] + CAMEL[Camel route] + OTEL[OpenTelemetry] end - subgraph "Collection" - OTEL[OpenTelemetry Collector] + subgraph "Backends" + DD[Datadog / OTLP collector] PROM[Prometheus] end - subgraph "Visualization" - GRAF[Grafana] - LOKI[Loki] - TEMPO[Tempo / Jaeger] - DATADOG[Datadog] - end - - M --> PROM --> GRAF - L --> OTEL --> LOKI --> GRAF - T --> OTEL --> TEMPO --> GRAF - OTEL --> DATADOG - PROM --> DATADOG + APP --> CAMEL + CAMEL --> OTEL + OTEL --> DD + OTEL --> PROM ``` ---- +The app exposes health endpoints and uses OTLP export for traces and metrics when enabled. The standard OpenTelemetry variables remain the integration point for the environment, not vendor-specific configuration. ## Metrics -### Prometheus Endpoint - -The Internal Developer Platform exposes metrics at `/actuator/prometheus`: - -```bash -curl http://localhost:8080/actuator/prometheus -``` - -### Key Metrics - -#### Application Metrics - -| Metric | Description | -| -------- | ------------- | -| `idp_entities_total` | Total entities by template | -| `idp_entity_operations_total` | CRUD operations count | -| `idp_webhook_invocations_total` | Webhook calls | -| `idp_action_executions_total` | Self-service action runs | - -#### HTTP Metrics - -| Metric | Description | -| -------- | ------------- | -| `http_server_requests_seconds` | Request latency | -| `http_server_requests_active` | Active requests | - -#### JVM Metrics - -| Metric | Description | -| -------- | ------------- | -| `jvm_memory_used_bytes` | Memory usage | -| `jvm_gc_pause_seconds` | GC pause time | -| `jvm_threads_live` | Thread count | +### Metrics exported by Spring Boot and Micrometer -#### Database Metrics - -| Metric | Description | -| -------- | ------------- | -| `hikaricp_connections_active` | Active DB connections | -| `hikaricp_connections_pending` | Waiting connections | - -### Metrics Configuration +The application exposes the standard Micrometer metrics and OTLP export can be enabled through environment variables. ```yaml management: - endpoints: - web: - exposure: - include: health,info,metrics,prometheus - metrics: + tracing: + sampling: + probability: ${OTEL_TRACES_SAMPLER_ARG:0.1} export: - prometheus: - enabled: true - distribution: - percentiles-histogram: - http.server.requests: true - percentiles: - http.server.requests: 0.5,0.95,0.99 - tags: - application: idp-core - environment: ${ENVIRONMENT:dev} -``` - -### Prometheus scrape configuration - -```yaml title="prometheus.yml" -scrape_configs: - - job_name: 'idp-core' - metrics_path: '/actuator/prometheus' - static_configs: - - targets: ['idp-core:8080'] - scrape_interval: 15s -``` - -### Kubernetes ServiceMonitor - -```yaml title="servicemonitor.yaml" -apiVersion: monitoring.coreos.com/v1 -kind: ServiceMonitor -metadata: - name: idp-core - namespace: idp -spec: - selector: - matchLabels: - app: idp-core - endpoints: - - port: http - path: /actuator/prometheus - interval: 30s -``` - ---- - -## Logging + enabled: ${OTEL_TRACING_ENABLED:false} -### Log Format - -#### Development (Human-readable) - -```text -2024-01-15 10:30:45.123 INFO [http-nio-8080-exec-1] c.d.i.a.EntityController - Creating entity: payment-service -``` - -#### Production (JSON) - -```json -{ - "timestamp": "2024-01-15T10:30:45.123Z", - "level": "INFO", - "logger": "c.d.i.a.EntityController", - "message": "Creating entity: payment-service", - "thread": "http-nio-8080-exec-1", - "traceId": "abc123def456", - "spanId": "789xyz" -} -``` - -### Logging Configuration - -```yaml -logging: - level: - root: INFO - com.decathlon.idp_core: INFO - org.springframework.web: WARN - org.hibernate: WARN - - pattern: - # JSON for production - console: '{"timestamp":"%d{ISO8601}","level":"%level","logger":"%logger{36}","message":"%msg","thread":"%thread","traceId":"%X{traceId}","spanId":"%X{spanId}"}%n' -``` - -### Loki Integration - -Send logs to Loki via the OpenTelemetry Collector: - -```yaml title="otel-collector-config.yaml" -receivers: otlp: - protocols: - grpc: - endpoint: 0.0.0.0:4317 - -exporters: - loki: - endpoint: http://loki:3100/loki/api/v1/push - labels: - attributes: - service.name: "service_name" - deployment.environment: "environment" - -service: - pipelines: - logs: - receivers: [otlp] - exporters: [loki] + metrics: + export: + url: ${OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:${OTEL_EXPORTER_OTLP_ENDPOINT:http://localhost:4318}/v1/metrics} + enabled: ${OTEL_METRICS_EXPORT_ENABLED:false} + transport: ${OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:${OTEL_EXPORTER_OTLP_PROTOCOL:http/protobuf}} + + opentelemetry: + tracing: + export: + otlp: + endpoint: ${OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:${OTEL_EXPORTER_OTLP_ENDPOINT:http://localhost:4318}/v1/traces} + transport: ${OTEL_EXPORTER_OTLP_TRACES_TRANSPORT:${OTEL_EXPORTER_OTLP_PROTOCOL:http}} + resource-attributes: + deployment.environment: ${OTEL_ENV:local} + service.namespace: ${OTEL_SERVICE_NAMESPACE:idp-core} + service.name: ${OTEL_SERVICE_NAME:internal-developer-platform} ``` -### Log Levels +### Custom business metrics -| Level | Usage | -| ------- | -------------------------- | -| `ERROR` | Errors requiring attention | -| `WARN` | Potential issues | -| `INFO` | Key business events | -| `DEBUG` | Development debugging | -| `TRACE` | Detailed tracing | +Business-level metrics are intentionally separate from Camel route telemetry. The application adds custom counters only for functional decisions that Camel does not expose as a reusable business signal. ---- +Examples: -## Distributed Tracing +- `idp.webhook.security.requests.total{connector, security_type}` +- `idp.webhook.security.result{connector, security_type, result}` +- `idp.webhook.security.validation.errors.total{connector, security_type, reason}` -### OpenTelemetry Setup +These metrics reflect the real security decision made by the application and should not duplicate the standard Camel `route.*` metrics. -```yaml -management: - tracing: - enabled: true - sampling: - probability: 1.0 # Sample all requests (use 0.1 for 10% in prod) - -otel: - exporter: - otlp: - endpoint: http://otel-collector:4317 - service: - name: idp-core - resource: - attributes: - deployment.environment: production - service.version: "1.0.0" -``` +## Logging -### Trace Context +Logs remain useful for debugging and operational incidents, but they are not the primary analytics signal. The main operational signals are traces and metrics. -IDP-Core propagates trace context through: +The application configuration keeps log filtering under `logging.level.*` and actuator health endpoints under `management.endpoint.health`. -- HTTP headers (W3C Trace Context) -- Kafka message headers -- Webhook requests +## Distributed tracing -### Key Spans +OpenTelemetry tracing is enabled through Spring Boot configuration. The application keeps the trace sampling rate and OTLP exporter configurable through environment variables. -| Span | Description | -| --------------------------- | -------------------- | -| `HTTP GET /api/v1/entities` | Incoming API request | -| `EntityRepository.findById` | Database query | -| `WebhookService.invoke` | Outgoing webhook | -| `KafkaProducer.send` | Kafka message | +### Standard environment variables -### Jaeger/Tempo Integration +| Variable | Description | Default | +| --- | --- | --- | +| `OTEL_TRACING_ENABLED` | Enables tracing export | `false` | +| `OTEL_METRICS_EXPORT_ENABLED` | Enables OTLP metrics export | `false` | +| `OTEL_TRACES_SAMPLER_ARG` | Trace sampling ratio | `0.1` | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | Base OTLP endpoint | `http://localhost:4318` | +| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Full traces endpoint | `/v1/traces` | +| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | Full metrics endpoint | `/v1/metrics` | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | Generic OTLP protocol fallback | `http/protobuf` for metrics, `http` for traces | +| `OTEL_EXPORTER_OTLP_TRACES_TRANSPORT` | Trace-specific transport override | `OTEL_EXPORTER_OTLP_PROTOCOL` or `http` | +| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Metrics-specific transport override | `OTEL_EXPORTER_OTLP_PROTOCOL` | +| `OTEL_RESOURCE_ATTRIBUTES` | Resource metadata injected by the environment | - | -```yaml title="otel-collector-config.yaml" -receivers: - otlp: - protocols: - grpc: - endpoint: 0.0.0.0:4317 - -exporters: - otlp/tempo: - endpoint: http://tempo:4317 - tls: - insecure: true - -service: - pipelines: - traces: - receivers: [otlp] - exporters: [otlp/tempo] -``` +The signal-specific variables win over the generic fallback, so local development and hosted deployments can both work without hard-coded vendor configuration. ---- +### Important trace attributes -## Health Checks +The application sets trace attributes for the webhook pipeline, including the connector identifier and the security decision. -### Endpoints +Examples: -| Endpoint | Purpose | -| ---------------------------- | --------------- | -| `/actuator/health` | Overall health | -| `/actuator/health/liveness` | Liveness probe | -| `/actuator/health/readiness` | Readiness probe | +- `idp.webhook.identifier` +- `idp.webhook.security.result` -### Health Configuration +These attributes support trace correlation in Datadog APM and allow support teams to trace a request across route execution, security validation, and mapping. -```yaml -management: - endpoint: - health: - show-details: when_authorized - show-components: always - probes: - enabled: true - health: - db: - enabled: true - diskspace: - enabled: true - threshold: 100MB -``` +## Health checks -### Response Example - -```json -{ - "status": "UP", - "components": { - "db": { - "status": "UP", - "details": { - "database": "PostgreSQL", - "validationQuery": "isValid()" - } - }, - "diskSpace": { - "status": "UP", - "details": { - "total": 107374182400, - "free": 85899345920, - "threshold": 104857600 - } - }, - "ping": { - "status": "UP" - } - } -} -``` +The app exposes health endpoints used by Docker and Kubernetes. ---- +| Endpoint | Purpose | +|------------------------------|----------------------| +| `/actuator/health` | Overall health | +| `/actuator/health/liveness` | Liveness probe | +| `/actuator/health/readiness` | Readiness probe | -## Next Steps +## Next steps -- **[Configuration](configuration.md)** - Observability settings -- **[Kubernetes](kubernetes.md)** - Production monitoring -- **[Docker](docker.md)** - Local observability setup +- **[Configuration](configuration.md)** - Environment and Spring Boot settings +- **[Docker](docker.md)** - Docker deployment and OTLP examples +- **[Kubernetes](kubernetes.md)** - Production deployment patterns diff --git a/docs/src/features/data-integration.md b/docs/src/features/data-integration.md index 13cc888b..350e7307 100644 --- a/docs/src/features/data-integration.md +++ b/docs/src/features/data-integration.md @@ -213,6 +213,10 @@ sequenceDiagram Route-->>Client: 201 Created ``` +> [!TIP] +> If a `filter` expression returns `false`, the payload is silently +> skipped for that mapping. Other mappings on the same connector continue to run. + Each step in the pipeline is isolated in its own Camel sub-route: | Step | Route ID | Responsibility | @@ -223,8 +227,8 @@ Each step in the pipeline is isolated in its own Camel sub-route: | **C** | `ingest-payload` | Apply each `EntityDynamicMapping` and persist entities | > [!TIP] -> If a `filter` expression returns `false`, the payload is silently -> skipped for that mapping. Other mappings on the same connector continue to run. +> Webhook ingestion uses the same relation validation mode as REST entity writes. `STRICT` is the default and rejects unresolved target identifiers. Set `APP_RELATIONS_TARGET_VALIDATION_MODE=TOLERANT` to filter unresolved identifiers from optional relations; IDP-Core keeps resolved targets and omits the relation if none resolve. +> Both modes enforce required relations, target-template compatibility, and cardinality. Tolerant mode checks cardinality after filtering. A webhook relation validation failure returns `422 Unprocessable Content`. --- diff --git a/docs/src/features/entity-dynamic-mapping.md b/docs/src/features/entity-dynamic-mapping.md index 3d16dcf2..62be57fc 100644 --- a/docs/src/features/entity-dynamic-mapping.md +++ b/docs/src/features/entity-dynamic-mapping.md @@ -7,6 +7,10 @@ description: Understand Dynamic mappings and JSLT expressions. A mapping targets one Entity Template and describes how to derive entity fields from the incoming JSON payload with a JSLT filter and entity projections. It is linked to a data integration configuration (Webhook, Kafka, etc) as it describes how to transform incoming payloads. +Only catalog administrators can create or update mappings that target the protected `principal` template. This +restriction prevents an ingestion mapping from changing principal privileges. Webhook deliveries that use an already +authorized mapping continue to run through the configured connector security strategy. + ## Entity Dynamic Mapping Fields | Field | Required | Description | @@ -195,6 +199,17 @@ if (.is_private == true) "PRIVATE_" + .name else .name } ``` +### JSLT Execution Limits + +To protect the platform against denial-of-service, JSLT processing is bounded: + +| Limit | Value | Exceeded behavior | +| ------------------ | ------------------------ | --------------------------------------- | +| Payload size | 1 MB (UTF-8 bytes) | Rejected before parsing (400) | +| JSON nesting depth | 64 levels | Rejected before the tree is built (400) | +| Expression length | 10,000 characters | Rejected at validation (422) | +| Evaluation timeout | 5 seconds per evaluation | Evaluation aborted (422) | + > [!TIP] > Use the **dry-run endpoint** (POST `/api/v1/entity_dynamic_mappings/dry-run`) to test > your JSLT expressions before deploying them to production. This helps catch syntax diff --git a/docs/src/features/webhooks.md b/docs/src/features/webhooks.md index ff4da621..8292f5c6 100644 --- a/docs/src/features/webhooks.md +++ b/docs/src/features/webhooks.md @@ -80,20 +80,19 @@ This validation keeps the connector configuration aligned with the current data Each connector declares one security type. IDP-Core validates the configuration at creation time and validates requests again at runtime. -| Type | Required configuration keys | Optional configuration keys | -| -------------- | ------------------------------------------------- | ------------------------------- | -| `HMAC_SHA256` | `header_name`, `secret_alias` | `prefix` (default is `sha256=`) | -| `STATIC_TOKEN` | `header_name`, `secret_alias` | None | -| `BASIC_AUTH` | `username`, `secret_alias` | None | -| `JWT_BEARER` | `jwks_uri`, `client_id_field`, `client_id_values` | `expected_audience` | -| `NONE` | None | None | +| Type | Required configuration keys | Runtime behavior | +|------------------|-----------------------------------------------------|--------------------------------------------------------------------------------------------------| +| `HMAC_SHA256` | `header_name`, `secret_alias`, `prefix` | Computes the SHA-256 HMAC of the raw body and compares it with the request header | +| `STATIC_TOKEN` | `header_name`, `secret_alias` | Compares a header value with a secret loaded from the environment | +| `BASIC_AUTH` | `username`, `secret_alias` | Compares the `Authorization: Basic ...` header with the configured username and secret | +| `JWT_BEARER` | `jwks_uri`, `client_id_field`, `client_id_values` | Validates the bearer token against a JWKS endpoint, then checks caller identity claim allow-list | +| `NONE` | none (`config` is optional) | Skips authentication. Disabled unless `IDP_WEBHOOK_SECURITY_ALLOW_NONE=true` | > [!IMPORTANT] > Configuration keys accept `snake_case` and `camelCase` variants where supported. HMAC prefix uses the `prefix` key and has a default set to `sha256=`. > [!WARNING] -> Secret aliases reference environment variables; they do not store the raw secret value in the connector configuration. -> Use `MY_SECRET`, `env:MY_SECRET`, or `${MY_SECRET}` as the value. You can also use `secret_alias_env` or -> `secretAliasEnv` as the key and set its value to the environment variable name. +> `secret_alias` must reference an environment variable alias in `UPPER_SNAKE_CASE`. It does not store the raw secret +value in the connector configuration. ### Example Security Configurations @@ -148,25 +147,37 @@ again at runtime. } ``` +=== "NONE" + + ```json + { + "type": "NONE" + } + ``` + + For `NONE`, you can omit `config`, set it to `null`, or pass `{}`. Any non-empty `config` is rejected. + + `NONE` is forbidden by default for enabled connectors. Set the `IDP_WEBHOOK_SECURITY_ALLOW_NONE` environment variable to `true` to allow creating or updating enabled connectors with `NONE`. Disabled connectors can omit `security`, set it to `null` or `{}`, or use `NONE` without enabling this flag. In all cases, a `NONE` configuration must be empty. Connectors that already use `NONE` continue to ingest events. + + Creating or updating a connector without mappings automatically disables it, even if you send `enabled: true`. These requests also accept `security: {}`. + ### JWT_BEARER Configuration Reference - `jwks_uri` (required): literal HTTPS URL used to validate JWT signatures. -- `client_id_field` (required): claim name used to identify the caller. Allowed values are only `azp` or `email`. +- `client_id_field` (required): name of the JWT claim that identifies the caller. Any non-empty claim name is accepted, for example `client_id`, `sub`, `azp`, `email`, or a custom claim. - `client_id_values` (required): comma-separated allow-list of accepted claim values. -- `expected_audience` (optional): comma-separated allow-list for the `aud` claim. If present, at least one JWT audience must match. If omitted, IDP-Core does not check the audience. +- `expected_audience` (optional): comma-separated allow-list for the `aud` claim. If present, at least one JWT audience must match. +- `allowed-jwks-hosts` (optional, environment-backed): comma-separated allow-list of trusted JWKS hosts under `idp.security.webhook`. Set `ALLOWED_JWKS_HOSTS` when you need to permit a specific issuer host explicitly. + +The caller must send the JWT in an `Authorization: Bearer ` header. If the claim named by `client_id_field` is missing from the token, the request is rejected with `401 Unauthorized`. If the claim value is not in `client_id_values`, the request is rejected with `403 Forbidden`. > [!WARNING] > `jwks_uri` must use a resolvable public HTTPS host. Local hosts, private networks, link-local addresses, and group-address destinations are rejected at connector creation. +> If you configure `allowed-jwks-hosts`, the listed hosts bypass this rejection path intentionally. +> This allow-list is configured under `idp.security.webhook.allowed-jwks-hosts`. `jwks_uri` is stored as a literal URL in the connector configuration. Environment references are not supported for this field. -### JWKS Host Allow-List - -The optional server-level property `idp.security.webhook.allowed-jwks-hosts` defaults to an empty list. Set the -`ALLOWED_JWKS_HOSTS` environment variable to a comma-separated list of hosts to allow. When the list is non-empty, -`jwks_uri` must use one of those hosts; allow-listed hosts bypass the private and local address rejection checks. -The URI must still use HTTPS. - ## Runtime Flow The webhook runtime uses a single generic endpoint: @@ -192,7 +203,7 @@ The request flow is: You manage webhook connectors through the inbound webhook management API, which exposes standard CRUD methods. | HTTP Method | Endpoint | Purpose | -| ----------- | --------------------------------------- | ---------------- | +|-------------|-----------------------------------------|------------------| | `POST` | `/api/v1/inbound_webhooks` | Create connector | | `GET` | `/api/v1/inbound_webhooks` | List connectors | | `GET` | `/api/v1/inbound_webhooks/{identifier}` | Get connector | diff --git a/docs/src/getting-started/configuration.md b/docs/src/getting-started/configuration.md index a5b573e4..c251d255 100644 --- a/docs/src/getting-started/configuration.md +++ b/docs/src/getting-started/configuration.md @@ -75,17 +75,12 @@ Configure CORS if your frontend loads from a different origin or if no API gatew spring: web: cors: - allowed-origins: - - http://localhost:3000 - - https://your-frontend.com - allowed-methods: - - GET - - POST - - PUT - - DELETE - allowed-headers: "*" + allowed-origins: http://localhost:3000,https://your-frontend.com + allowed-origin-patterns: https://*.your-domain.com ``` +Set exact origins with `spring.web.cors.allowed-origins` or the `SPRING_WEB_CORS_ALLOWED_ORIGINS` environment variable. Set wildcard origin patterns with `spring.web.cors.allowed-origin-patterns` or the `SPRING_WEB_CORS_ALLOWED_ORIGIN_PATTERNS` environment variable. Separate multiple values with commas. + --- ## Security Configuration @@ -153,6 +148,7 @@ All configuration can be overridden using environment variables: | `SPRING_DATASOURCE_PASSWORD` | DB password | `secret` | | `SERVER_PORT` | HTTP port | `8084` | | `LOGGING_LEVEL_ROOT` | Log level | `INFO` | +| `MAX_PAGE_SIZE` | Maximum `size` accepted by search and listing endpoints (default `500`) | `1000` | ### Naming Convention diff --git a/docs/src/static/swagger.yaml b/docs/src/static/swagger.yaml index 5d564f02..bd634ffa 100644 --- a/docs/src/static/swagger.yaml +++ b/docs/src/static/swagger.yaml @@ -1,4 +1,3 @@ ---- openapi: 3.1.0 info: title: Idp core API @@ -14,6 +13,8 @@ tags: description: Entity relationship graph operations - name: Inbound Webhook Management description: Operations for managing inbound webhook connector configurations +- name: Principals + description: Principal identity and profile management - name: Entities Management description: Operations related to entity management - name: Audit @@ -28,7 +29,7 @@ tags: - name: Entity dynamic mapping description: Operations related to entity dynamic mapping management paths: - "/api/v1/inbound_webhooks/{identifier}": + /api/v1/inbound_webhooks/{identifier}: get: tags: - Inbound Webhook Management @@ -45,21 +46,20 @@ paths: '200': description: Webhook connector found content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/InboundWebhookDtoOut" + $ref: '#/components/schemas/InboundWebhookDtoOut' '404': description: Webhook connector not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' put: tags: - Inbound Webhook Management summary: Update an existing webhook connector by identifier - description: Update the details of an existing webhook connector identified - by its unique string identifier + description: Update the details of an existing webhook connector identified by its unique string identifier operationId: putWebhookConnector parameters: - name: identifier @@ -71,33 +71,33 @@ paths: content: application/json: schema: - "$ref": "#/components/schemas/InboundWebhookUpdateDtoIn" + $ref: '#/components/schemas/InboundWebhookUpdateDtoIn' required: true responses: '200': description: Webhook connector updated successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/InboundWebhookDtoOut" - '400': - description: Invalid request payload - content: - "*/*": - schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/InboundWebhookDtoOut' '404': description: Webhook connector not found with the provided identifier content: - "*/*": + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' + '400': + description: Invalid request payload + content: + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '409': description: Webhook connector name already exists content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' delete: tags: - Inbound Webhook Management @@ -116,10 +116,10 @@ paths: '404': description: Webhook connector not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/entity_dynamic_mappings/{identifier}": + $ref: '#/components/schemas/ProblemDetail' + /api/v1/entity_dynamic_mappings/{identifier}: get: tags: - Entity dynamic mapping @@ -136,21 +136,20 @@ paths: '200': description: Entity dynamic mapping found content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDynamicMappingDtoOut" + $ref: '#/components/schemas/EntityDynamicMappingDtoOut' '404': description: Entity dynamic mapping not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' put: tags: - Entity dynamic mapping summary: Update an existing entity dynamic mapping by identifier - description: Update the details of an existing entity dynamic mapping identified - by its unique string identifier + description: Update the details of an existing entity dynamic mapping identified by its unique string identifier operationId: updateEntityDynamicMapping parameters: - name: identifier @@ -162,34 +161,33 @@ paths: content: application/json: schema: - "$ref": "#/components/schemas/EntityDynamicMappingUpdateDtoIn" + $ref: '#/components/schemas/EntityDynamicMappingUpdateDtoIn' required: true responses: '200': description: Entity dynamic mapping updated successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDynamicMappingDtoOut" - '400': - description: Entity template identifier is mandatory or target entity template - not found - content: - "*/*": - schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/EntityDynamicMappingDtoOut' '404': description: Entity dynamic mapping not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' + '400': + description: Entity template identifier is mandatory or target entity template not found + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '409': description: Target entity template not found or identifier already exists content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' delete: tags: - Entity dynamic mapping @@ -208,10 +206,10 @@ paths: '404': description: Entity dynamic mapping not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/entity-templates/{identifier}": + $ref: '#/components/schemas/ProblemDetail' + /api/v1/entity-templates/{identifier}: get: tags: - Entities Templates Management @@ -228,21 +226,20 @@ paths: '200': description: Template found content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityTemplateDtoOut" + $ref: '#/components/schemas/EntityTemplateDtoOut' '404': description: Template not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' put: tags: - Entities Templates Management summary: Update an existing template by template identifier - description: Update the details of an existing template identified by its unique - string identifier + description: Update the details of an existing template identified by its unique string identifier operationId: updateTemplate parameters: - name: identifier @@ -254,21 +251,21 @@ paths: content: application/json: schema: - "$ref": "#/components/schemas/EntityTemplateUpdateDtoIn" + $ref: '#/components/schemas/EntityTemplateUpdateDtoIn' required: true responses: '200': description: Template update successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityTemplateDtoOut" + $ref: '#/components/schemas/EntityTemplateDtoOut' '404': description: Template not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' delete: tags: - Entities Templates Management @@ -287,24 +284,23 @@ paths: '400': description: 'Cannot delete template: it is a target for other relations' content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '404': description: Template not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/entities/{templateIdentifier}/{entityIdentifier}": + $ref: '#/components/schemas/ProblemDetail' + /api/v1/entities/{templateIdentifier}/{entityIdentifier}: get: tags: - Entities Management summary: Get entity by entity template and identifier - description: Retrieve a specific entity using its string identifier and its - template identifier with configurable relationship graph traversal. Supports - fetching both inbound and outbound relations up to a specified depth using - direct lineage mode. + description: Retrieve a specific entity using its string identifier and its template identifier with configurable relationship + graph traversal. Supports fetching both inbound and outbound relations up to a specified depth using direct lineage + mode. operationId: getEntity parameters: - name: templateIdentifier @@ -319,8 +315,7 @@ paths: type: string - name: relations_depth in: query - description: 'Maximum depth to traverse when collecting entity relations. - Defaults to 1. Valid range: 1-6.' + description: 'Maximum depth to traverse when collecting entity relations. Defaults to 1. Valid range: 1-6.' required: false schema: type: integer @@ -329,26 +324,32 @@ paths: minimum: 1 - name: relations_to_display in: query - description: Comma-separated list of relation names to filter the response. - Only relations that form a connected chain from the root entity are included. - Isolated relations (not reachable from the root) are excluded even if listed. + description: Comma-separated list of relation names to filter the response. Only relations that form a connected chain + from the root entity are included. Isolated relations (not reachable from the root) are excluded even if listed. When omitted, all reachable relations are included. required: false schema: type: array + - name: include_relations_properties + in: query + description: When true, include property values for related entities. Defaults to false. + required: false + schema: + type: boolean + default: false responses: '200': description: Entity found content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDtoOut" + $ref: '#/components/schemas/EntityDtoOut' '404': description: Entity not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' put: tags: - Entities Management @@ -372,43 +373,52 @@ paths: content: application/json: schema: - "$ref": "#/components/schemas/EntityUpdateDtoIn" + $ref: '#/components/schemas/EntityUpdateDtoIn' required: true responses: '200': description: Entity updated successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDtoOut" + $ref: '#/components/schemas/EntityDtoOut' '400': description: Invalid entity data provided content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '401': description: Unauthorized - Missing or invalid token + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '403': description: Insufficient rights + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '404': description: Entity not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '500': description: Unexpected server-side failure content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - patch: + $ref: '#/components/schemas/ProblemDetail' + delete: tags: - Entities Management - summary: Partially update an existing entity - description: Partially update an existing entity in the system with the provided information - operationId: patchEntity + summary: Delete an existing entity + description: Delete an entity from the system using its template and entity identifiers. This operation removes the + entity and automatically cleans up any relations from other entities that reference it. + operationId: deleteEntity parameters: - name: templateIdentifier in: path @@ -422,49 +432,51 @@ paths: schema: type: string minLength: 1 - requestBody: - content: - application/json: - schema: - "$ref": "#/components/schemas/EntityPatchDtoIn" - required: true responses: - '200': - description: Entity updated successfully - content: - "*/*": - schema: - "$ref": "#/components/schemas/EntityDtoOut" + '204': + description: Entity deleted successfully '400': description: Invalid entity data provided content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '401': description: Unauthorized - Missing or invalid token + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '403': description: Insufficient rights + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '404': description: Entity not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' + '409': + description: Target entity has required relations + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '500': description: Unexpected server-side failure content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - delete: + $ref: '#/components/schemas/ProblemDetail' + patch: tags: - Entities Management - summary: Delete an existing entity - description: Delete an entity from the system using its template and entity - identifiers. This operation removes the entity and automatically cleans up - any relations from other entities that reference it. - operationId: deleteEntity + summary: Partially update an existing entity + description: Partially update an existing entity in the system with the provided information + operationId: patchEntity parameters: - name: templateIdentifier in: path @@ -478,38 +490,50 @@ paths: schema: type: string minLength: 1 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/EntityPatchDtoIn' + required: true responses: - '204': - description: Entity deleted successfully + '200': + description: Entity updated successfully + content: + '*/*': + schema: + $ref: '#/components/schemas/EntityDtoOut' '400': description: Invalid entity data provided content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '401': description: Unauthorized - Missing or invalid token + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '403': description: Insufficient rights - '404': - description: Entity not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - '409': - description: Target entity has required relations + $ref: '#/components/schemas/ProblemDetail' + '404': + description: Entity not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '500': description: Unexpected server-side failure content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/webhooks/{webhookIdentifier}": + $ref: '#/components/schemas/ProblemDetail' + /webhooks/{webhookIdentifier}: post: tags: - spring-boot-platform-http-consumer @@ -517,7 +541,7 @@ paths: responses: '200': description: OK - "/api/v1/inbound_webhooks": + /api/v1/inbound_webhooks: get: tags: - Inbound Webhook Management @@ -529,24 +553,23 @@ paths: in: query description: Page number for pagination. Defaults to 0. content: - "*/*": + '*/*': schema: type: integer default: '0' - name: size in: query - description: Number of items per page. Defaults to 20. + description: Number of items per page. Defaults to 20. Must be between 1 and 500. content: - "*/*": + '*/*': schema: type: integer default: '20' - name: sort in: query - description: 'Sorting criteria in the format: property(,asc|desc). Defaults - to identifier,asc.' + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' content: - "*/*": + '*/*': schema: type: string default: identifier,asc @@ -554,78 +577,75 @@ paths: '200': description: Paginated webhook connector retrieved successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/WebhookConnectorPageResponse" + $ref: '#/components/schemas/WebhookConnectorPageResponse' '400': description: Invalid pagination parameters content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' post: tags: - Inbound Webhook Management summary: Create a new webhook connector configuration - description: Creates a webhook connector configuration used by the generic inbound - webhook endpoint + description: Creates a webhook connector configuration used by the generic inbound webhook endpoint operationId: createInboundWebhook requestBody: content: application/json: schema: - "$ref": "#/components/schemas/InboundWebhookCreateDtoIn" + $ref: '#/components/schemas/InboundWebhookCreateDtoIn' required: true responses: '201': description: Webhook connector created content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/InboundWebhookDtoOut" + $ref: '#/components/schemas/InboundWebhookDtoOut' '400': description: Invalid webhook connector data provided content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/InboundWebhookDtoOut" + $ref: '#/components/schemas/InboundWebhookDtoOut' '409': description: Webhook connector already exists in this entityTemplateIdentifier content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/InboundWebhookDtoOut" - "/api/v1/entity_dynamic_mappings": + $ref: '#/components/schemas/InboundWebhookDtoOut' + /api/v1/entity_dynamic_mappings: get: tags: - Entity dynamic mapping summary: Get paginated entity dynamic mappings - description: Retrieve a paginated list of entity dynamic mappings with optional - sorting + description: Retrieve a paginated list of entity dynamic mappings with optional sorting operationId: getEntityDynamicMappingPaginated parameters: - name: page in: query description: Page number for pagination. Defaults to 0. content: - "*/*": + '*/*': schema: type: integer default: '0' - name: size in: query - description: Number of items per page. Defaults to 20. + description: Number of items per page. Defaults to 20. Must be between 1 and 500. content: - "*/*": + '*/*': schema: type: integer default: '20' - name: sort in: query - description: 'Sorting criteria in the format: property(,asc|desc). Defaults - to identifier,asc.' + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' content: - "*/*": + '*/*': schema: type: string default: identifier,asc @@ -633,88 +653,86 @@ paths: '200': description: Paginated entity dynamic mapping retrieved successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDynamicMappingPageResponse" + $ref: '#/components/schemas/EntityDynamicMappingPageResponse' '400': description: Invalid pagination parameters content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' post: tags: - Entity dynamic mapping summary: Create entity dynamic mapping - description: Creates a new entity dynamic mapping used by the generic inbound - webhook endpoint + description: Creates a new entity dynamic mapping used by the generic inbound webhook endpoint operationId: createDynamicMapping requestBody: content: application/json: schema: - "$ref": "#/components/schemas/EntityDynamicMappingCreateDtoIn" + $ref: '#/components/schemas/EntityDynamicMappingCreateDtoIn' required: true responses: '201': description: Entity dynamic mapping created content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDynamicMappingDtoOut" + $ref: '#/components/schemas/EntityDynamicMappingDtoOut' '400': description: Invalid entity dynamic mapping data provided content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDynamicMappingDtoOut" + $ref: '#/components/schemas/EntityDynamicMappingDtoOut' '409': description: Identifier already exists content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDynamicMappingDtoOut" - "/api/v1/entity_dynamic_mappings/dry-run": + $ref: '#/components/schemas/EntityDynamicMappingDtoOut' + /api/v1/entity_dynamic_mappings/dry-run: post: tags: - Entity dynamic mapping summary: Validate a single entity dynamic mapping with a dry-run - description: Validate one JSLT mapping definition against a sample payload and - target template identifier without persisting any data + description: Validate one JSLT mapping definition against a sample payload and target template identifier without persisting + any data operationId: executeDryRun requestBody: content: application/json: schema: - "$ref": "#/components/schemas/EntityDynamicMappingDryRunDtoIn" + $ref: '#/components/schemas/EntityDynamicMappingDryRunDtoIn' required: true responses: '200': description: Dry-run completed successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDynamicMappingDryRunDtoOut" + $ref: '#/components/schemas/EntityDynamicMappingDryRunDtoOut' '400': description: Invalid entity dynamic mapping data provided content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '404': description: Entity template not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '422': - description: Mapping validation, template validation or expression evaluation - error + description: Mapping validation, template validation or expression evaluation error content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/entity-templates": + $ref: '#/components/schemas/ProblemDetail' + /api/v1/entity-templates: get: tags: - Entities Templates Management @@ -726,24 +744,23 @@ paths: in: query description: Page number for pagination. Defaults to 0. content: - "*/*": + '*/*': schema: type: integer default: '0' - name: size in: query - description: Number of items per page. Defaults to 20. + description: Number of items per page. Defaults to 20. Must be between 1 and 500. content: - "*/*": + '*/*': schema: type: integer default: '20' - name: sort in: query - description: 'Sorting criteria in the format: property(,asc|desc). Defaults - to identifier,asc.' + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' content: - "*/*": + '*/*': schema: type: string default: identifier,asc @@ -751,15 +768,15 @@ paths: '200': description: Paginated templates retrieved successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/TemplatePageResponse" + $ref: '#/components/schemas/TemplatePageResponse' '400': description: Invalid pagination parameters content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' post: tags: - Entities Templates Management @@ -770,22 +787,22 @@ paths: content: application/json: schema: - "$ref": "#/components/schemas/EntityTemplateCreateDtoIn" + $ref: '#/components/schemas/EntityTemplateCreateDtoIn' required: true responses: '201': description: Template created successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityTemplateDtoOut" + $ref: '#/components/schemas/EntityTemplateDtoOut' '400': description: Invalid template data provided content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/entities/{templateIdentifier}": + $ref: '#/components/schemas/ProblemDetail' + /api/v1/entities/{templateIdentifier}: get: tags: - Entities Management @@ -798,58 +815,66 @@ paths: description: Page number for pagination. Defaults to 0. required: false content: - "*/*": + '*/*': schema: type: integer default: '0' - name: size in: query - description: Number of items per page. Defaults to 20. + description: Number of items per page. Defaults to 20. Must be between 1 and 500. required: false content: - "*/*": + '*/*': schema: type: integer default: '20' + - name: sort + in: query + description: 'Sorting criteria in the format: field[,asc|desc]' + required: false + content: + "*/*": + schema: + type: string + default: identifier,asc - name: templateIdentifier in: path required: true schema: type: string - - name: q + - name: sort in: query - description: 'Optional filter query using a simple expression language. See - more details in the API documentation. Example: `name:idp` for entities - with names containing ''idp''. - - ' + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' required: false content: - "*/*": + '*/*': schema: type: string - - name: sort + default: identifier,asc + - name: q in: query - description: 'Sorting criteria in the format: property(,asc|desc). Defaults - to identifier,asc.' + description: 'Optional filter query using a simple expression language. See more details in the API documentation. + Example: `name:idp` for entities with names containing ''idp''. + + ' + required: false content: - "*/*": + '*/*': schema: type: string - default: identifier,asc responses: '200': description: Paginated entities retrieved successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityPageResponse" + $ref: '#/components/schemas/EntityPageResponse' '400': description: Invalid filter query syntax content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' post: tags: - Entities Management @@ -867,79 +892,99 @@ paths: content: application/json: schema: - "$ref": "#/components/schemas/EntityCreateDtoIn" + $ref: '#/components/schemas/EntityCreateDtoIn' required: true responses: '201': description: Entity created successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityDtoOut" + $ref: '#/components/schemas/EntityDtoOut' '400': description: Invalid entity data provided content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '401': description: Unauthorized - Missing or invalid token + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '403': description: Insufficient rights - '404': - description: Template not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '409': description: Entity already exists in this template content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' + '404': + description: Template not found with the provided identifier + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '500': description: Unexpected server-side failure content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/entities/search": + $ref: '#/components/schemas/ProblemDetail' + /api/v1/entities/search: post: tags: - Entities Management summary: Search entities - description: Search for entities across all templates using nested filter queries. - Supports complex logical compositions (AND / OR) of filter criteria on template, - identifier, name, properties, relations, and reverse relations. + description: Search for entities across all templates using nested filter queries. Supports complex logical compositions + (AND / OR) of filter criteria on template, identifier, name, properties, relations, and reverse relations. operationId: searchEntities requestBody: content: application/json: schema: - "$ref": "#/components/schemas/EntitySearchRequestDtoIn" + $ref: '#/components/schemas/EntitySearchRequestDtoIn' + examples: + Entity search: + description: Entity search + value: + query: test + filter: + connector: AND + criteria: + - field: template + operation: EQ + value: service + page: 0 + size: 20 + sort: identifier,asc required: true responses: '200': description: Entities retrieved successfully content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityPageResponse" + $ref: '#/components/schemas/EntityPageResponse' '400': description: Invalid search filter content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/entities/{templateIdentifier}/{entityIdentifier}/graph": + $ref: '#/components/schemas/ProblemDetail' + /api/v1/entities/{templateIdentifier}/{entityIdentifier}/graph: get: tags: - Entity Graph summary: Get entity relationship graph as flat nodes and edges - description: Retrieves the entity relationship graph as a flat nodes-and-edges - structure, suitable for frontend visualization tools such as React Flow, Vis.js, - and Cytoscape. + description: Retrieves the entity relationship graph as a flat nodes-and-edges structure, suitable for frontend visualization + tools such as React Flow, Vis.js, and Cytoscape. operationId: getEntityGraph parameters: - name: templateIdentifier @@ -956,8 +1001,7 @@ paths: minLength: 1 - name: depth in: query - description: Maximum traversal depth for relationship resolution. Clamped - between 1 and 6. + description: Maximum traversal depth for relationship resolution. Clamped between 1 and 6. required: false schema: type: integer @@ -965,16 +1009,15 @@ paths: default: 1 - name: include_data in: query - description: When true, each graph node includes a data object containing - the entity's property values. Defaults to false. + description: When true, each graph node includes a data object containing the entity's property values. Defaults to + false. required: false schema: type: boolean default: false - name: traversal_mode in: query - description: Specifies the traversal mode for the entity graph. Defaults to - DIRECT_LINEAGE. + description: Specifies the traversal mode for the entity graph. Defaults to DIRECT_LINEAGE. required: false schema: type: string @@ -985,8 +1028,8 @@ paths: - OUTBOUND_ONLY - name: relations in: query - description: When provided, only relations whose name matches one of the listed - values are traversed and included. Omit to include all relations. + description: When provided, only relations whose name matches one of the listed values are traversed and included. + Omit to include all relations. required: false schema: type: array @@ -994,9 +1037,8 @@ paths: type: string - name: properties in: query - description: When provided, each node's data object is restricted to the listed - property names. Requires include_data=true to have any effect. Omit to include - all properties. + description: When provided, each node's data object is restricted to the listed property names. Requires include_data=true + to have any effect. Omit to include all properties. required: false schema: type: array @@ -1006,22 +1048,92 @@ paths: '200': description: Flat entity graph successfully retrieved content: - "*/*": + '*/*': schema: - "$ref": "#/components/schemas/EntityGraphFlatDtoOut" + $ref: '#/components/schemas/EntityGraphFlatDtoOut' + '400': + description: Invalid graph query parameter value + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '404': description: Entity not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/audit/entities/{templateIdentifier}/{entityIdentifier}": + $ref: '#/components/schemas/ProblemDetail' + /api/v1/entities/principals/me: + get: + tags: + - Principals + summary: Get current authenticated principal + description: 'Returns the Principal entity of the currently authenticated actor (human or service account). + + The principal is automatically provisioned via JIT if this is the first authentication. + + + **Response includes:** + + - Principal identifier (unique ID) + + - Display name + + - Principal kind (HUMAN or SERVICE_ACCOUNT) + + - Attributes (email, client_id, etc.) + + - Group memberships (via relations) + + + **Use cases:** + + - Profile inspection: "Who am I?" + + - Authorization context retrieval + + - Service account validation + + ' + operationId: getCurrentPrincipal + responses: + '200': + description: Principal entity retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/EntityDtoOut' + '401': + description: Unauthorized - Missing or invalid token + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' + '403': + description: Insufficient rights + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' + '404': + description: Principal not found in catalog (JIT provisioning may have failed) + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' + '500': + description: Unexpected server-side failure + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' + /api/v1/audit/entities/{templateIdentifier}/{entityIdentifier}: get: tags: - Audit summary: Get entity audit history - description: Retrieve the complete audit history for a specific entity, including - all revisions with timestamps and modification types + description: Retrieve the complete audit history for a specific entity, including all revisions with timestamps and + modification types operationId: getEntityAuditHistory parameters: - name: templateIdentifier @@ -1040,35 +1152,42 @@ paths: '200': description: Successfully retrieved entity audit history content: - "*/*": + '*/*': schema: type: array items: - "$ref": "#/components/schemas/EntityAuditDtoOut" + $ref: '#/components/schemas/EntityAuditDtoOut' '400': description: Invalid template or entity identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '401': description: Unauthorized - Missing or invalid token + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '403': description: Insufficient rights + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ProblemDetail' '404': - description: Template not found with the provided identifier or Entity not - found with the provided identifier + description: Template not found with the provided identifier or Entity not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '500': description: Unexpected server-side failure content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/actuator": + $ref: '#/components/schemas/ProblemDetail' + /actuator: get: tags: - Actuator @@ -1084,22 +1203,22 @@ paths: additionalProperties: type: object additionalProperties: - "$ref": "#/components/schemas/Link" + $ref: '#/components/schemas/Link' application/vnd.spring-boot.actuator.v2+json: schema: type: object additionalProperties: type: object additionalProperties: - "$ref": "#/components/schemas/Link" + $ref: '#/components/schemas/Link' application/json: schema: type: object additionalProperties: type: object additionalProperties: - "$ref": "#/components/schemas/Link" - "/actuator/health": + $ref: '#/components/schemas/Link' + /actuator/health: get: tags: - Actuator @@ -1125,14 +1244,10 @@ components: properties: type: type: string - minLength: 1 config: type: object additionalProperties: type: string - required: - - config - - type InboundWebhookUpdateDtoIn: type: object properties: @@ -1149,7 +1264,7 @@ components: items: type: string security: - "$ref": "#/components/schemas/InboundWebhookSecurityContractDtoIn" + $ref: '#/components/schemas/InboundWebhookSecurityContractDtoIn' required: - name EntityDynamicMappingDtoOut: @@ -1173,7 +1288,7 @@ components: description: type: string entity: - "$ref": "#/components/schemas/InboundWebhookEntityMappingDtoOut" + $ref: '#/components/schemas/InboundWebhookEntityMappingDtoOut' InboundWebhookDtoOut: type: object properties: @@ -1188,9 +1303,9 @@ components: mappings: type: array items: - "$ref": "#/components/schemas/EntityDynamicMappingDtoOut" + $ref: '#/components/schemas/EntityDynamicMappingDtoOut' security: - "$ref": "#/components/schemas/InboundWebhookSecurityDtoOut" + $ref: '#/components/schemas/InboundWebhookSecurityDtoOut' InboundWebhookEntityMappingDtoOut: type: object properties: @@ -1205,7 +1320,7 @@ components: relations: type: array items: - "$ref": "#/components/schemas/RelationMappingDtoOut" + $ref: '#/components/schemas/RelationMappingDtoOut' InboundWebhookSecurityDtoOut: type: object properties: @@ -1224,13 +1339,32 @@ components: type: array items: type: string - ErrorResponse: + ProblemDetail: type: object properties: + type: + type: string + format: uri + title: + type: string + status: + type: integer + format: int32 + detail: + type: string + instance: + type: string + format: uri error: type: string + description: HTTP status name, e.g. NOT_FOUND error_description: type: string + description: Human-readable description of the error + timestamp: + type: string + format: date-time + description: Instant at which the error occurred EntityDynamicMappingRelationDtoIn: type: object properties: @@ -1268,7 +1402,7 @@ components: description: type: string entity: - "$ref": "#/components/schemas/EntityMappingDtoIn" + $ref: '#/components/schemas/EntityMappingDtoIn' required: - action - entity @@ -1291,7 +1425,7 @@ components: relations: type: array items: - "$ref": "#/components/schemas/EntityDynamicMappingRelationDtoIn" + $ref: '#/components/schemas/EntityDynamicMappingRelationDtoIn' required: - identifier - name @@ -1305,7 +1439,7 @@ components: example: Service maxLength: 255 minLength: 0 - pattern: "^[a-zA-Z0-9 _-]+$" + pattern: ^[a-zA-Z0-9 _-]+$ description: type: string description: Entity Template description @@ -1314,12 +1448,12 @@ components: type: array description: List of property definitions for this template items: - "$ref": "#/components/schemas/PropertyDefinitionDtoIn" + $ref: '#/components/schemas/PropertyDefinitionDtoIn' relations_definitions: type: array description: List of relation definitions for this template items: - "$ref": "#/components/schemas/RelationDefinitionDtoIn" + $ref: '#/components/schemas/RelationDefinitionDtoIn' required: - name PropertyDefinitionDtoIn: @@ -1350,7 +1484,7 @@ components: description: Whether this property is required example: true rules: - "$ref": "#/components/schemas/PropertyRulesDtoIn" + $ref: '#/components/schemas/PropertyRulesDtoIn' description: Property validation rules required: - description @@ -1378,7 +1512,7 @@ components: regex: type: string description: Regular expression pattern for validation - example: "^[a-zA-Z0-9]+$" + example: ^[a-zA-Z0-9]+$ max_length: type: integer format: int32 @@ -1446,12 +1580,12 @@ components: type: array description: List of property definitions for this template items: - "$ref": "#/components/schemas/PropertyDefinitionDtoOut" + $ref: '#/components/schemas/PropertyDefinitionDtoOut' relations_definitions: type: array description: List of relation definitions for this template items: - "$ref": "#/components/schemas/RelationDefinitionDtoOut" + $ref: '#/components/schemas/RelationDefinitionDtoOut' PropertyDefinitionDtoOut: type: object description: Output DTO for property definition @@ -1477,7 +1611,7 @@ components: description: Whether this property is required example: true rules: - "$ref": "#/components/schemas/PropertyRulesDtoOut" + $ref: '#/components/schemas/PropertyRulesDtoOut' description: Property validation rules example: Property validation rules PropertyRulesDtoOut: @@ -1502,7 +1636,7 @@ components: regex: type: string description: Regular expression for property validation - example: "^[A-Za-z0-9]+$" + example: ^[A-Za-z0-9]+$ max_length: type: integer format: int32 @@ -1564,27 +1698,9 @@ components: type: array description: List of relations for this entity items: - "$ref": "#/components/schemas/RelationDtoIn" + $ref: '#/components/schemas/RelationDtoIn' required: - name - EntityPatchDtoIn: - type: object - description: Input DTO for partially updating an entity. Omitted fields remain unchanged. - properties: - name: - type: string - description: Name of the entity - example: my-web-service-updated - properties: - type: object - additionalProperties: - type: string - description: Properties to merge with the existing entity properties - relations: - type: array - description: Relations to merge with the existing entity relations - items: - "$ref": "#/components/schemas/RelationDtoIn" RelationDtoIn: type: object description: Input DTO for an entity relation instance @@ -1622,7 +1738,7 @@ components: additionalProperties: type: array items: - "$ref": "#/components/schemas/EntitySummaryDto" + $ref: '#/components/schemas/EntitySummaryDto' EntitySummaryDto: type: object properties: @@ -1632,6 +1748,10 @@ components: type: string template_identifier: type: string + properties: + type: object + additionalProperties: {} + description: Property values for the related entity; included only when include_relations_properties=true InboundWebhookCreateDtoIn: type: object properties: @@ -1652,7 +1772,7 @@ components: items: type: string security: - "$ref": "#/components/schemas/InboundWebhookSecurityContractDtoIn" + $ref: '#/components/schemas/InboundWebhookSecurityContractDtoIn' required: - identifier - name @@ -1681,7 +1801,7 @@ components: description: type: string entity: - "$ref": "#/components/schemas/EntityMappingDtoIn" + $ref: '#/components/schemas/EntityMappingDtoIn' required: - action - entity @@ -1694,7 +1814,7 @@ components: description: Request payload for a single entity dynamic mapping dry-run validation properties: mapping: - "$ref": "#/components/schemas/EntityDynamicMappingCreateDtoIn" + $ref: '#/components/schemas/EntityDynamicMappingCreateDtoIn' payload: description: Sample JSON payload to test against the webhook mapping configuration required: @@ -1721,7 +1841,7 @@ components: type: array description: Extracted relations items: - "$ref": "#/components/schemas/DryRunRelationDto" + $ref: '#/components/schemas/DryRunRelationDto' DryRunEntityResultDto: type: object properties: @@ -1732,10 +1852,10 @@ components: type: boolean description: Whether the mapping was successful entity: - "$ref": "#/components/schemas/DryRunEntityDto" + $ref: '#/components/schemas/DryRunEntityDto' description: Mapped entity data error: - "$ref": "#/components/schemas/DryRunErrorDto" + $ref: '#/components/schemas/DryRunErrorDto' description: Error details DryRunErrorDto: type: object @@ -1765,7 +1885,7 @@ components: type: array description: List of entity mapping results items: - "$ref": "#/components/schemas/DryRunEntityResultDto" + $ref: '#/components/schemas/DryRunEntityResultDto' EntityTemplateCreateDtoIn: type: object description: Input DTO for creating an entity template @@ -1781,7 +1901,7 @@ components: example: Service maxLength: 255 minLength: 0 - pattern: "^[a-zA-Z0-9 _-]+$" + pattern: ^[a-zA-Z0-9 _-]+$ description: type: string description: Entity Template description @@ -1790,12 +1910,12 @@ components: type: array description: List of property definitions for this template items: - "$ref": "#/components/schemas/PropertyDefinitionDtoIn" + $ref: '#/components/schemas/PropertyDefinitionDtoIn' relations_definitions: type: array description: List of relation definitions for this template items: - "$ref": "#/components/schemas/RelationDefinitionDtoIn" + $ref: '#/components/schemas/RelationDefinitionDtoIn' required: - identifier - name @@ -1825,7 +1945,7 @@ components: type: array description: List of relations for this entity items: - "$ref": "#/components/schemas/RelationDtoIn" + $ref: '#/components/schemas/RelationDtoIn' required: - identifier - name @@ -1835,14 +1955,12 @@ components: properties: query: type: string - description: Free-text search string. When present, returns entities whose - identifier, name, templateIdentifier, or any property value contains this - string (case-insensitive). Can be combined with filter. + description: Free-text search string. When present, returns entities whose identifier, name, templateIdentifier, + or any property value contains this string (case-insensitive). Can be combined with filter. example: checkout filter: - "$ref": "#/components/schemas/FilterNodeDtoIn" - description: Root node of the search filter tree. May be omitted or null - to return all entities. + $ref: '#/components/schemas/FilterNodeDtoIn' + description: Root node of the search filter tree. May be omitted or null to return all entities. page: type: integer format: int32 @@ -1853,45 +1971,39 @@ components: type: integer format: int32 default: 20 - description: Number of items per page. Defaults to 20. + description: Number of items per page. Defaults to 20. Must be between 1 and 500. example: 20 sort: type: string - description: 'Sorting criteria in the format: property(,asc|desc). Defaults - to identifier,asc.' - example: identifier:asc + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' + example: identifier,asc FilterNodeDtoIn: type: object - description: A node in the search filter tree. Either a logical group (connector - + criteria) or a leaf criterion (field + operation + value). + description: A node in the search filter tree. Either a logical group (connector + criteria) or a leaf criterion (field + + operation + value). properties: connector: type: string - description: 'Logical connector for a group node. One of: AND, OR. Required - for group nodes.' + description: 'Logical connector for a group node. One of: AND, OR. Required for group nodes.' example: AND criteria: type: array - description: Child filter nodes for a group node. Required for group nodes - (must be non-empty). + description: Child filter nodes for a group node. Required for group nodes (must be non-empty). items: - "$ref": "#/components/schemas/FilterNodeDtoIn" + $ref: '#/components/schemas/FilterNodeDtoIn' field: type: string - description: 'Field to filter on for a criterion node. Required for leaf - nodes. Examples: template, identifier, name, relation, property.language, - relation.api-link, relation.api-link.identifier, relations_as_target.api-link.name' + description: 'Field to filter on for a criterion node. Required for leaf nodes. Examples: template, identifier, + name, relation, property.language, relation.api-link, relation.api-link.identifier, relations_as_target.api-link.name' example: template operation: type: string - description: 'Filter operation for a criterion node. One of: EQ, NEQ, CONTAINS, - NOT_CONTAINS, STARTS_WITH, ENDS_WITH, GT, GTE, LT, LTE. Required for leaf - nodes.' + description: 'Filter operation for a criterion node. One of: EQ, NEQ, CONTAINS, NOT_CONTAINS, STARTS_WITH, ENDS_WITH, + GT, GTE, LT, LTE. Required for leaf nodes.' example: EQ value: type: string - description: Value to compare against for a criterion node. Required for - leaf nodes. + description: Value to compare against for a criterion node. Required for leaf nodes. example: microservice EntityPageResponse: type: object @@ -1900,24 +2012,24 @@ components: content: type: array items: - "$ref": "#/components/schemas/EntityDtoOut" + $ref: '#/components/schemas/EntityDtoOut' pageable: - "$ref": "#/components/schemas/PageableObject" + $ref: '#/components/schemas/PageableObject' + last: + type: boolean totalElements: type: integer format: int64 totalPages: type: integer format: int32 - last: - type: boolean - sort: - "$ref": "#/components/schemas/SortObject" first: type: boolean numberOfElements: type: integer format: int32 + sort: + $ref: '#/components/schemas/SortObject' size: type: integer format: int32 @@ -1929,6 +2041,9 @@ components: PageableObject: type: object properties: + offset: + type: integer + format: int64 paged: type: boolean pageNumber: @@ -1938,21 +2053,38 @@ components: type: integer format: int32 sort: - "$ref": "#/components/schemas/SortObject" + $ref: '#/components/schemas/SortObject' unpaged: type: boolean - offset: - type: integer - format: int64 SortObject: type: object properties: + empty: + type: boolean sorted: type: boolean unsorted: type: boolean - empty: - type: boolean + EntityPatchDtoIn: + type: object + description: Input DTO for partially updating an entity + properties: + name: + type: string + description: Name of the entity + example: my-web-service-updated + properties: + type: object + additionalProperties: + type: string + description: Map of property name to value for this entity + example: + port: '8080' + relations: + type: array + description: List of relations for this entity + items: + $ref: '#/components/schemas/RelationDtoIn' WebhookConnectorPageResponse: type: object description: Paginated response containing Inbound Webhook Connector objects @@ -1960,24 +2092,24 @@ components: content: type: array items: - "$ref": "#/components/schemas/InboundWebhookDtoOut" + $ref: '#/components/schemas/InboundWebhookDtoOut' pageable: - "$ref": "#/components/schemas/PageableObject" + $ref: '#/components/schemas/PageableObject' + last: + type: boolean totalElements: type: integer format: int64 totalPages: type: integer format: int32 - last: - type: boolean - sort: - "$ref": "#/components/schemas/SortObject" first: type: boolean numberOfElements: type: integer format: int32 + sort: + $ref: '#/components/schemas/SortObject' size: type: integer format: int32 @@ -1993,24 +2125,24 @@ components: content: type: array items: - "$ref": "#/components/schemas/EntityDynamicMappingDtoOut" + $ref: '#/components/schemas/EntityDynamicMappingDtoOut' pageable: - "$ref": "#/components/schemas/PageableObject" + $ref: '#/components/schemas/PageableObject' + last: + type: boolean totalElements: type: integer format: int64 totalPages: type: integer format: int32 - last: - type: boolean - sort: - "$ref": "#/components/schemas/SortObject" first: type: boolean numberOfElements: type: integer format: int32 + sort: + $ref: '#/components/schemas/SortObject' size: type: integer format: int32 @@ -2026,24 +2158,24 @@ components: content: type: array items: - "$ref": "#/components/schemas/EntityTemplateDtoOut" + $ref: '#/components/schemas/EntityTemplateDtoOut' pageable: - "$ref": "#/components/schemas/PageableObject" + $ref: '#/components/schemas/PageableObject' + last: + type: boolean totalElements: type: integer format: int64 totalPages: type: integer format: int32 - last: - type: boolean - sort: - "$ref": "#/components/schemas/SortObject" first: type: boolean numberOfElements: type: integer format: int32 + sort: + $ref: '#/components/schemas/SortObject' size: type: integer format: int32 @@ -2074,12 +2206,12 @@ components: type: array description: All entity nodes in the graph items: - "$ref": "#/components/schemas/EntityGraphNodeFlatDtoOut" + $ref: '#/components/schemas/EntityGraphNodeFlatDtoOut' edges: type: array description: All directed relation edges in the graph items: - "$ref": "#/components/schemas/EntityGraphEdgeDtoOut" + $ref: '#/components/schemas/EntityGraphEdgeDtoOut' EntityGraphNodeFlatDtoOut: type: object properties: @@ -2098,8 +2230,7 @@ components: data: type: object additionalProperties: {} - description: Entity property values keyed by property name; present only - when include_data=true is requested + description: Entity property values keyed by property name; present only when include_data=true is requested EntityAuditDtoOut: type: object description: Audit information for an entity revision @@ -2122,7 +2253,7 @@ components: description: Identifier of the user who performed the modification example: user@example.com snapshot: - "$ref": "#/components/schemas/EntitySnapshotDtoOut" + $ref: '#/components/schemas/EntitySnapshotDtoOut' description: Snapshot of the entity state at this revision EntitySnapshotDtoOut: type: object @@ -2144,12 +2275,12 @@ components: type: array description: Properties of the entity at this revision items: - "$ref": "#/components/schemas/PropertySnapshotDtoOut" + $ref: '#/components/schemas/PropertySnapshotDtoOut' relations: type: array description: Relations of the entity at this revision items: - "$ref": "#/components/schemas/RelationSnapshotDtoOut" + $ref: '#/components/schemas/RelationSnapshotDtoOut' PropertySnapshotDtoOut: type: object description: Snapshot of a property at a specific audit revision diff --git a/docs/uv.lock b/docs/uv.lock index 709fc259..005f2aa9 100644 --- a/docs/uv.lock +++ b/docs/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.14" [[package]] @@ -227,7 +227,7 @@ wheels = [ [[package]] name = "zensical" -version = "0.0.67" +version = "0.0.73" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "click" }, @@ -240,15 +240,14 @@ dependencies = [ { name = "pyyaml" }, { name = "tomli" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fc/11/d655563a922eb96bc930543132a6cb404971d980b36dcf7aa90751f4af8f/zensical-0.0.67.tar.gz", hash = "sha256:6691e79d1fec9e6235ded01a7d98c19342bfff144fceae7d043c4d3830890038", size = 4300450, upload-time = "2026-09-30T09:26:24.153Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/75/88/15bf6b4eef8895c37e96d6beb1c57fedcdcaa51527ba728869b81db0341d/zensical-0.0.67-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:2fbb86fb0773d32aab2ce5bb40be64a6962871ef049c925d633996a6f54d7130", size = 18057715, upload-time = "2026-09-30T09:26:01.536Z" }, - { url = "https://files.pythonhosted.org/packages/00/c0/bb8dd996633ba4ad2a0d73bd0b09381fff309cdccec965b0978746e22189/zensical-0.0.67-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:679a513ffb0013b6db3bd5aacbc73484f6a734df702e5ba41baf049753d38995", size = 17588275, upload-time = "2026-09-30T09:26:04.495Z" }, - { url = "https://files.pythonhosted.org/packages/c6/6b/f3aa259b9ee24a26de148d0d49a239683a43ecd985dd35b30cf0c3f5dead/zensical-0.0.67-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:100b21a42eb6f48c5f3fb89c7a4b3e3b12dcf6f7e2bd7da65b344842b1da30ad", size = 18039684, upload-time = "2026-09-30T09:26:06.963Z" }, - { url = "https://files.pythonhosted.org/packages/94/9c/f850af0905eb7319201f823a9fdedf32d0a479845dd3186e4a80f845f181/zensical-0.0.67-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:610c577a3d1200e21c443590e12334b46cb38ce0ef2dad12110afe19925160e2", size = 17988405, upload-time = "2026-09-30T09:26:09.578Z" }, - { url = "https://files.pythonhosted.org/packages/4b/ac/9a9210bb96cbeb848df301462ac2d557e67548366014f4fa33dac10385d8/zensical-0.0.67-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9ee6369a253c9ff18f3c221bb48ac8c82eda22cb46f03650b937be8786b00b9", size = 18508864, upload-time = "2026-09-30T09:26:11.917Z" }, - { url = "https://files.pythonhosted.org/packages/f5/5d/7180698732ca5cf566f88300fa9ec487d81e852392be98d84d7cbc7cca80/zensical-0.0.67-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7f9baff27363551dcdb4970936a126a714f7ac84fd646bb673e2676ff2ab526d", size = 18204439, upload-time = "2026-09-30T09:26:14.152Z" }, - { url = "https://files.pythonhosted.org/packages/9b/89/04d8768895a39bb0ea65c1275fca0af0b1e1e5f3722a075fbd77476c199a/zensical-0.0.67-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3e1a7b7d5edf58394df235ade589b187da8f97107b11056ca989dbd6d7e646cc", size = 18769301, upload-time = "2026-09-30T09:26:16.585Z" }, - { url = "https://files.pythonhosted.org/packages/79/63/45108c9b220d73af5dc3577edf48c63f4336d7d80295fa2abc8c6ee3a4fe/zensical-0.0.67-cp310-abi3-win_amd64.whl", hash = "sha256:df5cc21899b4a5f3956d959e403dc754d7abcdcc2704c40dc43cff84e257b037", size = 18700647, upload-time = "2026-09-30T09:26:19.028Z" }, - { url = "https://files.pythonhosted.org/packages/93/43/09836dcb02085b7da0339d753b2b153352205209bfe14a3e16ec56740a0d/zensical-0.0.67-cp310-abi3-win_arm64.whl", hash = "sha256:20fb40bd0b8d05be92a793887e312de5b522fbda8fbdf80267395fd97baefc7b", size = 18120901, upload-time = "2026-09-30T09:26:21.683Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/e8/49/1dada916f2537c065da395e0188fdc83d66a983af9926cf188e7150ce0cc/zensical-0.0.73.tar.gz", hash = "sha256:ddeca0695e1015a4fbd09b9a9e50e77a2bb43753bf7479dfb23255f35fd14450", size = 4350383, upload-time = "2026-10-26T13:04:05.768Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/94/bc67421deb1e2c06776545d2450ec8142b132f587240ec87d33d3f196fe5/zensical-0.0.73-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:7bf70ebdb80628e17b5597d5da5669514df37b9e983b2c40e814b65c0f1bd9e1", size = 18278864, upload-time = "2026-10-26T12:05:47.987Z" }, + { url = "https://files.pythonhosted.org/packages/e2/bf/6fda434e479e86fbc9c32d14a1641ac7a75d4ed07c840420e13049bd2f41/zensical-0.0.73-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:8411c5c16cefd04e139dedbdc38ae59cf503e4cc83b03613a790bbab64e2aace", size = 17799234, upload-time = "2026-10-26T12:05:51.043Z" }, + { url = "https://files.pythonhosted.org/packages/24/ec/82c3964ae15db6659150f01217ac858355e6cd10f0ac65f8d9be9fa609d3/zensical-0.0.73-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9e27878c515ef1695b3587b762c2738c93dee1a0412c4c9b240583a968535e45", size = 18300892, upload-time = "2026-10-26T12:05:53.953Z" }, + { url = "https://files.pythonhosted.org/packages/e1/a5/0a6ac4434cbaa7764ecf7d41a54b8ea81ae08c24fd2f5414cb61a60b0598/zensical-0.0.73-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:78b45462e8925f8eb1d45aeed09dea1450c57d2533bfc28214af4a4a9e910e9e", size = 18798355, upload-time = "2026-10-26T12:05:58.838Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0a/6d9b7a36b6f950e124b1711de16588da1d4e436097c94afede8d8de4d8d9/zensical-0.0.73-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:5c79302dec347e1d2c7b3e0961ac56c97134f59c6f5cff786b81accf50b3bbb2", size = 18476606, upload-time = "2026-10-26T12:06:01.184Z" }, + { url = "https://files.pythonhosted.org/packages/08/d6/1e9b02225ceb6905c50d320e8e9edd3d541de4243b785d6c4313e605ec36/zensical-0.0.73-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:02a20d9cce5a5b976671d02550a8e65fcea49230a12978bf3c13b497f542ea16", size = 19057264, upload-time = "2026-10-26T12:06:03.485Z" }, + { url = "https://files.pythonhosted.org/packages/35/b8/6f894a0efe07863f0b16afc7c0aa524fd33efb3565c338b89a8c3a9b0c04/zensical-0.0.73-cp311-abi3-win_amd64.whl", hash = "sha256:d8f7b9e03a6280f67f55afd1a9a17937778d77ba7490124b11393bb79220a60d", size = 19005486, upload-time = "2026-10-26T13:04:00.768Z" }, + { url = "https://files.pythonhosted.org/packages/3c/18/1b25f5d450fbc3145d595f9d3a414ae993da6db002b476f68eb8f9c17bd0/zensical-0.0.73-cp311-abi3-win_arm64.whl", hash = "sha256:a68b0d23b9de360a1f1867c56c786d77947616eca42195c4cc1f18a1e1686bbf", size = 18408634, upload-time = "2026-10-26T13:04:03.376Z" }, ] diff --git a/flyway-migration-order-report.md b/flyway-migration-order-report.md deleted file mode 100644 index e69de29b..00000000 diff --git a/mvnw b/mvnw index df1a80ac..1ddd97b9 100755 --- a/mvnw +++ b/mvnw @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version @@project.version@@ +# Apache Maven Wrapper startup batch script, version 3.3.4 # # Required ENV vars: # ------------------ @@ -220,9 +220,9 @@ else log "Couldn't find $wrapperJarPath, downloading it ..." if [ -n "$MVNW_REPOURL" ]; then - wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/@@project.version@@/maven-wrapper-@@project.version@@.jar" + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar" else - wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/@@project.version@@/maven-wrapper-@@project.version@@.jar" + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar" fi while IFS="=" read -r key value; do case "$key" in wrapperUrl) @@ -290,7 +290,7 @@ done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" if [ -n "$wrapperSha256Sum" ]; then wrapperSha256Result=false if command -v sha256sum >/dev/null; then - if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c --strict - >/dev/null 2>&1; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - >/dev/null 2>&1; then wrapperSha256Result=true fi elif command -v shasum >/dev/null; then diff --git a/mvnw.cmd b/mvnw.cmd index 97fff177..c453424c 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,206 +1,206 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version @@project.version@@ -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* -if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. >&2 -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. >&2 -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. >&2 -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. >&2 -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/@@project.version@@/maven-wrapper-@@project.version@@.jar" - -FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/@@project.version@@/maven-wrapper-@@project.version@@.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %WRAPPER_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file -SET WRAPPER_SHA_256_SUM="" -FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B -) -IF NOT %WRAPPER_SHA_256_SUM%=="" ( - powershell -Command "&{"^ - "Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash;"^ - "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ - "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ - " Write-Error 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ - " Write-Error 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ - " Write-Error 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ - " exit 1;"^ - "}"^ - "}" - if ERRORLEVEL 1 goto error -) - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% ^ - %JVM_CONFIG_MAVEN_PROPS% ^ - %MAVEN_OPTS% ^ - %MAVEN_DEBUG_OPTS% ^ - -classpath %WRAPPER_JAR% ^ - "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ - %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" -if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%"=="on" pause - -if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% - -cmd /C exit /B %ERROR_CODE% +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. >&2 +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. >&2 +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. >&2 +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. >&2 +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash;"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Error 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Error 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Error 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index 456b4c59..031dcc4a 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 4.1.0 + 4.1.2 @@ -18,19 +18,16 @@ 25 - 2.2.52 - 1.18.46 - 7.4.0 + 2.2.55 + 1.18.48 + 9.2.0 1.21.4 - 3.15.0 - 0.8.15 - 1.2.1 + 3.16.0 + 0.8.16 + 1.2.2 1.6.3 - 1.4.2 - 4.2.16.Final - 7.1.0 - 7.0.8 - 42.7.12 + 1.5.1 + 4.2.20.Final 10.9.1 security @@ -73,15 +70,10 @@ org.apache.tomcat.embed tomcat-embed-el - - tools.jackson.core - jackson-databind - 3.1.5 - org.apache.camel.springboot camel-spring-boot-bom - 4.21.0 + 4.23.0 pom import @@ -103,7 +95,7 @@ org.apache.httpcomponents.client5 httpclient5 - 5.6.3 + 5.6.5 @@ -244,14 +236,14 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - 3.0.3 + 3.2.0 io.swagger.parser.v3 swagger-parser - 2.1.45 + 2.1.48 test @@ -268,16 +260,16 @@ org.apache.commons commons-lang3 - 3.20.0 + 3.21.0 + execution --> com.schibsted.spt.data jslt - 0.1.14 + 0.1.15 @@ -337,6 +329,21 @@ camel-rest-starter + + org.springframework.boot + spring-boot-starter-opentelemetry + + + + org.apache.camel.springboot + camel-opentelemetry2-starter + + + + org.apache.camel.springboot + camel-micrometer-starter + + @@ -361,13 +368,13 @@ org.sonarsource.scanner.maven sonar-maven-plugin - 5.7.0.6970 + 5.8.0.7211 org.flywaydb flyway-maven-plugin - 13.0.0 + 13.12.1 @@ -491,7 +498,7 @@ com.github.spotbugs spotbugs-maven-plugin - 4.10.3.0 + 4.10.5.0 true ${project.build.directory} @@ -510,7 +517,7 @@ com.github.codemonstur maven-check-license - 1.2.0 + 1.5.0 true passOnMatch @@ -545,6 +552,7 @@ org.hibernate.orm:hibernate-core:6.6.29.Final ch.qos.logback:logback-classic:1.5.34 ch.qos.logback:logback-core:1.5.34 + org.codehaus.mojo:animal-sniffer-annotations:1.26 @@ -561,7 +569,7 @@ com.diffplug.spotless spotless-maven-plugin - 3.8.0 + 3.11.0 diff --git a/src/main/java/com/decathlon/idp_core/domain/constant/JsltConstraints.java b/src/main/java/com/decathlon/idp_core/domain/constant/JsltConstraints.java new file mode 100644 index 00000000..2a0e4d67 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/constant/JsltConstraints.java @@ -0,0 +1,21 @@ +package com.decathlon.idp_core.domain.constant; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +/// Domain constants for JSLT mapping safety limits (DoS prevention). +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class JsltConstraints { + + /// Maximum size (in UTF-8 bytes) of a raw payload accepted for mapping. + public static final int MAX_PAYLOAD_BYTES = 1024 * 1024; + + /// Maximum JSON nesting depth of a raw payload accepted for mapping. + public static final int MAX_JSON_DEPTH = 64; + + /// Maximum length (in characters) of a JSLT expression. + public static final int MAX_EXPRESSION_LENGTH = 10_000; + + /// Maximum wall-clock time (in milliseconds) allowed for one JSLT evaluation. + public static final long EVALUATION_TIMEOUT_MS = 5_000L; +} diff --git a/src/main/java/com/decathlon/idp_core/domain/constant/SearchConstraints.java b/src/main/java/com/decathlon/idp_core/domain/constant/SearchConstraints.java index 08723413..e2964a76 100644 --- a/src/main/java/com/decathlon/idp_core/domain/constant/SearchConstraints.java +++ b/src/main/java/com/decathlon/idp_core/domain/constant/SearchConstraints.java @@ -11,8 +11,14 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class SearchConstraints { - /// Maximum number of entities returned per page in a search request. - public static final int MAX_PAGE_SIZE = 500; + /// Page size applied when a request omits `size`. Capped at the configured + /// maximum. + public static final int DEFAULT_PAGE_SIZE = 20; + + /// Default maximum number of entities returned per page in a search request. + /// The effective limit is configurable via `app.max-page-size` (env + /// `MAX_PAGE_SIZE`). + public static final int DEFAULT_MAX_PAGE_SIZE = 500; /// Maximum length (in characters) of the free-text `query` parameter. public static final int MAX_QUERY_LENGTH = 255; diff --git a/src/main/java/com/decathlon/idp_core/domain/constant/ValidationMessages.java b/src/main/java/com/decathlon/idp_core/domain/constant/ValidationMessages.java index b230f849..dc3149fe 100644 --- a/src/main/java/com/decathlon/idp_core/domain/constant/ValidationMessages.java +++ b/src/main/java/com/decathlon/idp_core/domain/constant/ValidationMessages.java @@ -84,6 +84,9 @@ public class ValidationMessages { // Principal provisioning validation messages public static final String PRINCIPAL_CREATION_FAILED = "Failed to create principal with identifier '%s'. The principal provider is currently unavailable. The system will automatically retry provisioning on the next request."; + // Authorization validation messages + public static final String AUTHORIZATION_VALUE_MUST_NOT_BE_NULL = "%s must not be null"; + // Helper method to construct rules incompatibility message public static String rulesAreIncompatible(String rule1, String rule2) { return PROPERTY_RULES_MUTUALLY_EXCLUSIVE.replace("{rule1}", rule1).replace("{rule2}", rule2); @@ -100,6 +103,14 @@ public static String minMaxConstraintViolated(String constraint) { return PROPERTY_RULES_MIN_MAX_CONSTRAINT_VIOLATED.replace("{constraint}", constraint); } + public static String authorizationValueMustNotBeNull(String fieldName) { + return AUTHORIZATION_VALUE_MUST_NOT_BE_NULL.formatted(fieldName); + } + // Pagination validation messages + public static final String PAGE_SIZE_TOO_LARGE = "Page size must not exceed %d"; + public static final String PAGE_SIZE_NOT_INTEGER = "Page size must be an integer"; + public static final String PAGE_INDEX_NOT_INTEGER = "Page index must be an integer"; + // Filter query validation messages public static final String FILTER_TOO_MANY_CRITERIA = "Filter query exceeds maximum of %d criteria"; public static final String FILTER_VALUE_TOO_LONG = "Filter value must not exceed %d characters in criterion '%s'"; @@ -123,8 +134,7 @@ public static String minMaxConstraintViolated(String constraint) { public static final String SEARCH_QUERY_TOO_LONG = "Search query must not exceed %d characters"; public static final String SEARCH_NUMERIC_OPERATOR_REQUIRES_PROPERTY = "Operator '%s' is only valid for property.{name} fields"; public static final String SEARCH_INVALID_SORT_FIELD = "Invalid sort field '%s'. Supported fields: identifier, name, templateIdentifier"; - public static final String SEARCH_INVALID_SORT_FORMAT = "Invalid sort expression '%s'. Expected format: field or field:asc|desc"; - public static final String SEARCH_PAGE_SIZE_TOO_LARGE = "Page size must not exceed %d"; + public static final String SEARCH_INVALID_SORT_FORMAT = "Invalid sort expression '%s'. Expected format: field[,asc|desc] or field alone"; public static final String SEARCH_PAGE_INVALID = "Page index must be 0 or greater"; public static final String SEARCH_SIZE_INVALID = "Page size must be greater than 0"; public static final String SEARCH_NUMERIC_OPERATOR_INVALID_VALUE = "Value '%s' is not a valid number for operator '%s'"; diff --git a/src/main/java/com/decathlon/idp_core/domain/exception/authorization/PrincipalNotAuthorizedException.java b/src/main/java/com/decathlon/idp_core/domain/exception/authorization/PrincipalNotAuthorizedException.java new file mode 100644 index 00000000..011f1427 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/exception/authorization/PrincipalNotAuthorizedException.java @@ -0,0 +1,22 @@ +package com.decathlon.idp_core.domain.exception.authorization; + +/// Indicates that a principal is not permitted to perform the requested operation. +public class PrincipalNotAuthorizedException extends RuntimeException { + + private final String identifier; + + /// Creates an authorization failure for the specified principal. + /// + /// @param identifier the identifier of the principal denied access + public PrincipalNotAuthorizedException(String identifier) { + super("Principal '" + identifier + "' is not authorized to perform this operation"); + this.identifier = identifier; + } + + /// Returns the identifier of the principal denied access. + /// + /// @return the principal identifier + public String getIdentifier() { + return identifier; + } +} diff --git a/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationAction.java b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationAction.java new file mode 100644 index 00000000..0dd04367 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationAction.java @@ -0,0 +1,6 @@ +package com.decathlon.idp_core.domain.model.authorization; + +/// CRUD operation requested against a platform resource. +public enum AuthorizationAction { + CREATE, READ, UPDATE, DELETE, UNSUPPORTED +} diff --git a/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationMode.java b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationMode.java new file mode 100644 index 00000000..747769c8 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationMode.java @@ -0,0 +1,6 @@ +package com.decathlon.idp_core.domain.model.authorization; + +/// Authorization strategies supported by the platform. +public enum AuthorizationMode { + GLOBAL, RBAC, ABAC +} diff --git a/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationPolicy.java b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationPolicy.java new file mode 100644 index 00000000..2466c18f --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationPolicy.java @@ -0,0 +1,23 @@ +package com.decathlon.idp_core.domain.model.authorization; + +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +import com.decathlon.idp_core.domain.constant.ValidationMessages; + +/// Immutable authorization configuration used by domain authorization services. +public record AuthorizationPolicy(AuthorizationMode mode, Set globalPrincipalIdentifiers, + Optional requiredPrincipalProperty) { + + public AuthorizationPolicy { + Objects.requireNonNull(mode, ValidationMessages.authorizationValueMustNotBeNull("mode")); + globalPrincipalIdentifiers = globalPrincipalIdentifiers != null + ? Set.copyOf(globalPrincipalIdentifiers) + : Set.of(); + Objects.requireNonNull(requiredPrincipalProperty, + ValidationMessages.authorizationValueMustNotBeNull("requiredPrincipalProperty")); + requiredPrincipalProperty = requiredPrincipalProperty.map(String::trim) + .filter(propertyName -> !propertyName.isBlank()); + } +} diff --git a/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationRequest.java b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationRequest.java new file mode 100644 index 00000000..6322f6dd --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationRequest.java @@ -0,0 +1,26 @@ +package com.decathlon.idp_core.domain.model.authorization; + +import java.util.Objects; +import java.util.Optional; + +import jakarta.validation.constraints.NotNull; + +import com.decathlon.idp_core.domain.constant.ValidationMessages; +import com.decathlon.idp_core.domain.model.entity.Entity; +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; + +/// Domain input describing a principal's request without infrastructure types. +public record AuthorizationRequest(@NotNull PrincipalInfo principal, + @NotNull Optional principalEntity, @NotNull AuthorizationAction action, + @NotNull AuthorizationResource resource) { + + public AuthorizationRequest { + Objects.requireNonNull(principal, + ValidationMessages.authorizationValueMustNotBeNull("principal")); + Objects.requireNonNull(principalEntity, + ValidationMessages.authorizationValueMustNotBeNull("principalEntity")); + Objects.requireNonNull(action, ValidationMessages.authorizationValueMustNotBeNull("action")); + Objects.requireNonNull(resource, + ValidationMessages.authorizationValueMustNotBeNull("resource")); + } +} diff --git a/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationResource.java b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationResource.java new file mode 100644 index 00000000..842129bf --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/model/authorization/AuthorizationResource.java @@ -0,0 +1,28 @@ +package com.decathlon.idp_core.domain.model.authorization; + +import java.util.Objects; +import java.util.Optional; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import com.decathlon.idp_core.domain.constant.ValidationMessages; + +/// Identifies the resource and optional parent context for an authorization request. +public record AuthorizationResource(@NotBlank String type, @NotNull Optional identifier, + @NotNull Optional parentIdentifier) { + + public static final String INBOUND_WEBHOOK_CONFIGURATION = "inbound_webhook_configuration"; + public static final String ENTITY_DYNAMIC_MAPPING = "entity_dynamic_mapping"; + public static final String ENTITY_TEMPLATE = "entity_template"; + public static final String PRINCIPAL_TEMPLATE_IDENTIFIER = "principal"; + public static final String PRINCIPAL_SELF = "principal_self"; + + public AuthorizationResource { + Objects.requireNonNull(type, ValidationMessages.authorizationValueMustNotBeNull("type")); + Objects.requireNonNull(identifier, + ValidationMessages.authorizationValueMustNotBeNull("identifier")); + Objects.requireNonNull(parentIdentifier, + ValidationMessages.authorizationValueMustNotBeNull("parentIdentifier")); + } +} diff --git a/src/main/java/com/decathlon/idp_core/domain/model/enums/RelationTargetValidationMode.java b/src/main/java/com/decathlon/idp_core/domain/model/enums/RelationTargetValidationMode.java new file mode 100644 index 00000000..62489dfa --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/model/enums/RelationTargetValidationMode.java @@ -0,0 +1,10 @@ +package com.decathlon.idp_core.domain.model.enums; + +/// Controls how relation target identifiers are checked during entity writes. +public enum RelationTargetValidationMode { + /// Requires every non-blank relation target identifier to resolve to an entity. + STRICT, + + /// Filters unresolved identifiers from optional relations. + TOLERANT +} diff --git a/src/main/java/com/decathlon/idp_core/domain/model/inbound_connectors/webhook/WebhookSecurity.java b/src/main/java/com/decathlon/idp_core/domain/model/inbound_connectors/webhook/WebhookSecurity.java index 9aba1e97..afbda12c 100644 --- a/src/main/java/com/decathlon/idp_core/domain/model/inbound_connectors/webhook/WebhookSecurity.java +++ b/src/main/java/com/decathlon/idp_core/domain/model/inbound_connectors/webhook/WebhookSecurity.java @@ -14,9 +14,10 @@ public record WebhookSecurity(WebhookSecurityType type, Map conf if (type == null) { throw new WebhookSecurityConfigurationException(WEBHOOK_CONNECTOR_SECURITY_TYPE_MANDATORY); } - if (config == null) { + // NONE needs no config: a missing config is normalized to an empty map + if (config == null && type != WebhookSecurityType.NONE) { throw new WebhookSecurityConfigurationException(WEBHOOK_CONNECTOR_SECURITY_CONFIG_MANDATORY); } - config = Map.copyOf(config); + config = config == null ? Map.of() : Map.copyOf(config); } } diff --git a/src/main/java/com/decathlon/idp_core/domain/model/inbound_connectors/webhook/WebhookSecurityValidationPolicy.java b/src/main/java/com/decathlon/idp_core/domain/model/inbound_connectors/webhook/WebhookSecurityValidationPolicy.java new file mode 100644 index 00000000..b19b5a8f --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/model/inbound_connectors/webhook/WebhookSecurityValidationPolicy.java @@ -0,0 +1,7 @@ +package com.decathlon.idp_core.domain.model.inbound_connectors.webhook; + +/// Domain policy controlling which webhook security configurations are allowed. +/// +/// @param allowNone whether connectors may be created without webhook authentication +public record WebhookSecurityValidationPolicy(boolean allowNone) { +} diff --git a/src/main/java/com/decathlon/idp_core/domain/model/search/PaginationCriteria.java b/src/main/java/com/decathlon/idp_core/domain/model/search/PaginationCriteria.java index 9c425a5a..dd283c61 100644 --- a/src/main/java/com/decathlon/idp_core/domain/model/search/PaginationCriteria.java +++ b/src/main/java/com/decathlon/idp_core/domain/model/search/PaginationCriteria.java @@ -1,4 +1,32 @@ package com.decathlon.idp_core.domain.model.search; +import com.decathlon.idp_core.domain.constant.ValidationMessages; +import com.decathlon.idp_core.domain.exception.search.InvalidSearchQueryException; + public record PaginationCriteria(int page, int size, String sort) { + + /// Checks that page is non-negative and size is at least 1, without an upper + /// bound. + /// + /// @throws InvalidSearchQueryException when page or size is out of range + public void validateRange() { + if (page < 0) { + throw new InvalidSearchQueryException(ValidationMessages.SEARCH_PAGE_INVALID); + } + if (size <= 0) { + throw new InvalidSearchQueryException(ValidationMessages.SEARCH_SIZE_INVALID); + } + } + + /// Checks that page is non-negative and size is between 1 and `maxPageSize`. + /// + /// @param maxPageSize configured maximum number of items per page + /// @throws InvalidSearchQueryException when page or size is out of bounds + public void validateBounds(int maxPageSize) { + validateRange(); + if (size > maxPageSize) { + throw new InvalidSearchQueryException( + ValidationMessages.PAGE_SIZE_TOO_LARGE.formatted(maxPageSize)); + } + } } diff --git a/src/main/java/com/decathlon/idp_core/domain/model/search/SortCriteria.java b/src/main/java/com/decathlon/idp_core/domain/model/search/SortCriteria.java new file mode 100644 index 00000000..16b66634 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/model/search/SortCriteria.java @@ -0,0 +1,9 @@ +package com.decathlon.idp_core.domain.model.search; + +/// A validated entity sort field and direction. +public record SortCriteria(String field, Direction direction) { + + public enum Direction { + ASC, DESC + } +} diff --git a/src/main/java/com/decathlon/idp_core/domain/port/audit/AuditIdentityProviderPort.java b/src/main/java/com/decathlon/idp_core/domain/port/audit/AuditIdentityProviderPort.java new file mode 100644 index 00000000..56f6f7cb --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/port/audit/AuditIdentityProviderPort.java @@ -0,0 +1,15 @@ +package com.decathlon.idp_core.domain.port.audit; + +/// Provides the authenticated identity associated with an audit revision. +public interface AuditIdentityProviderPort { + + /// Returns the identifier recorded for the authenticated user. + /// + /// @return authenticated user identifier + String getAuthId(); + + /// Returns the name associated with the authenticated user. + /// + /// @return authenticated user name + String getName(); +} diff --git a/src/main/java/com/decathlon/idp_core/domain/service/authorization/GlobalAuthorizationService.java b/src/main/java/com/decathlon/idp_core/domain/service/authorization/GlobalAuthorizationService.java new file mode 100644 index 00000000..998d2d74 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/service/authorization/GlobalAuthorizationService.java @@ -0,0 +1,84 @@ +package com.decathlon.idp_core.domain.service.authorization; + +import org.springframework.stereotype.Service; + +import com.decathlon.idp_core.domain.exception.authorization.PrincipalNotAuthorizedException; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationMode; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationRequest; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; +import com.decathlon.idp_core.domain.model.entity.Entity; +import com.decathlon.idp_core.domain.model.principal.PrincipalKind; + +/// Applies the global authorization policy to a principal request. +@Service +public class GlobalAuthorizationService { + + private static final String IS_ADMIN_PROPERTY = "is_admin"; + private static final String PRINCIPAL_TEMPLATE_IDENTIFIER = AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER; + private static final String ENTITY_RESOURCE = "entity"; + private static final String ENTITY_SEARCH_RESOURCE = "entity_search"; + private static final String ENTITY_TEMPLATE_RESOURCE = AuthorizationResource.ENTITY_TEMPLATE; + private static final String PRINCIPAL_SELF_RESOURCE = AuthorizationResource.PRINCIPAL_SELF; + + /// Applies the global authorization matrix, including the break-glass bypass. + /// + /// @param request the principal and operation being authorized + /// @param policy the configured global authorization policy + /// @throws PrincipalNotAuthorizedException when the request is not permitted + public void authorize(AuthorizationRequest request, AuthorizationPolicy policy) { + String identifier = request.principal().identifier(); + if (policy.mode() != AuthorizationMode.GLOBAL + || request.action() == AuthorizationAction.UNSUPPORTED) { + throw new PrincipalNotAuthorizedException(identifier); + } + + if (policy.globalPrincipalIdentifiers().contains(identifier)) { + return; + } + + boolean catalogAdministrator = request.principalEntity().filter(this::isCatalogAdministrator) + .isPresent(); + if (catalogAdministrator) { + return; + } + + boolean missingConfiguredAccessProperty = request.principal().kind() == PrincipalKind.HUMAN + && policy.requiredPrincipalProperty() + .map(propertyName -> request.principalEntity() + .filter(entity -> hasRequiredPrincipalProperty(entity, propertyName)).isEmpty()) + .orElse(false); + if (missingConfiguredAccessProperty) { + throw new PrincipalNotAuthorizedException(identifier); + } + + if (PRINCIPAL_SELF_RESOURCE.equals(request.resource().type()) + && request.action() == AuthorizationAction.READ) { + return; + } + + boolean readOnlyResource = ENTITY_RESOURCE.equals(request.resource().type()) + || ENTITY_SEARCH_RESOURCE.equals(request.resource().type()) + || ENTITY_TEMPLATE_RESOURCE.equals(request.resource().type()); + if (readOnlyResource && request.action() == AuthorizationAction.READ) { + return; + } + + throw new PrincipalNotAuthorizedException(identifier); + } + + private boolean isCatalogAdministrator(Entity principalEntity) { + return PRINCIPAL_TEMPLATE_IDENTIFIER.equals(principalEntity.templateIdentifier()) + && principalEntity.properties().stream() + .anyMatch(property -> IS_ADMIN_PROPERTY.equals(property.name()) + && Boolean.parseBoolean(property.value())); + } + + private boolean hasRequiredPrincipalProperty(Entity principalEntity, String propertyName) { + return PRINCIPAL_TEMPLATE_IDENTIFIER.equals(principalEntity.templateIdentifier()) + && principalEntity.properties().stream() + .anyMatch(property -> propertyName.equals(property.name()) + && Boolean.parseBoolean(property.value())); + } +} diff --git a/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityAuditService.java b/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityAuditService.java index 592e3253..5b1aaaf7 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityAuditService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityAuditService.java @@ -7,7 +7,6 @@ import com.decathlon.idp_core.domain.model.entity.EntityAuditInfo; import com.decathlon.idp_core.domain.port.audit.EntityAuditPort; -import com.decathlon.idp_core.domain.service.entity_template.EntityTemplateService; import lombok.RequiredArgsConstructor; @@ -28,7 +27,6 @@ public class EntityAuditService { private final EntityAuditPort entityAuditPort; - private final EntityTemplateService entityTemplateService; /// Retrieves the complete audit history for a specific entity. /// diff --git a/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityService.java b/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityService.java index 6a583887..809c5f8b 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityService.java @@ -18,8 +18,6 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; -import com.decathlon.idp_core.domain.constant.SearchConstraints; -import com.decathlon.idp_core.domain.constant.ValidationMessages; import com.decathlon.idp_core.domain.exception.entity.EntityAlreadyExistsException; import com.decathlon.idp_core.domain.exception.entity.EntityDeletionBlockedException; import com.decathlon.idp_core.domain.exception.entity.EntityNotFoundException; @@ -43,6 +41,7 @@ import com.decathlon.idp_core.domain.service.entity_template.EntityTemplateValidationService; import com.decathlon.idp_core.domain.service.filter.EntityFilterDslParser; import com.decathlon.idp_core.domain.service.search.SearchFilterValidationService; +import com.decathlon.idp_core.domain.service.search.SortParameterParser; import lombok.RequiredArgsConstructor; @@ -162,9 +161,9 @@ public Entity createEntity(@Valid Entity entity) { // Enrich relations with target template identifiers from template definition Entity enrichedEntity = enrichRelationsWithTargetTemplates(entity, template); - entityValidationService.validateForCreation(enrichedEntity, template); + Entity validatedEntity = entityValidationService.validateForCreation(enrichedEntity, template); - return entityRepository.save(enrichedEntity); + return entityRepository.save(validatedEntity); } /// Updates an existing entity identified by template and entity identifiers. @@ -194,11 +193,11 @@ public Entity updateEntity(String templateIdentifier, String entityIdentifier, // Enrich relations with target template identifiers from template definition Entity enrichedEntity = enrichRelationsWithTargetTemplates(entityToSave, template); - entityValidationService.validateForUpdate(enrichedEntity, template); + Entity validatedEntity = entityValidationService.validateForUpdate(enrichedEntity, template); // Only save if there are actual changes to avoid unnecessary audit records - if (hasEntityChanged(existingEntity, enrichedEntity)) { - return entityRepository.save(enrichedEntity); + if (hasEntityChanged(existingEntity, validatedEntity)) { + return entityRepository.save(validatedEntity); } return existingEntity; @@ -247,10 +246,10 @@ public Entity patchEntity(String templateIdentifier, String entityIdentifier, new ArrayList<>(mergedProperties.values()), new ArrayList<>(mergedRelations.values())); Entity updatedEntity = enrichRelationsWithTargetTemplates(entityToSave, template); - entityValidationService.validateForUpdate(updatedEntity, template); + Entity validatedEntity = entityValidationService.validateForUpdate(updatedEntity, template); - if (hasEntityChanged(existingEntity, updatedEntity)) { - return entityRepository.save(updatedEntity); + if (hasEntityChanged(existingEntity, validatedEntity)) { + return entityRepository.save(validatedEntity); } return existingEntity; @@ -631,14 +630,14 @@ private Entity retrieveEntity(final String templateIdentifier, final String enti /// and all property values; null means no text restriction /// @param paginationCriteria contains page (zero-based), size (1 to /// MAX_PAGE_SIZE), - /// and optional sort expression (`field` or `field:asc|desc`) + /// and optional sort expression (`field` or `field,asc|desc`) /// @return paginated entities matching the filter and query /// @throws InvalidSearchQueryException when pagination parameters are invalid @Transactional(readOnly = true) public PaginatedResult searchEntities(SearchFilterNode filter, String query, - PaginationCriteria paginationCriteria) { + PaginationCriteria paginationCriteria, int maxPageSize) { searchFilterValidationService.validate(filter, query); - validatePaginationCriteria(paginationCriteria); + validatePaginationCriteria(paginationCriteria, maxPageSize); return entityRepository.search(filter, query, paginationCriteria); } @@ -654,41 +653,9 @@ public boolean entityExists(String templateIdentifier, String entityIdentifier) .findByTemplateIdentifierAndIdentifier(templateIdentifier, entityIdentifier).isPresent(); } - private void validatePaginationCriteria(PaginationCriteria criteria) { - if (criteria.page() < 0) { - throw new InvalidSearchQueryException(ValidationMessages.SEARCH_PAGE_INVALID); - } - if (criteria.size() <= 0) { - throw new InvalidSearchQueryException(ValidationMessages.SEARCH_SIZE_INVALID); - } - if (criteria.size() > SearchConstraints.MAX_PAGE_SIZE) { - throw new InvalidSearchQueryException( - ValidationMessages.SEARCH_PAGE_SIZE_TOO_LARGE.formatted(SearchConstraints.MAX_PAGE_SIZE)); - } - String sort = criteria.sort(); - if (sort != null && !sort.isBlank()) { - validateSortExpression(sort); - } - } - - private void validateSortExpression(String sortExpression) { - String[] parts = sortExpression.split(":"); - if (parts.length > 2) { - throw new InvalidSearchQueryException( - ValidationMessages.SEARCH_INVALID_SORT_FORMAT.formatted(sortExpression)); - } - String property = parts[0].trim(); - if (!SearchConstraints.ALLOWED_SORT_FIELDS.contains(property)) { - throw new InvalidSearchQueryException( - ValidationMessages.SEARCH_INVALID_SORT_FIELD.formatted(property)); - } - if (parts.length == 2) { - String direction = parts[1].trim().toLowerCase(); - if (!direction.equals("asc") && !direction.equals("desc")) { - throw new InvalidSearchQueryException( - ValidationMessages.SEARCH_INVALID_SORT_FORMAT.formatted(sortExpression)); - } - } + private void validatePaginationCriteria(PaginationCriteria criteria, int maxPageSize) { + criteria.validateBounds(maxPageSize); + SortParameterParser.parse(criteria.sort()); } } diff --git a/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityValidationService.java b/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityValidationService.java index acaf6ee1..367934cb 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityValidationService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/entity/EntityValidationService.java @@ -13,6 +13,7 @@ import com.decathlon.idp_core.domain.exception.entity.EntityValidationException; import com.decathlon.idp_core.domain.model.entity.Entity; import com.decathlon.idp_core.domain.model.entity.Property; +import com.decathlon.idp_core.domain.model.entity.Relation; import com.decathlon.idp_core.domain.model.entity_template.EntityTemplate; import com.decathlon.idp_core.domain.model.entity_template.PropertyDefinition; import com.decathlon.idp_core.domain.port.EntityRepositoryPort; @@ -45,13 +46,15 @@ public class EntityValidationService { /// /// @param entity the entity to validate /// @param template the already-resolved template the entity must conform to + /// @return the validated entity with unresolved optional relation targets + /// removed /// @throws EntityValidationException when one or more validation rules are /// violated /// @throws EntityAlreadyExistsException if an entity with the same identifier /// exists for the template - public void validateForCreation(Entity entity, EntityTemplate template) { + public Entity validateForCreation(Entity entity, EntityTemplate template) { validateUniqueness(entity); - validateAgainstTemplate(template, entity); + return validateAgainstTemplate(template, entity); } /// Validates entity data for update operations. @@ -62,22 +65,26 @@ public void validateForCreation(Entity entity, EntityTemplate template) { /// /// @param entity the entity payload to validate /// @param template the already-resolved template the entity must conform to + /// @return the validated entity with unresolved optional relation targets + /// removed /// @throws EntityValidationException when one or more validation rules are /// violated - void validateForUpdate(Entity entity, EntityTemplate template) { - validateAgainstTemplate(template, entity); + Entity validateForUpdate(Entity entity, EntityTemplate template) { + return validateAgainstTemplate(template, entity); } - /// Validates entity properties against the template's property definitions, + /// Validates entity data against template property and relation definitions, /// enforcing required fields and value rules. /// /// @param template the entity template whose property definitions are used for /// validation /// @param entity the entity being validated, containing the actual property /// values to check + /// @return the validated entity with unresolved optional relation targets + /// removed /// @throws EntityValidationException if any property validation rules are /// violated, including missing required properties - private void validateAgainstTemplate(EntityTemplate template, Entity entity) { + private Entity validateAgainstTemplate(EntityTemplate template, Entity entity) { Violations violations = new Violations(); violations.addIfBlank(entity.name(), ENTITY_NAME_MANDATORY); @@ -91,12 +98,15 @@ private void validateAgainstTemplate(EntityTemplate template, Entity entity) { propertyValidationService.validatePropertiesAgainstTemplate(template, definitions, propertiesByName, violations); - relationValidationService.validateRelationsAgainstTemplate(template, entity.relations(), - violations); + List normalizedRelations = relationValidationService + .validateAndNormalizeRelationsAgainstTemplate(template, entity.relations(), violations); if (!violations.isEmpty()) { throw new EntityValidationException(violations.asList()); } + + return new Entity(entity.id(), entity.templateIdentifier(), entity.name(), entity.identifier(), + entity.properties(), normalizedRelations); } /// Checks for existing entity with same template and identifier to prevent diff --git a/src/main/java/com/decathlon/idp_core/domain/service/entity_graph/EntityGraphService.java b/src/main/java/com/decathlon/idp_core/domain/service/entity_graph/EntityGraphService.java index 1143d495..fc683bab 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/entity_graph/EntityGraphService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/entity_graph/EntityGraphService.java @@ -7,12 +7,15 @@ import java.util.UUID; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.decathlon.idp_core.domain.exception.entity.EntityNotFoundException; import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateNotFoundException; +import com.decathlon.idp_core.domain.exception.search.InvalidSearchQueryException; import com.decathlon.idp_core.domain.model.entity.Entity; import com.decathlon.idp_core.domain.model.entity.EntityCompositeKey; import com.decathlon.idp_core.domain.model.entity.EntityFilter; @@ -20,9 +23,12 @@ import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphNode; import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphQueryOptions; import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphTraversalMode; +import com.decathlon.idp_core.domain.model.search.PaginationCriteria; +import com.decathlon.idp_core.domain.model.search.SortCriteria; import com.decathlon.idp_core.domain.port.EntityGraphRepositoryPort; import com.decathlon.idp_core.domain.port.EntityRepositoryPort; import com.decathlon.idp_core.domain.service.entity.EntityService; +import com.decathlon.idp_core.domain.service.search.SortParameterParser; import lombok.RequiredArgsConstructor; @@ -120,17 +126,26 @@ public EntityGraphNode getEntityGraph(String templateIdentifier, String entityId /// produce /// unified `relations` DTOs without any further DB calls. /// - /// @param pageable pagination and sorting configuration + /// @param paginationCriteria zero-based page, page size, and optional sort + /// expression, validated against `maxPageSize` /// @param templateIdentifier template to scope the entity list /// @param entityFilter optional filter criteria; `null` means no filtering /// @param depth the maximum relationship depth used for each page entity's /// graph traversal /// @return paginated graph nodes with outbound and inbound relations resolved + /// @param maxPageSize the largest page size accepted /// @throws EntityTemplateNotFoundException when the template does not exist + /// @throws InvalidSearchQueryException when page or size is out of bounds @SuppressWarnings("null") @Transactional(readOnly = true) - public Page getEntityGraphPageByTemplate(Pageable pageable, - String templateIdentifier, EntityFilter entityFilter, int depth) { + public Page getEntityGraphPageByTemplate(PaginationCriteria paginationCriteria, + String templateIdentifier, EntityFilter entityFilter, int depth, int maxPageSize) { + + paginationCriteria.validateBounds(maxPageSize); + Pageable pageable = SortParameterParser.parse(paginationCriteria.sort()) + .map(sortCriteria -> PageRequest.of(paginationCriteria.page(), paginationCriteria.size(), + toSpringSort(sortCriteria))) + .orElseGet(() -> PageRequest.of(paginationCriteria.page(), paginationCriteria.size())); // Fetch paginated entities — template existence is validated inside this call Page entityPage = entityService.getEntitiesByTemplateIdentifier(pageable, @@ -161,4 +176,11 @@ public Page getEntityGraphPageByTemplate(Pageable pageable, entity.properties(), List.of(), List.of()))); } + private Sort toSpringSort(SortCriteria criteria) { + Sort.Direction direction = criteria.direction() == SortCriteria.Direction.ASC + ? Sort.Direction.ASC + : Sort.Direction.DESC; + return Sort.by(direction, criteria.field()); + } + } diff --git a/src/main/java/com/decathlon/idp_core/domain/service/principal/PrincipalProvisioningService.java b/src/main/java/com/decathlon/idp_core/domain/service/principal/PrincipalProvisioningService.java index 3d9e9521..de4bfaa7 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/principal/PrincipalProvisioningService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/principal/PrincipalProvisioningService.java @@ -13,6 +13,7 @@ import com.decathlon.idp_core.domain.model.entity.Property; import com.decathlon.idp_core.domain.model.entity.Relation; import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; +import com.decathlon.idp_core.domain.model.principal.PrincipalKind; import com.decathlon.idp_core.domain.port.EntityRepositoryPort; import lombok.RequiredArgsConstructor; @@ -36,6 +37,8 @@ public class PrincipalProvisioningService { private static final String PRINCIPAL_TEMPLATE_IDENTIFIER = "principal"; + private static final String KIND_PROPERTY = "kind"; + private static final String IS_ADMIN_PROPERTY = "is_admin"; private final EntityRepositoryPort entityRepository; @@ -57,6 +60,20 @@ public class PrincipalProvisioningService { /// @return the provisioned Principal entity @Transactional public Entity provisionPrincipal(PrincipalInfo principalInfo) { + return provisionPrincipal(principalInfo, false); + } + + /// Provisions a globally configured administrator principal. + /// + /// @param principalInfo extracted authentication information for an + /// allow-listed principal + /// @return the provisioned Principal entity + @Transactional + public Entity provisionGlobalAdministrator(PrincipalInfo principalInfo) { + return provisionPrincipal(principalInfo, true); + } + + private Entity provisionPrincipal(PrincipalInfo principalInfo, boolean isAdmin) { Optional existingPrincipal = entityRepository.findByTemplateIdentifierAndIdentifier( PRINCIPAL_TEMPLATE_IDENTIFIER, principalInfo.identifier()); @@ -64,7 +81,7 @@ public Entity provisionPrincipal(PrincipalInfo principalInfo) { return existingPrincipal.get(); } - return createNewPrincipal(principalInfo); + return createNewPrincipal(principalInfo, isAdmin); } /// Retrieves a Principal entity by its identifier. @@ -74,11 +91,30 @@ public Entity provisionPrincipal(PrincipalInfo principalInfo) { /// @param identifier unique principal identifier /// @return optional containing the principal entity @Transactional(readOnly = true) - public Optional getPrincipal(String identifier) { + public Optional findPrincipal(String identifier) { return entityRepository.findByTemplateIdentifierAndIdentifier(PRINCIPAL_TEMPLATE_IDENTIFIER, identifier); } + /// Retrieves a principal only when its stored kind matches the authenticated + /// actor. + /// + /// @param principalInfo authenticated principal identity + /// @return matching principal entity, or empty when missing or of a different + /// kind + @Transactional(readOnly = true) + public Optional findPrincipalWithSameKind(PrincipalInfo principalInfo) { + return entityRepository + .findByTemplateIdentifierAndIdentifier(PRINCIPAL_TEMPLATE_IDENTIFIER, + principalInfo.identifier()) + .filter(entity -> hasMatchingKind(entity, principalInfo.kind())); + } + + private boolean hasMatchingKind(Entity entity, PrincipalKind kind) { + return entity.properties().stream().anyMatch( + property -> KIND_PROPERTY.equals(property.name()) && kind.name().equals(property.value())); + } + /// Creates a new Principal entity in the catalog. /// /// **Business logic:** Maps PrincipalInfo to entity properties and relations. @@ -87,9 +123,10 @@ public Optional getPrincipal(String identifier) { /// /// @param principalInfo extracted authentication information /// @return the newly created or existing Principal entity - private Entity createNewPrincipal(PrincipalInfo principalInfo) { + private Entity createNewPrincipal(PrincipalInfo principalInfo, boolean isAdmin) { Entity newPrincipal = new Entity(null, PRINCIPAL_TEMPLATE_IDENTIFIER, principalInfo.name(), - principalInfo.identifier(), buildProperties(principalInfo), buildRelations(principalInfo)); + principalInfo.identifier(), buildProperties(principalInfo, isAdmin), + buildRelations(principalInfo)); try { return entityRepository.save(newPrincipal); } catch (EntityAlreadyExistsException _) { @@ -110,12 +147,14 @@ private Entity createNewPrincipal(PrincipalInfo principalInfo) { /// /// @param principalInfo the principal information containing attributes /// @return list of properties for the principal entity - private List buildProperties(PrincipalInfo principalInfo) { + private List buildProperties(PrincipalInfo principalInfo, boolean isAdmin) { List properties = new ArrayList<>(); - properties.add(new Property(null, "kind", principalInfo.kind().name())); + properties.add(new Property(null, KIND_PROPERTY, principalInfo.kind().name())); + properties.add(new Property(null, IS_ADMIN_PROPERTY, Boolean.toString(isAdmin))); principalInfo.attributes().forEach((key, value) -> { - if (value != null && !value.isBlank()) { + if (!KIND_PROPERTY.equalsIgnoreCase(key) && !IS_ADMIN_PROPERTY.equalsIgnoreCase(key) + && value != null && !value.isBlank()) { properties.add(new Property(null, key, value)); } }); diff --git a/src/main/java/com/decathlon/idp_core/domain/service/relation/RelationValidationService.java b/src/main/java/com/decathlon/idp_core/domain/service/relation/RelationValidationService.java index 04b90bc7..8f96958c 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/relation/RelationValidationService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/relation/RelationValidationService.java @@ -1,14 +1,18 @@ package com.decathlon.idp_core.domain.service.relation; import static com.decathlon.idp_core.domain.constant.ValidationMessages.ENTITY_DYNAMIC_MAPPING_ENTITY_RELATIONS_MISSING; +import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_NAME_ALREADY_EXISTS; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_NOT_DEFINED_IN_TEMPLATE; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_REQUIRED_MISSING; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_TARGET_ENTITY_NOT_FOUND; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_TARGET_TEMPLATE_MISMATCH; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_TOO_MANY_TARGETS; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -20,6 +24,7 @@ import com.decathlon.idp_core.domain.model.entity.Relation; import com.decathlon.idp_core.domain.model.entity_template.EntityTemplate; import com.decathlon.idp_core.domain.model.entity_template.RelationDefinition; +import com.decathlon.idp_core.domain.model.enums.RelationTargetValidationMode; import com.decathlon.idp_core.domain.port.EntityRepositoryPort; import com.decathlon.idp_core.domain.service.entity.Violations; @@ -31,13 +36,25 @@ /// 1. **Mapping validation** ([#validateMappingRelationsAgainstTemplate]): validates that /// relation names exist in the template and required relations are mapped. /// Used by dynamic mapping validation. -/// 2. **Full relation validation** ([#validateRelationsAgainstTemplate]): validates complete -/// [Relation] objects including cardinality and target existence. Used by entity validation. +/// 2. **Full relation validation** +/// ([#validateAndNormalizeRelationsAgainstTemplate]): filters target identifiers +/// not found in the repository from optional relations, omits relations left +/// without targets, and validates required relations, cardinality, and target +/// templates. Used by entity write validation. @Service @RequiredArgsConstructor public class RelationValidationService { + private record RelationValidationOptions(boolean skipDatabaseChecks, + boolean omitMissingOptionalTargets) { + } + + private record RelationNormalization(Optional relation, + List targetIdentifiers) { + } + private final EntityRepositoryPort entityRepository; + private final RelationTargetValidationMode targetValidationMode; /// Validates mapping relation names against the template's relation /// definitions. @@ -74,7 +91,8 @@ private void validateNamesExistInTemplate(EntityTemplate template, List return; } - Set definedRelationNames = getDefinedRelationNames(template); + Set definedRelationNames = template.relationsDefinitions().stream() + .map(RelationDefinition::name).collect(Collectors.toSet()); relationNames.stream().filter(name -> !definedRelationNames.contains(name)).findFirst() .ifPresent(name -> { @@ -102,14 +120,6 @@ private void validateRequiredRelationsAreMapped(EntityTemplate template, } } - private Set getDefinedRelationNames(EntityTemplate template) { - if (template.relationsDefinitions().isEmpty()) { - return Set.of(); - } - return template.relationsDefinitions().stream().map(RelationDefinition::name) - .collect(Collectors.toSet()); - } - /// Validates entity relations against the template's relation definitions, /// enforcing required relations and cardinality constraints. /// @param template the entity template whose relation definitions are used for @@ -120,16 +130,40 @@ private Set getDefinedRelationNames(EntityTemplate template) { /// the process public void validateRelationsAgainstTemplate(EntityTemplate template, List providedRelations, Violations violations) { - validateRelationsAgainstTemplate(template, providedRelations, violations, false); + validateRelationsAgainstTemplate(template, providedRelations, violations, false, false); + } + + /// Validates relations and filters out target identifiers that do not resolve + /// to entities in the repository from optional relations. Omits an optional + /// relation if no targets remain. + /// + /// Missing targets on required relations and existing targets with an + /// incompatible template remain validation errors. The returned relations + /// retain all resolved targets. + /// + /// @param template the entity template whose relation definitions are used + /// @param providedRelations the relations and target identifiers to validate + /// @param violations the accumulator for validation violations + /// @return relations with repository-missing target identifiers filtered out + /// and optional relations with no targets omitted + public List validateAndNormalizeRelationsAgainstTemplate(EntityTemplate template, + List providedRelations, Violations violations) { + boolean omitMissingOptionalTargets = targetValidationMode == RelationTargetValidationMode.TOLERANT; + return validateRelationsAgainstTemplate(template, providedRelations, violations, false, + omitMissingOptionalTargets); } - /// Internal unified relation validation used by both normal and dry-run - /// workflows. + /// Validates unique relation names, target entities, required relations, and + /// cardinality for normal and dry-run workflows. /// - /// @param skipDatabaseChecks when true, skips target-entity existence checks - /// in repository-backed validation - private void validateRelationsAgainstTemplate(EntityTemplate template, - List providedRelations, Violations violations, boolean skipDatabaseChecks) { + /// @param skipDatabaseChecks when true, skips repository lookups for target + /// existence and target-template compatibility + /// @param omitMissingOptionalTargets when true, filters repository-missing + /// identifiers from optional relations and omits relations left empty + /// @return relations with tolerated missing optional targets filtered out + private List validateRelationsAgainstTemplate(EntityTemplate template, + List providedRelations, Violations violations, boolean skipDatabaseChecks, + boolean omitMissingOptionalTargets) { List definitions = template.relationsDefinitions() != null ? template.relationsDefinitions() @@ -140,36 +174,175 @@ private void validateRelationsAgainstTemplate(EntityTemplate template, .filter(def -> def.name() != null).collect(Collectors.toMap(RelationDefinition::name, def -> def, (existing, replacement) -> existing)); - Map relationsByName = relations.stream().filter(rel -> rel.name() != null) - .collect(Collectors.toMap(Relation::name, rel -> rel, (existing, replacement) -> existing)); + Map relationsByName = new HashMap<>(); + for (Relation relation : relations) { + if (relation.name() != null + && relationsByName.putIfAbsent(relation.name(), relation) != null) { + violations.add(RELATION_NAME_ALREADY_EXISTS, relation.name()); + } + } + + Map> targetIdentifiersByName = new HashMap<>(); + RelationValidationOptions options = new RelationValidationOptions(skipDatabaseChecks, + omitMissingOptionalTargets); + List normalizedRelations = normalizeRelations(template.identifier(), relations, + definitionsByName, targetIdentifiersByName, violations, options); + + validateRelationDefinitions(template.identifier(), definitions, relationsByName, + targetIdentifiersByName, violations); + return normalizedRelations; + } + + /// Filters repository-missing identifiers from optional relations when enabled + /// and records the remaining identifiers for required and cardinality checks. + /// + /// @param templateIdentifier the identifier of the source entity template + /// @param relations the relations and their target identifiers to validate + /// @param definitionsByName the template relation definitions indexed by name + /// @param targetIdentifiersByName receives the identifiers remaining after + /// filtering + /// @param violations the accumulator for validation violations + /// @param options the relation validation options + /// @return relations with tolerated missing optional targets filtered out + private List normalizeRelations(String templateIdentifier, List relations, + Map definitionsByName, + Map> targetIdentifiersByName, Violations violations, + RelationValidationOptions options) { + List normalizedRelations = new ArrayList<>(); for (Relation relation : relations) { - if (relation.name() != null && !definitionsByName.containsKey(relation.name())) { - violations.add(RELATION_NOT_DEFINED_IN_TEMPLATE, relation.name(), template.identifier()); - } else if (!skipDatabaseChecks) { - validateRelationTargetEntityExistence(relation, violations); + RelationNormalization normalization = normalizeRelation(templateIdentifier, relation, + definitionsByName, violations, options); + if (relation.name() != null && definitionsByName.containsKey(relation.name())) { + targetIdentifiersByName.putIfAbsent(relation.name(), normalization.targetIdentifiers()); } + normalization.relation().ifPresent(normalizedRelations::add); + } + + return normalizedRelations; + } + + /// Validates one relation and filters repository-missing target identifiers + /// from optional relations when enabled. Omits the relation if no targets + /// remain, but retains undefined relations so their name violations are + /// reported. + /// + /// @param templateIdentifier the identifier of the source entity template + /// @param relation the relation and target identifiers to validate + /// @param definitionsByName the template relation definitions indexed by name + /// @param violations the accumulator for validation violations + /// @param options the relation validation options + /// @return the filtered relation, if any, and its remaining target identifiers + private RelationNormalization normalizeRelation(String templateIdentifier, Relation relation, + Map definitionsByName, Violations violations, + RelationValidationOptions options) { + if (relation.name() != null && !definitionsByName.containsKey(relation.name())) { + violations.add(RELATION_NOT_DEFINED_IN_TEMPLATE, relation.name(), templateIdentifier); + return new RelationNormalization(Optional.of(relation), + extractValidTargetIdentifiers(relation)); + } + + RelationDefinition definition = definitionsByName.get(relation.name()); + List targetIdentifiers = extractValidTargetIdentifiers(relation); + boolean omitUnresolvedTargets = options.omitMissingOptionalTargets() && definition != null + && !definition.required(); + List normalizedTargetIdentifiers = normalizeTargetIdentifiers(relation, + targetIdentifiers, violations, options.skipDatabaseChecks(), omitUnresolvedTargets); + + if (omitUnresolvedTargets && normalizedTargetIdentifiers.isEmpty()) { + return new RelationNormalization(Optional.empty(), normalizedTargetIdentifiers); + } + + Relation normalizedRelation = new Relation(relation.id(), relation.name(), + relation.targetTemplateIdentifier(), normalizedTargetIdentifiers); + return new RelationNormalization(Optional.of(normalizedRelation), normalizedTargetIdentifiers); + } + + /// Looks up target identifiers, reports missing targets unless optional + /// filtering is enabled, and checks the templates of found entities. In + /// optional filtering mode, removes identifiers that have no repository match. + /// + /// @param relation the relation whose targets are checked + /// @param targetIdentifiers the non-blank target identifiers to validate + /// @param violations the accumulator for validation violations + /// @param skipDatabaseChecks whether to skip the repository lookup and target + /// template checks + /// @param omitUnresolvedTargets whether repository-missing identifiers should + /// be filtered without adding missing-target violations + /// @return target identifiers remaining after optional filtering + private List normalizeTargetIdentifiers(Relation relation, List targetIdentifiers, + Violations violations, boolean skipDatabaseChecks, boolean omitUnresolvedTargets) { + if (skipDatabaseChecks || targetIdentifiers.isEmpty()) { + return targetIdentifiers; } + List existingEntities = entityRepository.findByIdentifierIn(targetIdentifiers); + Set existingIdentifiers = existingEntities.stream().map(EntitySummary::identifier) + .collect(Collectors.toSet()); + + validateTargetExistence(relation, targetIdentifiers, existingIdentifiers, violations, + omitUnresolvedTargets); + validateRelationTargetTemplates(relation, existingEntities, violations); + + if (omitUnresolvedTargets) { + return targetIdentifiers.stream().filter(existingIdentifiers::contains).toList(); + } + + return targetIdentifiers; + } + + /// Adds a missing-target violation for each identifier absent from the + /// repository unless optional filtering is enabled. + /// + /// @param relation the relation being validated + /// @param targetIdentifiers the non-blank target identifiers to check + /// @param existingIdentifiers the identifiers found in the repository + /// @param violations the accumulator for validation violations + /// @param omitUnresolvedTargets whether repository-missing identifiers should + /// be tolerated without a violation + private void validateTargetExistence(Relation relation, List targetIdentifiers, + Set existingIdentifiers, Violations violations, boolean omitUnresolvedTargets) { + for (String identifier : targetIdentifiers) { + if (!existingIdentifiers.contains(identifier) && !omitUnresolvedTargets) { + violations.add(RELATION_TARGET_ENTITY_NOT_FOUND, relation.name(), identifier); + } + } + } + + /// Reports missing required relations and multiple targets on single-target + /// relations using identifiers remaining after optional filtering. + /// + /// @param templateIdentifier the identifier of the source entity template + /// @param definitions the relation definitions to validate + /// @param relationsByName the provided relations indexed by name + /// @param targetIdentifiersByName the target identifiers remaining after + /// optional filtering, indexed by relation name + /// @param violations the accumulator for validation violations + private void validateRelationDefinitions(String templateIdentifier, + List definitions, Map relationsByName, + Map> targetIdentifiersByName, Violations violations) { for (RelationDefinition definition : definitions) { Relation relation = relationsByName.get(definition.name()); - List validTargets = extractValidTargetIdentifiers(relation); + List validTargets = relation == null + ? List.of() + : targetIdentifiersByName.getOrDefault(relation.name(), + extractValidTargetIdentifiers(relation)); if (definition.required() && validTargets.isEmpty()) { - violations.add(RELATION_REQUIRED_MISSING, definition.name(), template.identifier()); + violations.add(RELATION_REQUIRED_MISSING, definition.name(), templateIdentifier); } if (relation != null && !definition.toMany() && validTargets.size() > 1) { - violations.add(RELATION_TOO_MANY_TARGETS, definition.name(), template.identifier()); + violations.add(RELATION_TOO_MANY_TARGETS, definition.name(), templateIdentifier); } } } /// Validates entity relations for dry-run executions. /// - /// Keeps structural validation (relation names, required relations, - /// cardinality) - /// and skips database existence checks for target entity identifiers. + /// Keeps structural validation (relation names, required relations, and + /// cardinality) while skipping repository-backed target existence and template + /// compatibility checks. /// /// This method is intentionally additive and does not change the behavior of /// [#validateRelationsAgainstTemplate]. @@ -181,35 +354,7 @@ private void validateRelationsAgainstTemplate(EntityTemplate template, /// the process public void validateRelationsAgainstTemplateForDryRun(EntityTemplate template, List providedRelations, Violations violations) { - validateRelationsAgainstTemplate(template, providedRelations, violations, true); - } - - /// Validates that all target entity identifiers in the relation actually exist - /// in the database and match the expected target template. - /// - /// @param relation the relation whose target entity identifiers are to be - /// validated - /// @param violations the accumulator for any validation violations found during - /// the process - private void validateRelationTargetEntityExistence(Relation relation, Violations violations) { - List targetIdentifiers = extractValidTargetIdentifiers(relation); - - if (targetIdentifiers.isEmpty()) { - return; - } - - var existingEntities = entityRepository.findByIdentifierIn(targetIdentifiers); - Set existingIdentifiers = existingEntities.stream().map(EntitySummary::identifier) - .collect(Collectors.toSet()); - - for (String identifier : targetIdentifiers) { - if (!existingIdentifiers.contains(identifier)) { - violations.add(RELATION_TARGET_ENTITY_NOT_FOUND, relation.name(), identifier); - } - } - - // Validate that target entities match the expected target template - validateRelationTargetTemplates(relation, existingEntities, violations); + validateRelationsAgainstTemplate(template, providedRelations, violations, true, false); } /// Validates that all target entities have the expected target template diff --git a/src/main/java/com/decathlon/idp_core/domain/service/search/SortParameterParser.java b/src/main/java/com/decathlon/idp_core/domain/service/search/SortParameterParser.java new file mode 100644 index 00000000..7d1fd982 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/domain/service/search/SortParameterParser.java @@ -0,0 +1,58 @@ +package com.decathlon.idp_core.domain.service.search; + +import java.util.Locale; +import java.util.Optional; + +import com.decathlon.idp_core.domain.constant.SearchConstraints; +import com.decathlon.idp_core.domain.constant.ValidationMessages; +import com.decathlon.idp_core.domain.exception.search.InvalidSearchQueryException; +import com.decathlon.idp_core.domain.model.search.SortCriteria; +import com.decathlon.idp_core.domain.model.search.SortCriteria.Direction; + +/// Parses and validates entity sort parameters shared by search and listing APIs. +public final class SortParameterParser { + + private SortParameterParser() { + } + + /// Parses a sort expression in the canonical `field,direction` form. + /// A field without a direction defaults to ascending; null or blank input means + /// no sort was requested. + /// + /// @param expression caller-provided sort expression + /// @return validated sort criteria, or empty when no sort was requested + /// @throws InvalidSearchQueryException when the expression or field is invalid + public static Optional parse(String expression) { + if (expression == null || expression.isBlank()) { + return Optional.empty(); + } + + String[] parts = expression.trim().split(",", -1); + if (expression.contains(":") || parts.length > 2 || parts[0].isBlank() + || parts.length == 2 && parts[1].isBlank()) { + throw invalidFormat(expression); + } + + String field = parts[0].trim(); + if (!SearchConstraints.ALLOWED_SORT_FIELDS.contains(field)) { + throw new InvalidSearchQueryException( + ValidationMessages.SEARCH_INVALID_SORT_FIELD.formatted(field)); + } + + Direction direction = Direction.ASC; + if (parts.length == 2) { + direction = switch (parts[1].trim().toLowerCase(Locale.ROOT)) { + case "asc" -> Direction.ASC; + case "desc" -> Direction.DESC; + default -> throw invalidFormat(expression); + }; + } + + return Optional.of(new SortCriteria(field, direction)); + } + + private static InvalidSearchQueryException invalidFormat(String expression) { + return new InvalidSearchQueryException( + ValidationMessages.SEARCH_INVALID_SORT_FORMAT.formatted(expression)); + } +} diff --git a/src/main/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorService.java b/src/main/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorService.java index adf6a2db..0871b076 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorService.java @@ -47,11 +47,10 @@ public WebhookConnector getWebhookConnector(String identifier) { @Transactional public WebhookConnector createWebhookConnector(WebhookConnector connector) { - webhookConnectorValidationService.validateWebhookConnectorForCreation(connector); - WebhookConnector connectorToSave = connector.mappings().isEmpty() && connector.enabled() ? connector.withEnabled(false) : connector; + webhookConnectorValidationService.validateWebhookConnectorForCreation(connectorToSave); return webhookConnectorRepositoryPort.save(connectorToSave); } @@ -60,12 +59,15 @@ public WebhookConnector createWebhookConnector(WebhookConnector connector) { public WebhookConnector updateWebhookConnector(String identifier, @Valid WebhookConnector connectorToUpdate) { WebhookConnector webhookConnectorInDb = getWebhookConnector(identifier); - webhookConnectorValidationService.validateWebhookConnectorForUpdate(connectorToUpdate); boolean enabledValue = !connectorToUpdate.mappings().isEmpty() && connectorToUpdate.enabled(); + WebhookConnector connectorToValidate = connectorToUpdate.enabled() == enabledValue + ? connectorToUpdate + : connectorToUpdate.withEnabled(enabledValue); + webhookConnectorValidationService.validateWebhookConnectorForUpdate(connectorToValidate); WebhookConnector mergedConnector = new WebhookConnector(webhookConnectorInDb.id(), - webhookConnectorInDb.identifier(), connectorToUpdate.name(), - connectorToUpdate.description(), enabledValue, connectorToUpdate.mappings(), - connectorToUpdate.security()); + webhookConnectorInDb.identifier(), connectorToValidate.name(), + connectorToValidate.description(), connectorToValidate.enabled(), + connectorToValidate.mappings(), connectorToValidate.security()); return webhookConnectorRepositoryPort.save(mergedConnector); } diff --git a/src/main/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorValidationService.java b/src/main/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorValidationService.java index fac62077..933d7ebd 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorValidationService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorValidationService.java @@ -26,13 +26,15 @@ public class WebhookConnectorValidationService { public void validateWebhookConnectorForCreation(WebhookConnector webhookConnector) { validateIdentifierUniqueness(webhookConnector.identifier()); - webhookSecurityValidationService.validateForCreation(webhookConnector.security()); + webhookSecurityValidationService.validateForCreation(webhookConnector.security(), + webhookConnector.enabled()); } public void validateWebhookConnectorForUpdate(WebhookConnector webhookConnectorToUpdate) { validateMappingsIfPresent(webhookConnectorToUpdate); - webhookSecurityValidationService.validateForCreation(webhookConnectorToUpdate.security()); + webhookSecurityValidationService.validateForCreation(webhookConnectorToUpdate.security(), + webhookConnectorToUpdate.enabled()); } private void validateMappingsIfPresent(WebhookConnector webhookConnector) { diff --git a/src/main/java/com/decathlon/idp_core/domain/service/webhook/security/WebhookSecurityValidationService.java b/src/main/java/com/decathlon/idp_core/domain/service/webhook/security/WebhookSecurityValidationService.java index 97f95b33..fc4a9ef8 100644 --- a/src/main/java/com/decathlon/idp_core/domain/service/webhook/security/WebhookSecurityValidationService.java +++ b/src/main/java/com/decathlon/idp_core/domain/service/webhook/security/WebhookSecurityValidationService.java @@ -8,27 +8,34 @@ import com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException; import com.decathlon.idp_core.domain.model.enums.WebhookSecurityType; import com.decathlon.idp_core.domain.model.inbound_connectors.webhook.WebhookSecurity; +import com.decathlon.idp_core.domain.model.inbound_connectors.webhook.WebhookSecurityValidationPolicy; import com.decathlon.idp_core.domain.port.WebhookSecurityStrategy; /// Domain service for validating webhook security configuration at creation/update time. /// /// This service ensures that the security configuration provided when creating or updating -/// a webhook connector is valid before storing it in the database. +/// a webhook connector is valid before storing it in the database. The `NONE` security type +/// (unauthenticated webhooks) is rejected for enabled connectors unless +/// `IDP_WEBHOOK_SECURITY_ALLOW_NONE` is enabled. @Service public class WebhookSecurityValidationService { private final List strategies; + private final WebhookSecurityValidationPolicy policy; - public WebhookSecurityValidationService(List strategies) { + public WebhookSecurityValidationService(List strategies, + WebhookSecurityValidationPolicy policy) { this.strategies = List.copyOf(strategies); + this.policy = policy; } /// Validates webhook security configuration for creation or update. /// /// @param security the security configuration to validate + /// @param enabled whether the webhook connector is enabled /// @throws WebhookSecurityConfigurationException if the configuration is /// invalid - public void validateForCreation(WebhookSecurity security) { + public void validateForCreation(WebhookSecurity security, boolean enabled) { if (security == null) { throw new WebhookSecurityConfigurationException("Webhook security section is mandatory"); } @@ -37,6 +44,10 @@ public void validateForCreation(WebhookSecurity security) { if (security.type() == WebhookSecurityType.NONE) { validateNoSecurityConfig(config); + if (enabled && !policy.allowNone()) { + throw new WebhookSecurityConfigurationException( + "Webhook security type NONE is disabled. Set IDP_WEBHOOK_SECURITY_ALLOW_NONE=true to allow it"); + } return; } @@ -48,7 +59,7 @@ public void validateForCreation(WebhookSecurity security) { } private void validateNoSecurityConfig(Map config) { - if (!config.isEmpty()) { + if (config != null && !config.isEmpty()) { throw new WebhookSecurityConfigurationException( "Webhook security config must be empty when type is NONE"); } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizationRequestFactory.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizationRequestFactory.java new file mode 100644 index 00000000..12fe8a3c --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizationRequestFactory.java @@ -0,0 +1,114 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.auth; + +import java.util.Map; +import java.util.Optional; + +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerExecutionChain; +import org.springframework.web.servlet.HandlerMapping; + +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationRequest; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; +import com.decathlon.idp_core.domain.model.entity.Entity; +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; + +import lombok.extern.slf4j.Slf4j; + +/// Maps servlet requests to the framework-independent authorization context. +/// +/// The resource is read from [AuthorizedResource] on the handler resolved by Spring MVC and +/// its identifiers from the matched URI template variables, so no URL is parsed manually. +@Slf4j +@Component +public class AuthorizationRequestFactory { + + private static final String UNKNOWN_RESOURCE = "unknown"; + private static final String TEMPLATE_IDENTIFIER = "templateIdentifier"; + private static final String ENTITY_IDENTIFIER = "entityIdentifier"; + private static final String IDENTIFIER = "identifier"; + + private final HandlerMapping handlerMapping; + + /// Creates a factory backed by the MVC handler mapping. + /// + /// @param handlerMapping the mapping used to resolve the controller method of a + /// request + public AuthorizationRequestFactory( + @Lazy @Qualifier("requestMappingHandlerMapping") HandlerMapping handlerMapping) { + this.handlerMapping = handlerMapping; + } + + /// Creates an authorization request from the principal and HTTP request. + public AuthorizationRequest create(HttpServletRequest request, PrincipalInfo principal, + Optional principalEntity) { + Optional handler = resolveHandler(request); + boolean readOnly = handler.map(this::isReadOnly).orElse(false); + return new AuthorizationRequest(principal, principalEntity, + resolveAction(request.getMethod(), readOnly), resolveResource(request, handler)); + } + + private Optional resolveHandler(HttpServletRequest request) { + try { + return Optional.ofNullable(handlerMapping.getHandler(request)) + .map(HandlerExecutionChain::getHandler).filter(HandlerMethod.class::isInstance) + .map(HandlerMethod.class::cast); + } catch (Exception exception) { + log.warn("Unable to resolve handler for {} {}", request.getMethod(), request.getRequestURI(), + exception); + return Optional.empty(); + } + } + + private boolean isReadOnly(HandlerMethod handler) { + AuthorizedResource annotation = handler.getMethodAnnotation(AuthorizedResource.class); + return annotation != null && annotation.readOnly(); + } + + private AuthorizationAction resolveAction(String method, boolean readOnly) { + if ("POST".equals(method) && readOnly) { + return AuthorizationAction.READ; + } + + return switch (method) { + case "GET", "HEAD", "OPTIONS" -> AuthorizationAction.READ; + case "POST" -> AuthorizationAction.CREATE; + case "PUT", "PATCH" -> AuthorizationAction.UPDATE; + case "DELETE" -> AuthorizationAction.DELETE; + default -> AuthorizationAction.UNSUPPORTED; + }; + } + + private AuthorizationResource resolveResource(HttpServletRequest request, + Optional handler) { + String type = handler.flatMap(this::resourceType).orElse(UNKNOWN_RESOURCE); + Map variables = pathVariables(request); + Optional identifier = Optional.ofNullable(variables.get(ENTITY_IDENTIFIER)) + .or(() -> Optional.ofNullable(variables.get(IDENTIFIER))); + return new AuthorizationResource(type, identifier, + Optional.ofNullable(variables.get(TEMPLATE_IDENTIFIER))); + } + + private Optional resourceType(HandlerMethod handler) { + AuthorizedResource onMethod = handler.getMethodAnnotation(AuthorizedResource.class); + if (onMethod != null && !onMethod.value().isBlank()) { + return Optional.of(onMethod.value()); + } + return Optional + .ofNullable(AnnotatedElementUtils.findMergedAnnotation(handler.getBeanType(), + AuthorizedResource.class)) + .map(AuthorizedResource::value).filter(value -> !value.isBlank()); + } + + @SuppressWarnings("unchecked") + private Map pathVariables(HttpServletRequest request) { + Object variables = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); + return variables instanceof Map map ? (Map) map : Map.of(); + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizedResource.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizedResource.java new file mode 100644 index 00000000..3ed985d5 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizedResource.java @@ -0,0 +1,25 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.auth; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/// Declares the authorization resource exposed by a controller or endpoint. +/// +/// A class-level declaration provides the default resource type; a method-level +/// declaration overrides it and may flag a non-safe HTTP method as read-only. +/// Path variables named `templateIdentifier`, `entityIdentifier` and `identifier` +/// are used to populate the resource context. +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface AuthorizedResource { + + /// Resource type; blank on a method means "inherit from the controller". + String value() default ""; + + /// Marks an endpoint that uses POST but only reads data (search, dry-run). + boolean readOnly() default false; +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilter.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilter.java new file mode 100644 index 00000000..9191811d --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilter.java @@ -0,0 +1,130 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.auth; + +import java.io.IOException; +import java.util.Optional; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.jspecify.annotations.NonNull; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import com.decathlon.idp_core.domain.exception.authorization.PrincipalNotAuthorizedException; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationRequest; +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; +import com.decathlon.idp_core.domain.service.authorization.GlobalAuthorizationService; +import com.decathlon.idp_core.domain.service.principal.PrincipalProvisioningService; +import com.decathlon.idp_core.infrastructure.adapters.api.exception.MissingPrincipalIdentifierException; +import com.decathlon.idp_core.infrastructure.adapters.api.handler.ApiErrorResponseWriter; +import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; + +import lombok.extern.slf4j.Slf4j; + +/// Enforces the global authorization policy for authenticated API requests. +@Slf4j +@Component +public class GlobalAuthorizationFilter extends OncePerRequestFilter { + + private final PrincipalExtractor principalExtractor; + private final PrincipalProvisioningService provisioningService; + private final GlobalAuthorizationService authorizationService; + private final AuthorizationPolicy authorizationPolicy; + private final AuthorizationRequestFactory authorizationRequestFactory; + private final ApiErrorResponseWriter errorResponseWriter; + + /// Creates a filter backed by the domain authorization service and configured + /// policy. + /// + /// @param principalExtractor converts Spring authentication into a domain + /// principal + /// @param provisioningService retrieves the principal's catalog entity + /// @param authorizationService evaluates the authorization policy + /// @param authorizationPolicy configured policy for authenticated requests + /// @param authorizationRequestFactory maps HTTP input to domain authorization + /// context + /// @param errorResponseWriter writes standard ProblemDetail errors at the + /// filter + /// boundary + public GlobalAuthorizationFilter(PrincipalExtractor principalExtractor, + PrincipalProvisioningService provisioningService, + GlobalAuthorizationService authorizationService, AuthorizationPolicy authorizationPolicy, + AuthorizationRequestFactory authorizationRequestFactory, + ApiErrorResponseWriter errorResponseWriter) { + this.principalExtractor = principalExtractor; + this.provisioningService = provisioningService; + this.authorizationService = authorizationService; + this.authorizationPolicy = authorizationPolicy; + this.authorizationRequestFactory = authorizationRequestFactory; + this.errorResponseWriter = errorResponseWriter; + } + + @Override + protected void doFilterInternal(@NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) + throws ServletException, IOException { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null || !authentication.isAuthenticated() + || authentication instanceof AnonymousAuthenticationToken) { + filterChain.doFilter(request, response); + return; + } + + var context = request.getAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE); + var principalContext = context instanceof ProvisionedPrincipalContext provisionedContext + ? provisionedContext + : null; + Optional principalInfo = principalContext != null + ? Optional.of(principalContext.principal()) + : extractPrincipal(authentication, request, response); + if (principalInfo.isEmpty()) { + return; + } + PrincipalInfo principal = principalInfo.orElseThrow(); + var principalEntity = principalContext != null + ? principalContext.principalEntity() + : provisioningService.findPrincipalWithSameKind(principal); + AuthorizationRequest authorizationRequest = authorizationRequestFactory.create(request, + principal, principalEntity); + + try { + authorizationService.authorize(authorizationRequest, authorizationPolicy); + } catch (PrincipalNotAuthorizedException _) { + log.debug( + "Authorization evaluation: result=DENIED, principal={}, kind={}, action={}, " + + "resource={}, method={}, path={}", + principal.identifier(), principal.kind(), authorizationRequest.action(), + authorizationRequest.resource().type(), request.getMethod(), request.getRequestURI()); + log.warn("Authorization denied for principal {} on {} {}", principal.identifier(), + request.getMethod(), request.getRequestURI()); + errorResponseWriter.write(request, response, HttpStatus.FORBIDDEN, + "Principal is not authorized to perform this operation"); + return; + } + + log.debug( + "Authorization evaluation: result=GRANTED, principal={}, kind={}, action={}, " + + "resource={}, method={}, path={}", + principal.identifier(), principal.kind(), authorizationRequest.action(), + authorizationRequest.resource().type(), request.getMethod(), request.getRequestURI()); + filterChain.doFilter(request, response); + } + + private Optional extractPrincipal(Authentication authentication, + HttpServletRequest request, HttpServletResponse response) throws IOException { + try { + return Optional.of(principalExtractor.extractPrincipalInfo(authentication)); + } catch (MissingPrincipalIdentifierException exception) { + log.warn("Authentication rejected: {}", exception.getMessage()); + errorResponseWriter.write(request, response, HttpStatus.UNAUTHORIZED, exception.getMessage()); + return Optional.empty(); + } + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/JitProvisioningFilter.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/JitProvisioningFilter.java index 5a8a48f4..16e92ec4 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/JitProvisioningFilter.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/JitProvisioningFilter.java @@ -1,24 +1,33 @@ package com.decathlon.idp_core.infrastructure.adapters.api.auth; import java.io.IOException; +import java.util.Optional; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import org.jspecify.annotations.NonNull; +import org.springframework.http.HttpStatus; import org.springframework.http.server.PathContainer; -import org.springframework.lang.NonNull; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.pattern.PathPatternParser; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationMode; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.domain.model.entity.Entity; import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; import com.decathlon.idp_core.domain.service.principal.PrincipalProvisioningService; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.AuthenticationProperties; +import com.decathlon.idp_core.infrastructure.adapters.api.configuration.PrincipalProvisioningMode; +import com.decathlon.idp_core.infrastructure.adapters.api.configuration.PrincipalProvisioningProperties; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.SecurityConfiguration; +import com.decathlon.idp_core.infrastructure.adapters.api.exception.MissingPrincipalIdentifierException; +import com.decathlon.idp_core.infrastructure.adapters.api.handler.ApiErrorResponseWriter; import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; import lombok.RequiredArgsConstructor; @@ -34,7 +43,8 @@ /// /// **Design rationale:** Positioned after Spring Security authentication but before /// controllers, ensuring JIT provisioning happens transparently for all API endpoints. -/// Failures are logged but don't block the request (fail-open for availability). +/// Provisioning failures reject the request so authorization cannot proceed without a +/// verified principal link. /// /// **Excluded Paths:** Public endpoints (health checks, documentation, etc.) are excluded /// from JIT provisioning to avoid unnecessary database queries and log pollution. @@ -49,11 +59,28 @@ @RequiredArgsConstructor public class JitProvisioningFilter extends OncePerRequestFilter { + private static final PathPatternParser PATTERN_PARSER = new PathPatternParser(); + private final PrincipalExtractor principalExtractor; private final PrincipalProvisioningService provisioningService; private final AuthenticationProperties authProperties; - private final PathPatternParser patternParser = new PathPatternParser(); + private final PrincipalProvisioningProperties provisioningProperties; + private final AuthorizationPolicy authorizationPolicy; + private final ApiErrorResponseWriter errorResponseWriter; + /// Verifies an authenticated principal before allowing the request to continue. + /// + /// Unauthenticated and anonymous requests pass through for the configured + /// security + /// chain to handle. Authenticated requests stop here if extraction or + /// provisioning + /// fails, or if the principal cannot be linked. + /// + /// @param request current HTTP request + /// @param response current HTTP response + /// @param filterChain remaining filters and request handler + /// @throws ServletException if a downstream filter fails + /// @throws IOException if request processing fails @Override protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) @@ -61,36 +88,115 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.isAuthenticated() - && !isAnonymous(authentication)) { - provisionPrincipalSafely(authentication); + if (authentication != null && authentication.isAuthenticated() && !isAnonymous(authentication) + && !provisionPrincipalSafely(request, response, authentication)) { + return; } filterChain.doFilter(request, response); } - private void provisionPrincipalSafely(Authentication authentication) { + /// Extracts the authenticated identity and applies the configured + /// principal-linking mode. + /// + /// On success, stores the verified principal context on the request for + /// authorization. + /// Missing links are rejected, while unexpected provisioning failures return a + /// service + /// unavailable response and prevent the request from continuing. + /// + /// @param request current HTTP request + /// @param response current HTTP response + /// @param authentication Spring Security authentication + /// @return `true` when principal verification succeeds; otherwise `false` + /// @throws IOException if writing an error response fails + private boolean provisionPrincipalSafely(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) throws IOException { + PrincipalInfo principalInfo; try { - PrincipalInfo principalInfo = principalExtractor.extractPrincipalInfo(authentication); + principalInfo = principalExtractor.extractPrincipalInfo(authentication); + } catch (MissingPrincipalIdentifierException exception) { + log.warn("Authentication rejected: {}", exception.getMessage()); + errorResponseWriter.write(request, response, HttpStatus.UNAUTHORIZED, exception.getMessage()); + return false; + } + + try { + if (provisioningProperties != null + && provisioningProperties.mode() == PrincipalProvisioningMode.LINK_ONLY) { + Optional linkedPrincipal = provisioningService + .findPrincipalWithSameKind(principalInfo); + if (linkedPrincipal.isEmpty()) { + if (authorizationPolicy.mode() == AuthorizationMode.GLOBAL && authorizationPolicy + .globalPrincipalIdentifiers().contains(principalInfo.identifier())) { + Entity globalPrincipal = provisioningService + .provisionGlobalAdministrator(principalInfo); + log.debug( + "Principal evaluation accepted: mode={}, principal={}, kind={}, linked=true, " + + "global=true", + PrincipalProvisioningMode.LINK_ONLY, principalInfo.identifier(), + principalInfo.kind()); + request.setAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE, + new ProvisionedPrincipalContext(principalInfo, Optional.of(globalPrincipal))); + return true; + } + log.debug("Principal evaluation rejected: mode={}, principal={}, kind={}, linked=false", + PrincipalProvisioningMode.LINK_ONLY, principalInfo.identifier(), + principalInfo.kind()); + errorResponseWriter.write(request, response, HttpStatus.UNAUTHORIZED, + "No linked principal matches the authenticated identity"); + return false; + } + log.debug("Principal evaluation accepted: mode={}, principal={}, kind={}, linked=true", + PrincipalProvisioningMode.LINK_ONLY, principalInfo.identifier(), principalInfo.kind()); + request.setAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE, + new ProvisionedPrincipalContext(principalInfo, linkedPrincipal)); + return true; + } + provisioningService.provisionPrincipal(principalInfo); + Optional matchingPrincipal = provisioningService + .findPrincipalWithSameKind(principalInfo); + if (matchingPrincipal.isEmpty()) { + log.debug("Principal evaluation rejected: mode={}, principal={}, kind={}, linked=false", + PrincipalProvisioningMode.JIT, principalInfo.identifier(), principalInfo.kind()); + errorResponseWriter.write(request, response, HttpStatus.UNAUTHORIZED, + "No linked principal matches the authenticated identity"); + return false; + } + log.debug("Principal evaluation accepted: mode={}, principal={}, kind={}, linked=true", + PrincipalProvisioningMode.JIT, principalInfo.identifier(), principalInfo.kind()); + request.setAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE, + new ProvisionedPrincipalContext(principalInfo, matchingPrincipal)); log.debug("JIT provisioning successful for principal: {} (kind: {})", principalInfo.identifier(), principalInfo.kind()); + return true; } catch (Exception e) { - // Log error but don't block the request - fail-open for availability - // The principal may not have a catalog entry, but can still authenticate log.warn("JIT provisioning failed for authenticated principal: {}", e.getMessage(), e); + errorResponseWriter.write(request, response, HttpStatus.SERVICE_UNAVAILABLE, + "Unable to verify your access at this time. Please try again later."); + return false; } } + /// Checks whether the supplied authentication represents an anonymous user. + /// + /// @param authentication Spring Security authentication to inspect + /// @return `true` when the authentication is anonymous private boolean isAnonymous(Authentication authentication) { return authentication instanceof org.springframework.security.authentication.AnonymousAuthenticationToken; } + /// Excludes configured public paths from principal provisioning. + /// + /// @param request current HTTP request + /// @return `true` when the request path matches a configured exclusion + /// pattern @Override protected boolean shouldNotFilter(@NonNull HttpServletRequest request) { String path = request.getRequestURI(); return authProperties.jitProvisioningExcludedPaths().stream() - .anyMatch(pattern -> patternParser.parse(pattern).matches(PathContainer.parsePath(path))); + .anyMatch(pattern -> PATTERN_PARSER.parse(pattern).matches(PathContainer.parsePath(path))); } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/ProvisionedPrincipalContext.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/ProvisionedPrincipalContext.java new file mode 100644 index 00000000..526b92f8 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/ProvisionedPrincipalContext.java @@ -0,0 +1,13 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.auth; + +import java.util.Optional; + +import com.decathlon.idp_core.domain.model.entity.Entity; +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; + +/// Request-scoped result shared by JIT provisioning and global authorization. +public record ProvisionedPrincipalContext(PrincipalInfo principal, + Optional principalEntity) { + + public static final String REQUEST_ATTRIBUTE = ProvisionedPrincipalContext.class.getName(); +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/RequestAuthorizer.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/RequestAuthorizer.java new file mode 100644 index 00000000..bc804d66 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/RequestAuthorizer.java @@ -0,0 +1,63 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.auth; + +import java.util.Optional; + +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +import com.decathlon.idp_core.domain.exception.authorization.PrincipalNotAuthorizedException; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationRequest; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; +import com.decathlon.idp_core.domain.model.entity.Entity; +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; +import com.decathlon.idp_core.domain.service.authorization.GlobalAuthorizationService; +import com.decathlon.idp_core.domain.service.principal.PrincipalProvisioningService; +import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; + +import lombok.RequiredArgsConstructor; + +/// Reapplies global authorization after a controller has resolved body-only resource context. +@Component +@RequiredArgsConstructor +public class RequestAuthorizer { + + private final PrincipalExtractor principalExtractor; + private final PrincipalProvisioningService provisioningService; + private final GlobalAuthorizationService authorizationService; + private final AuthorizationPolicy authorizationPolicy; + + /// Authorizes a sensitive operation using its fully resolved resource context. + /// + /// @param request current HTTP request + /// @param action operation being performed + /// @param resource resource context resolved from the request body + public void authorize(HttpServletRequest request, AuthorizationAction action, + AuthorizationResource resource) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null || !authentication.isAuthenticated() + || authentication instanceof AnonymousAuthenticationToken) { + throw new PrincipalNotAuthorizedException("unknown"); + } + + Object context = request.getAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE); + ProvisionedPrincipalContext provisionedContext = context instanceof ProvisionedPrincipalContext value + ? value + : null; + PrincipalInfo principal = provisionedContext != null + ? provisionedContext.principal() + : principalExtractor.extractPrincipalInfo(authentication); + Optional principalEntity = provisionedContext != null + ? provisionedContext.principalEntity() + : provisioningService.findPrincipalWithSameKind(principal); + + authorizationService.authorize( + new AuthorizationRequest(principal, principalEntity, action, resource), + authorizationPolicy); + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UnifiedUserProvider.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UnifiedUserProvider.java index 875b63b0..9b6cd594 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UnifiedUserProvider.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UnifiedUserProvider.java @@ -1,24 +1,24 @@ package com.decathlon.idp_core.infrastructure.adapters.api.auth; -import java.util.Optional; - import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.oauth2.core.oidc.user.OidcUser; -import org.springframework.security.oauth2.core.user.OAuth2User; -import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.stereotype.Component; -/// UnifiedUserProvider is a Spring component that implements the UserIdentityProvider interface to provide a consistent way +import com.decathlon.idp_core.domain.port.audit.AuditIdentityProviderPort; +import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; + +import lombok.RequiredArgsConstructor; + +/// UnifiedUserProvider is a Spring component that implements the AuditIdentityProviderPort interface to provide a consistent way /// to retrieve the authenticated user's identity across different authentication mechanisms (JWT, OAuth2, OpenID). -/// It checks the current security context for the authentication type and extracts the user ID accordingly: -/// - For JWT authentication, it retrieves the subject (sub) claim from the JWT token. -/// - For OAuth2 authentication, it first checks if the user is an OIDC user to -/// retrieve the subject, otherwise it looks for a "sub" or "id" attribute in the OAuth2 user attributes, falling back to the authentication name if neither is found. -/// - For basic authentication, it simply returns the authentication name. +/// The shared principal extractor keeps audit identities aligned with the identifiers used for provisioning +/// and authorization. @Component -public class UnifiedUserProvider implements UserIdentityProvider { +@RequiredArgsConstructor +public class UnifiedUserProvider implements AuditIdentityProviderPort { + + private final PrincipalExtractor principalExtractor; @Override public String getAuthId() { @@ -29,25 +29,7 @@ public String getAuthId() { return "UNKNOWN"; } - // Jwt Case - if (authentication instanceof JwtAuthenticationToken jwtToken) { - return jwtToken.getToken().getSubject(); - } - - // OAuth2 and OpenId case - if (authentication.getPrincipal()instanceof OAuth2User oauth2Token) { - - if (oauth2Token instanceof OidcUser oidcUser) { - return oidcUser.getSubject(); - } - - return Optional.ofNullable(oauth2Token.getAttribute("sub")).map(Object::toString) - .orElseGet(() -> Optional.ofNullable(oauth2Token.getAttribute("id")).map(Object::toString) - .orElse(authentication.getName())); - } - - // Basic Auth case - return authentication.getName(); + return principalExtractor.extractPrincipalInfo(authentication).identifier(); } @Override diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UserIdentityProvider.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UserIdentityProvider.java deleted file mode 100644 index 3ec29a3b..00000000 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UserIdentityProvider.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.decathlon.idp_core.infrastructure.adapters.api.auth; - -public interface UserIdentityProvider { - String getAuthId(); - String getName(); -} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthenticationProperties.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthenticationProperties.java index bdd62f7b..7893e05b 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthenticationProperties.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthenticationProperties.java @@ -7,75 +7,34 @@ import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; -/** - * Type-safe authentication and JWT configuration properties bound from - * {@code app.security.authentication}. - * - *

Purpose

Externalizes all hardcoded authentication logic to - * configuration, enabling: - *
    - *
  • Support for multiple Identity Providers (Auth0, Keycloak, Azure AD, - * etc.)
  • - *
  • Flexible service account detection without code changes
  • - *
  • Conditional authentication mechanism selection per environment
  • - *
  • Clear documentation of IdP-specific token claim expectations
  • - *
- * - *

Design rationale

Follows the same pattern as {@code CorsProperties} - * and {@code SecurityRoleProperties}. Configuration is externalized to - * {@code application.yml} for easy environment customization. - * - *

Claim Mapping Strategy

Different IdPs use different JWT claim names - * for the same semantic meaning. This configuration allows mapping IdP-specific - * claim names to standardized extraction logic. - *

- * Examples: - *

    - *
  • Auth0: {@code preferred_username} (username) vs. {@code sub} (unique - * ID)
  • - *
  • Azure AD: {@code unique_name} vs. {@code oid}
  • - *
  • Keycloak: {@code preferred_username} vs. {@code sub}
  • - *
- * - *

Service Account Detection

Service accounts (M2M tokens) can be - * identified in multiple ways depending on the IdP: - *
    - *
  • Strict Mode (Recommended): Single definitive claim - * (e.g., {@code token_type=m2m}, {@code client_credentials})
  • - *
  • Legacy Mode: Multiple fallback claims (for backwards - * compatibility with existing deployments)
  • - *
- * - * @see SecurityConfiguration - * @see PrincipalExtractor - */ +/// Type-safe authentication configuration properties bound from +/// `app.security.authentication`. +/// +/// # Purpose +/// Externalizes hardcoded authentication logic to configuration, enabling: +/// - Support for multiple identity providers (Auth0, Keycloak, Azure AD, etc.) +/// - Flexible authentication mechanism configuration +/// - Conditional authentication mechanism selection per environment +/// - Clear documentation of identity-provider-specific token claim expectations +/// +/// # Design Rationale +/// Configuration is externalized to `application.yml` for easy environment +/// customization. +/// +/// # Principal Identifier +/// OAuth2 users use the provider-configured principal name, while OIDC users use +/// the standard subject. JWT resource-server identifiers and classification are +/// configured by [PrincipalExtractionProperties]. +/// +/// @see SecurityConfiguration +/// @see PrincipalExtractor @ConfigurationProperties(prefix = "app.security.authentication") public record AuthenticationProperties( - // Maps standard claim names to the names used by the configured identity + // Maps optional standard claims to the names used by the configured identity // provider. Map userClaimMappings, - // Controls strict or legacy detection of machine-to-machine tokens. - ServiceAccountDetection serviceAccountDetection, - // Public paths excluded from JIT provisioning. List jitProvisioningExcludedPaths) { - // Configuration used to identify service accounts. - public record ServiceAccountDetection( - // Enables or disables service account detection. - boolean enabled, - - // "strict" checks one claim; "legacy" checks the configured fallbacks. - String mode, - - // Claim checked in strict mode. - String definitiveClaimName, - - // Value that identifies a service account in strict mode. - String definitiveClaimValue, - - // Claims checked as fallbacks in legacy mode. - List legacyFallbackClaims) { - } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationConfiguration.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationConfiguration.java new file mode 100644 index 00000000..c0979273 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationConfiguration.java @@ -0,0 +1,43 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import java.util.Optional; +import java.util.Set; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.GlobalAuthorizationFilter; + +/// Bridges external authorization properties into the pure domain policy. +@Configuration +@EnableConfigurationProperties({AuthorizationProperties.class, + PrincipalProvisioningProperties.class}) +public class AuthorizationConfiguration { + + /// Binds a disabled servlet registration so the filter only runs in selected + /// security chains. + /// + /// @param filter the filter instance used by the JWT and mock security chains + /// @return a disabled servlet-container registration + @Bean + public FilterRegistrationBean globalAuthorizationFilterRegistration( + GlobalAuthorizationFilter filter) { + var registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + + /// Creates the pure domain policy from externalized authorization settings. + /// + /// @param properties external authorization configuration + /// @return an immutable domain authorization policy + @Bean + public AuthorizationPolicy authorizationPolicy(AuthorizationProperties properties) { + return new AuthorizationPolicy(properties.mode(), + Set.copyOf(properties.globalPrincipalIdentifiers()), + Optional.ofNullable(properties.requiredPrincipalProperty())); + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationProperties.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationProperties.java new file mode 100644 index 00000000..ba1363aa --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationProperties.java @@ -0,0 +1,24 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import com.decathlon.idp_core.domain.model.authorization.AuthorizationMode; + +/// Authorization settings bound from `app.security.authorization`. +@ConfigurationProperties(prefix = "app.security.authorization") +public record AuthorizationProperties(AuthorizationMode mode, + List globalPrincipalIdentifiers, String requiredPrincipalProperty) { + + public AuthorizationProperties { + mode = mode != null ? mode : AuthorizationMode.GLOBAL; + globalPrincipalIdentifiers = globalPrincipalIdentifiers != null + ? globalPrincipalIdentifiers.stream() + .filter(identifier -> identifier != null && !identifier.isBlank()).map(String::trim) + .toList() + : List.of(); + requiredPrincipalProperty = requiredPrincipalProperty == null + || requiredPrincipalProperty.isBlank() ? null : requiredPrincipalProperty.trim(); + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/JwtConfiguration.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/JwtConfiguration.java index 26e7b02f..1ff41d8e 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/JwtConfiguration.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/JwtConfiguration.java @@ -1,11 +1,23 @@ package com.decathlon.idp_core.infrastructure.adapters.api.configuration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; +import org.springframework.security.oauth2.core.OAuth2TokenValidator; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; +import org.springframework.security.oauth2.jwt.JwtClaimValidator; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtValidators; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; /// Custom JWT decoder configuration for OAuth2 resource server integration. @@ -20,20 +32,63 @@ /// /// **Security considerations:** Maintains security while providing flexibility for various /// identity provider implementations that may not follow all JWKS specifications exactly. +/// +/// **Token binding:** a valid signature only proves that the token comes from the identity +/// provider, not that it was issued for this service. When +/// `app.security.authentication.jwt.issuer-uri` and/or `...jwt.audiences` are set, the `iss` +/// and `aud` claims are validated in addition to the signature and timestamps. Both are +/// optional for backward compatibility; a warning is logged at startup when either is missing. @Configuration @ConditionalOnProperty(prefix = "app.security.authentication.jwt", name = "enabled", havingValue = "true", matchIfMissing = false) public class JwtConfiguration { + private static final Logger LOGGER = LoggerFactory.getLogger(JwtConfiguration.class); + private final String jwkSetUri; + private final String issuerUri; + private final List audiences; public JwtConfiguration( - @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}") String jwkSetUri) { + @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}") String jwkSetUri, + @Value("${app.security.authentication.jwt.issuer-uri:}") String issuerUri, + @Value("${app.security.authentication.jwt.audiences:}") String audiences) { this.jwkSetUri = jwkSetUri; + this.issuerUri = issuerUri == null ? "" : issuerUri.trim(); + this.audiences = audiences == null + ? List.of() + : Arrays.stream(audiences.split(",")).map(String::trim).filter(a -> !a.isEmpty()).toList(); } @Bean @ConditionalOnMissingBean public JwtDecoder jwtDecoder() { - return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); + NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); + decoder.setJwtValidator(jwtValidator()); + return decoder; + } + + /// Builds the claim validators applied after signature verification. + /// + /// Timestamps are always validated. The issuer is validated when configured, + /// and the token + /// must carry at least one of the configured audiences when any is configured. + OAuth2TokenValidator jwtValidator() { + List> validators = new ArrayList<>(); + if (issuerUri.isEmpty()) { + LOGGER.warn( + "app.security.authentication.jwt.issuer-uri is not set: the JWT issuer (iss) is not validated."); + validators.add(JwtValidators.createDefault()); + } else { + validators.add(JwtValidators.createDefaultWithIssuer(issuerUri)); + } + if (audiences.isEmpty()) { + LOGGER.warn( + "app.security.authentication.jwt.audiences is not set: the JWT audience (aud) is not validated, " + + "tokens issued for other applications of the same identity provider are accepted."); + } else { + validators.add(new JwtClaimValidator>(JwtClaimNames.AUD, + aud -> aud != null && aud.stream().anyMatch(audiences::contains))); + } + return new DelegatingOAuth2TokenValidator<>(validators); } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalExtractionProperties.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalExtractionProperties.java new file mode 100644 index 00000000..2175bd89 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalExtractionProperties.java @@ -0,0 +1,43 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Provider-specific JWT principal classification and identifier configuration. + * + * @param humanIndicatorClaims + * claims whose nonblank values identify human tokens + * @param human + * human principal identifier configuration + * @param machine + * machine principal identifier and namespace configuration + */ +@ConfigurationProperties(prefix = "app.security.authentication.principal-extraction") +public record PrincipalExtractionProperties(List humanIndicatorClaims, Human human, + Machine machine) { + + public PrincipalExtractionProperties { + humanIndicatorClaims = humanIndicatorClaims == null + ? List.of() + : List.copyOf(humanIndicatorClaims); + human = human == null ? new Human("sub") : human; + machine = machine == null ? new Machine("client_id", "") : machine; + } + + /** Human principal identifier claim. */ + public record Human(String idClaim) { + public Human { + idClaim = idClaim == null || idClaim.isBlank() ? "sub" : idClaim.trim(); + } + } + + /** Machine principal identifier claim and optional identifier prefix. */ + public record Machine(String idClaim, String idPrefix) { + public Machine { + idClaim = idClaim == null || idClaim.isBlank() ? "client_id" : idClaim.trim(); + idPrefix = idPrefix == null ? "" : idPrefix; + } + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalProvisioningMode.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalProvisioningMode.java new file mode 100644 index 00000000..89ac101e --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalProvisioningMode.java @@ -0,0 +1,6 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +/// Controls whether authenticated principals are created or only linked to existing records. +public enum PrincipalProvisioningMode { + JIT, LINK_ONLY +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalProvisioningProperties.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalProvisioningProperties.java new file mode 100644 index 00000000..b0e80ce2 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalProvisioningProperties.java @@ -0,0 +1,12 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/// Principal provisioning settings bound from `app.security.principal-provisioning`. +@ConfigurationProperties(prefix = "app.security.principal-provisioning") +public record PrincipalProvisioningProperties(PrincipalProvisioningMode mode) { + + public PrincipalProvisioningProperties { + mode = mode != null ? mode : PrincipalProvisioningMode.JIT; + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationConfiguration.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationConfiguration.java new file mode 100644 index 00000000..6912d0d4 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationConfiguration.java @@ -0,0 +1,24 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.decathlon.idp_core.domain.model.enums.RelationTargetValidationMode; + +/// Bridges external relation validation settings into the domain mode. +@Configuration +@EnableConfigurationProperties(RelationValidationProperties.class) +public class RelationValidationConfiguration { + + /// Exposes the configured mode without making the domain depend on Spring + /// configuration types. + /// + /// @param properties the externalized relation validation settings + /// @return the configured target validation mode + @Bean + public RelationTargetValidationMode relationTargetValidationMode( + RelationValidationProperties properties) { + return properties.targetValidationMode(); + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationProperties.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationProperties.java new file mode 100644 index 00000000..2397f475 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationProperties.java @@ -0,0 +1,12 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; + +import com.decathlon.idp_core.domain.model.enums.RelationTargetValidationMode; + +/// Relation target validation settings bound from `app.relations`. +@ConfigurationProperties(prefix = "app.relations") +public record RelationValidationProperties( + @DefaultValue("STRICT") RelationTargetValidationMode targetValidationMode) { +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SearchProperties.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SearchProperties.java new file mode 100644 index 00000000..2d0b59a1 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SearchProperties.java @@ -0,0 +1,20 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import jakarta.validation.constraints.Min; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; +import org.springframework.validation.annotation.Validated; + +import com.decathlon.idp_core.domain.constant.SearchConstraints; + +/// Configuration properties for search and listing pagination. +/// +/// Binds `app.max-page-size`, which can be overridden with the +/// `MAX_PAGE_SIZE` environment variable. Defaults to +/// [SearchConstraints#DEFAULT_MAX_PAGE_SIZE]. +@Validated +@ConfigurationProperties(prefix = "app") +public record SearchProperties( + @DefaultValue("" + SearchConstraints.DEFAULT_MAX_PAGE_SIZE) @Min(1) int maxPageSize) { +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityConfiguration.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityConfiguration.java index cee1de3a..dadd19cd 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityConfiguration.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityConfiguration.java @@ -6,7 +6,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; @@ -42,25 +41,19 @@ /// @see JitProvisioningFilter @Configuration @EnableWebSecurity -@EnableConfigurationProperties({CorsProperties.class, SecurityRoleProperties.class, - AuthenticationProperties.class}) +@EnableConfigurationProperties({CorsProperties.class, AuthenticationProperties.class, + PrincipalExtractionProperties.class}) public class SecurityConfiguration { private final CorsProperties corsProperties; - private final SecurityRoleProperties securityRoleProperties; - public SecurityConfiguration(CorsProperties corsProperties, - SecurityRoleProperties securityRoleProperties) { + public SecurityConfiguration(CorsProperties corsProperties) { this.corsProperties = corsProperties; - this.securityRoleProperties = securityRoleProperties; } @Bean public JwtAuthenticationConverter jwtAuthenticationConverter() { - JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); - converter.setJwtGrantedAuthoritiesConverter( - jwt -> List.of(new SimpleGrantedAuthority(securityRoleProperties.baselineRole()))); - return converter; + return new JwtAuthenticationConverter(); } @Bean diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityRoleProperties.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityRoleProperties.java deleted file mode 100644 index 46d3b50a..00000000 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityRoleProperties.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.decathlon.idp_core.infrastructure.adapters.api.configuration; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/// Configuration properties for security role assignment. -/// -/// **Business purpose:** Externalizes baseline role configuration to enable -/// easy transition from V1 (global admin for all) to V2 (granular RBAC). -/// -/// **Usage:** Bind via `@EnableConfigurationProperties` in SecurityConfiguration. -@ConfigurationProperties(prefix = "app.security.roles") -public record SecurityRoleProperties(String baselineRole) { - - /// Default baseline role is `*` (Super Admin) for V1 phase. - public SecurityRoleProperties { - if (baselineRole == null || baselineRole.isBlank()) { - baselineRole = "*"; - } - } -} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerConfiguration.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerConfiguration.java index 94d9e28a..bdfe0837 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerConfiguration.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerConfiguration.java @@ -5,6 +5,7 @@ import java.util.List; +import org.springdoc.core.customizers.GlobalOpenApiCustomizer; import org.springdoc.core.models.GroupedOpenApi; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -25,6 +26,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.media.DateTimeSchema; +import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.security.OAuthFlow; import io.swagger.v3.oas.models.security.OAuthFlows; import io.swagger.v3.oas.models.security.SecurityRequirement; @@ -98,6 +101,34 @@ public OpenAPI openAPI() { return openApi; } + /** + * Documents the ProblemDetail extension members at the schema root, matching + * the wire format (Jackson unwraps the properties map), instead of a nested + * "properties" object. + */ + @Bean + public GlobalOpenApiCustomizer problemDetailSchemaCustomizer() { + return openApi -> { + if (openApi.getComponents() == null || openApi.getComponents().getSchemas() == null) { + return; + } + io.swagger.v3.oas.models.media.Schema problemDetail = openApi.getComponents().getSchemas() + .get("ProblemDetail"); + if (problemDetail == null) { + return; + } + if (problemDetail.getProperties() != null) { + problemDetail.getProperties().remove("properties"); + } + problemDetail.addProperty("error", + new StringSchema().description("HTTP status name, e.g. NOT_FOUND")); + problemDetail.addProperty("error_description", + new StringSchema().description("Human-readable description of the error")); + problemDetail.addProperty("timestamp", + new DateTimeSchema().description("Instant at which the error occurred")); + }; + } + @Bean public GroupedOpenApi allApis() { return GroupedOpenApi.builder().group("internal").pathsToMatch("/**").build(); diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerDescription.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerDescription.java index 213d51a6..e765e0a5 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerDescription.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerDescription.java @@ -66,6 +66,24 @@ public class SwaggerDescription { public static final String ENDPOINT_POST_ENTITY_SUMMARY = "Create a new entity"; public static final String ENDPOINT_POST_ENTITY_DESCRIPTION = "Create a new entity in the system with the provided information"; + public static final String ENTITY_SEARCH_REQUEST_EXAMPLE = """ + { + "query": "test", + "filter": { + "connector": "AND", + "criteria": [ + { + "field": "template", + "operation": "EQ", + "value": "service" + } + ] + }, + "page": 0, + "size": 20, + "sort": "identifier,asc" + } + """; public static final String ENDPOINT_PUT_ENTITY_SUMMARY = "Update an existing entity"; public static final String ENDPOINT_PUT_ENTITY_DESCRIPTION = "Update an existing entity in the system with the provided information"; @@ -185,6 +203,7 @@ public class SwaggerDescription { public static final String FIELD_ENTITY_RELATIONS = "List of relations for this entity"; public static final String FIELD_ENTITY_RELATION_NAME = "Name of the relation (must match a template relation definition)"; public static final String FIELD_ENTITY_RELATION_TARGETS = "List of target entity identifiers for this relation"; + public static final String FIELD_RELATION_ENTITY_PROPERTIES = "Property values for the related entity; included only when include_relations_properties=true"; public static final String FIELD_PROPERTY_ID = "Unique identifier of the property definition"; public static final String FIELD_PROPERTY_NAME = "Property name"; @@ -221,8 +240,8 @@ public class SwaggerDescription { // --- Pagination and sorting parameter descriptions --- public static final String PARAM_PAGE_DESCRIPTION = "Page number for pagination. Defaults to 0."; - public static final String PARAM_SIZE_DESCRIPTION = "Number of items per page. Defaults to 20."; - public static final String PARAM_SORT_DESCRIPTION = "Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc."; + public static final String PARAM_SIZE_DESCRIPTION = "Number of items per page. Defaults to 20. Must be between 1 and 500."; + public static final String PARAM_SORT_DESCRIPTION = "Sorting criteria in the format: field[,asc|desc]"; public static final String PARAM_QUERY_DESCRIPTION = """ Optional filter query using a simple expression language. See more details in the API documentation. Example: `name:idp` for entities with names containing 'idp'. """; @@ -232,9 +251,11 @@ public class SwaggerDescription { public static final String PARAM_DEPTH_DESCRIPTION = "Maximum traversal depth for relationship resolution. Clamped between 1 and 6."; public static final String RELATIONS_DEPTH_DESCRIPTION = "Maximum depth to traverse when collecting entity relations. Defaults to 1. Valid range: 1-6."; public static final String RELATIONS_TO_DISPLAY_DESCRIPTION = "Comma-separated list of relation names to filter the response. Only relations that form a connected chain from the root entity are included. Isolated relations (not reachable from the root) are excluded even if listed. When omitted, all reachable relations are included."; + public static final String INCLUDE_RELATIONS_PROPERTIES_DESCRIPTION = "When true, include property values for related entities. Defaults to false."; public static final String ENDPOINT_GET_ENTITY_GRAPH_FLAT_SUMMARY = "Get entity relationship graph as flat nodes and edges"; public static final String ENDPOINT_GET_ENTITY_GRAPH_FLAT_DESCRIPTION = "Retrieves the entity relationship graph as a flat nodes-and-edges structure, suitable for frontend visualization tools such as React Flow, Vis.js, and Cytoscape."; public static final String RESPONSE_ENTITY_GRAPH_FLAT_SUCCESS = "Flat entity graph successfully retrieved"; + public static final String RESPONSE_INVALID_GRAPH_QUERY = "Invalid graph query parameter value"; public static final String ENTITY_GRAPH_FLAT_NODES_DESCRIPTION = "All entity nodes in the graph"; public static final String ENTITY_GRAPH_FLAT_EDGES_DESCRIPTION = "All directed relation edges in the graph"; public static final String ENTITY_GRAPH_FLAT_NODE_ID_DESCRIPTION = "Unique node identifier composed of templateIdentifier:identifier"; diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/ValidatingPageableArgumentResolver.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/ValidatingPageableArgumentResolver.java new file mode 100644 index 00000000..e9208424 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/ValidatingPageableArgumentResolver.java @@ -0,0 +1,63 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import java.util.Optional; + +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; +import org.springframework.core.MethodParameter; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.ModelAndViewContainer; + +import com.decathlon.idp_core.domain.constant.ValidationMessages; +import com.decathlon.idp_core.domain.exception.search.InvalidSearchQueryException; +import com.decathlon.idp_core.domain.model.search.PaginationCriteria; + +/// Resolves Spring Data `Pageable` arguments and rejects invalid `page` and `size` +/// query parameters with [InvalidSearchQueryException] (HTTP 400). +public class ValidatingPageableArgumentResolver extends PageableHandlerMethodArgumentResolver { + + private static final String PAGE_PARAM = "page"; + private static final String SIZE_PARAM = "size"; + + private final int maxPageSize; + + public ValidatingPageableArgumentResolver(int maxPageSize) { + this.maxPageSize = maxPageSize; + setMaxPageSize(maxPageSize); + } + + @Override + public @NonNull Pageable resolveArgument(@NonNull MethodParameter methodParameter, + @Nullable ModelAndViewContainer mavContainer, @NonNull NativeWebRequest webRequest, + @Nullable WebDataBinderFactory binderFactory) { + validatePageableParameters(webRequest); + return super.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory); + } + + private void validatePageableParameters(NativeWebRequest webRequest) { + Optional page = parseInteger(webRequest, PAGE_PARAM, + ValidationMessages.PAGE_INDEX_NOT_INTEGER); + Optional size = parseInteger(webRequest, SIZE_PARAM, + ValidationMessages.PAGE_SIZE_NOT_INTEGER); + if (page.isEmpty() && size.isEmpty()) { + return; + } + new PaginationCriteria(page.orElse(0), size.orElse(1), null).validateBounds(maxPageSize); + } + + private static Optional parseInteger(NativeWebRequest webRequest, String name, + String errorMessage) { + String raw = webRequest.getParameter(name); + if (raw == null) { + return Optional.empty(); + } + try { + return Optional.of(Integer.parseInt(raw)); + } catch (NumberFormatException _) { + throw new InvalidSearchQueryException(errorMessage); + } + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/WebConfiguration.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/WebConfiguration.java index cab1b62f..cc599401 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/WebConfiguration.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/WebConfiguration.java @@ -1,6 +1,12 @@ package com.decathlon.idp_core.infrastructure.adapters.api.configuration; +import java.util.List; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @@ -14,11 +20,24 @@ /// by making documentation the default landing page for the application. @Configuration +@EnableConfigurationProperties(SearchProperties.class) +@Order(Ordered.HIGHEST_PRECEDENCE) public class WebConfiguration implements WebMvcConfigurer { + private final int maxPageSize; + + public WebConfiguration(SearchProperties searchProperties) { + this.maxPageSize = searchProperties.maxPageSize(); + } + @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addRedirectViewController("/", "swagger-ui/index.html"); } + @Override + public void addArgumentResolvers(List resolvers) { + resolvers.add(new ValidatingPageableArgumentResolver(maxPageSize)); + } + } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/FallbackDenyAllFilterChainConfig.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/FallbackDenyAllFilterChainConfig.java new file mode 100644 index 00000000..50fcd65f --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/FallbackDenyAllFilterChainConfig.java @@ -0,0 +1,67 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration.security.chains; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.NoneNestedConditions; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.SecurityFilterChain; + +/// Fail-closed fallback applied when no authentication mode is enabled. +/// +/// **Security rationale:** every authenticated chain (JWT, OAuth2 login, API key, mock) is +/// conditional on its own `app.security.authentication.*.enabled` flag, and only the public +/// and webhook chains declare a request matcher. Without this fallback, a deployment where +/// all flags are `false` leaves `/api/v1/**` outside every filter chain, which means the API +/// is served without authentication or authorization. +/// +/// **Behaviour:** when none of the modes is enabled, this chain matches every request not +/// already handled by the public or webhook chains and denies it. It is not registered when +/// at least one mode is enabled, because those chains already match any request and Spring +/// Security rejects a chain declared after an any-request chain as unreachable. +@Configuration +@Conditional(FallbackDenyAllFilterChainConfig.NoAuthenticationModeEnabled.class) +public class FallbackDenyAllFilterChainConfig { + + private static final Logger LOGGER = LoggerFactory + .getLogger(FallbackDenyAllFilterChainConfig.class); + + @Bean + @Order(Ordered.LOWEST_PRECEDENCE) + public SecurityFilterChain fallbackDenyAllFilterChain(HttpSecurity http) { + LOGGER.warn( + "No authentication mode is enabled (app.security.authentication.[jwt|oauth2-login|api-key|mock].enabled). " + + "All non-public requests will be denied."); + http.authorizeHttpRequests(auth -> auth.anyRequest().denyAll()); + return http.build(); + } + + /// Matches when none of the authentication modes is switched on. + static class NoAuthenticationModeEnabled extends NoneNestedConditions { + + NoAuthenticationModeEnabled() { + super(ConfigurationPhase.PARSE_CONFIGURATION); + } + + @ConditionalOnProperty(prefix = "app.security.authentication.jwt", name = "enabled", havingValue = "true") + static class JwtEnabled { + } + + @ConditionalOnProperty(prefix = "app.security.authentication.oauth2-login", name = "enabled", havingValue = "true") + static class OAuth2LoginEnabled { + } + + @ConditionalOnProperty(prefix = "app.security.authentication.api-key", name = "enabled", havingValue = "true") + static class ApiKeyEnabled { + } + + @ConditionalOnProperty(prefix = "app.security.authentication.mock", name = "enabled", havingValue = "true") + static class MockEnabled { + } + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/JwtFilterChainConfig.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/JwtFilterChainConfig.java index 9c189c0a..9488ca17 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/JwtFilterChainConfig.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/JwtFilterChainConfig.java @@ -11,6 +11,7 @@ import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.GlobalAuthorizationFilter; import com.decathlon.idp_core.infrastructure.adapters.api.auth.JitProvisioningFilter; @Configuration @@ -18,11 +19,14 @@ public class JwtFilterChainConfig { private final JitProvisioningFilter jitProvisioningFilter; + private final GlobalAuthorizationFilter globalAuthorizationFilter; private final JwtAuthenticationConverter jwtAuthenticationConverter; public JwtFilterChainConfig(JitProvisioningFilter jitProvisioningFilter, + GlobalAuthorizationFilter globalAuthorizationFilter, JwtAuthenticationConverter jwtAuthenticationConverter) { this.jitProvisioningFilter = jitProvisioningFilter; + this.globalAuthorizationFilter = globalAuthorizationFilter; this.jwtAuthenticationConverter = jwtAuthenticationConverter; } @@ -34,7 +38,8 @@ public SecurityFilterChain jwtSecurityFilterChain(HttpSecurity http) { .cors(withDefaults()) .oauth2ResourceServer( oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter))) - .addFilterAfter(jitProvisioningFilter, BearerTokenAuthenticationFilter.class); + .addFilterAfter(jitProvisioningFilter, BearerTokenAuthenticationFilter.class) + .addFilterAfter(globalAuthorizationFilter, JitProvisioningFilter.class); return http.build(); } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/MockFilterChainConfig.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/MockFilterChainConfig.java index 076ae659..d797498d 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/MockFilterChainConfig.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/MockFilterChainConfig.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.time.Instant; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -31,6 +32,7 @@ import org.springframework.web.filter.OncePerRequestFilter; import com.decathlon.idp_core.domain.exception.mock.MockSecurityConfigurationException; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.GlobalAuthorizationFilter; import com.decathlon.idp_core.infrastructure.adapters.api.auth.JitProvisioningFilter; /// Local mock security configuration that mirrors OAuth2/JWT behavior for local development. @@ -50,10 +52,14 @@ @ConditionalOnProperty(prefix = "app.security.authentication.mock", name = "enabled", havingValue = "true") public class MockFilterChainConfig { + public static final String LOCAL_DEVELOPER = "local-developer"; private final JitProvisioningFilter jitProvisioningFilter; + private final GlobalAuthorizationFilter globalAuthorizationFilter; - public MockFilterChainConfig(JitProvisioningFilter jitProvisioningFilter) { + public MockFilterChainConfig(JitProvisioningFilter jitProvisioningFilter, + GlobalAuthorizationFilter globalAuthorizationFilter) { this.jitProvisioningFilter = jitProvisioningFilter; + this.globalAuthorizationFilter = globalAuthorizationFilter; } /// Security filter chain for local mocking with JWT-like behavior. @@ -82,7 +88,9 @@ public SecurityFilterChain mockSecurityFilterChain(HttpSecurity http) { .addFilterBefore(new MockJwtAuthenticationFilter(), AnonymousAuthenticationFilter.class) // 2. Trigger JIT provisioning based on the fake token (tests production // behavior locally) - .addFilterAfter(jitProvisioningFilter, MockJwtAuthenticationFilter.class); + .addFilterAfter(jitProvisioningFilter, MockJwtAuthenticationFilter.class) + // 3. Apply the global authorization policy after the principal is provisioned + .addFilterAfter(globalAuthorizationFilter, JitProvisioningFilter.class); } catch (Exception e) { throw new MockSecurityConfigurationException("Failed to configure mock security filter chain", @@ -102,6 +110,7 @@ public SecurityFilterChain mockSecurityFilterChain(HttpSecurity http) { /// making it available to all downstream components (controllers, services, /// etc.) static class MockJwtAuthenticationFilter extends OncePerRequestFilter { + @Override protected void doFilterInternal(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull FilterChain filterChain) @@ -137,10 +146,16 @@ private Jwt createMockJwt() { Instant expiresAt = now.plusSeconds(3600); Map headers = Map.of("alg", "RS256", "typ", "JWT"); - Map claims = Map.of("sub", "local-developer", "preferred_username", - "local-developer", "name", "Local Developer", "client_id", "client-id", "scope", - "auth read write", "iat", now.getEpochSecond(), "exp", expiresAt.getEpochSecond(), - "email", "developer@local.dev", "user_id", "dev-user-001"); + Map claims = new HashMap<>(); + claims.put("sub", LOCAL_DEVELOPER); + claims.put("preferred_username", LOCAL_DEVELOPER); + claims.put("name", "Local Developer"); + claims.put("client_id", "client-id"); + claims.put("scope", "auth read write"); + claims.put("iat", now.getEpochSecond()); + claims.put("exp", expiresAt.getEpochSecond()); + claims.put("email", "developer@local.dev"); + claims.put("user_id", "dev-user-001"); return new Jwt("mock-token-value", now, expiresAt, headers, claims); } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/OAuth2LoginFilterChainConfig.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/OAuth2LoginFilterChainConfig.java index 22ca3c11..3769ab78 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/OAuth2LoginFilterChainConfig.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/OAuth2LoginFilterChainConfig.java @@ -13,6 +13,7 @@ import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.GlobalAuthorizationFilter; import com.decathlon.idp_core.infrastructure.adapters.api.auth.JitProvisioningFilter; /// Security filter chain for browser-based OAuth2 login. @@ -26,9 +27,12 @@ public class OAuth2LoginFilterChainConfig { private final JitProvisioningFilter jitProvisioningFilter; + private final GlobalAuthorizationFilter globalAuthorizationFilter; - public OAuth2LoginFilterChainConfig(JitProvisioningFilter jitProvisioningFilter) { + public OAuth2LoginFilterChainConfig(JitProvisioningFilter jitProvisioningFilter, + GlobalAuthorizationFilter globalAuthorizationFilter) { this.jitProvisioningFilter = jitProvisioningFilter; + this.globalAuthorizationFilter = globalAuthorizationFilter; } @Bean @@ -40,7 +44,8 @@ public SecurityFilterChain oauth2LoginSecurityFilterChain(HttpSecurity http) { .authorizeHttpRequests(auth -> auth.requestMatchers("/oauth2/**", "/login/**").permitAll() .requestMatchers("/api/v1/**").fullyAuthenticated().anyRequest().authenticated()) .oauth2Login(withDefaults()) - .addFilterAfter(jitProvisioningFilter, OAuth2LoginAuthenticationFilter.class); + .addFilterAfter(jitProvisioningFilter, OAuth2LoginAuthenticationFilter.class) + .addFilterAfter(globalAuthorizationFilter, JitProvisioningFilter.class); return http.build(); } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditController.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditController.java index fbbdabd1..fe6dd043 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditController.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditController.java @@ -20,6 +20,7 @@ import jakarta.validation.constraints.NotBlank; +import org.springframework.http.ProblemDetail; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -29,9 +30,9 @@ import com.decathlon.idp_core.domain.model.entity.EntityAuditInfo; import com.decathlon.idp_core.domain.service.entity.EntityAuditService; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.AuthorizedResource; import com.decathlon.idp_core.infrastructure.adapters.api.dto.out.entity.audit.EntityAuditDtoOut; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity.EntityAuditDtoOutMapper; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -53,6 +54,7 @@ /// keeping the other controller focused on CRUD operations. This follows the Single /// Responsibility Principle. @RestController +@AuthorizedResource("audit") @RequestMapping("/api/v1/audit/") @Tag(name = "Audit", description = "Operations related to audit history") @Validated @@ -77,14 +79,16 @@ public class AuditController { @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_AUDIT_SUCCESS, content = { @Content(array = @ArraySchema(schema = @Schema(implementation = EntityAuditDtoOut.class)))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = "Invalid template or entity identifier", content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) - @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = @Content) - @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = @Content) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = { + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = { + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_TEMPLATE_NOT_FOUND_IDENTIFIER + " or " + RESPONSE_ENTITY_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = INTERNAL_SERVER_ERROR_CODE, description = RESPONSE_UNEXPECTED_SERVER_ERROR, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @GetMapping("entities/{templateIdentifier}/{entityIdentifier}") @ResponseStatus(OK) public List getEntityAuditHistory( diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityController.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityController.java index 15b8a8f4..ef5a5401 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityController.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityController.java @@ -17,7 +17,9 @@ import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.ENDPOINT_POST_SEARCH_SUMMARY; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.ENDPOINT_PUT_ENTITY_DESCRIPTION; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.ENDPOINT_PUT_ENTITY_SUMMARY; +import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.ENTITY_SEARCH_REQUEST_EXAMPLE; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.FORBIDDEN_CODE; +import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.INCLUDE_RELATIONS_PROPERTIES_DESCRIPTION; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.INTERNAL_SERVER_ERROR_CODE; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.NOT_FOUND_CODE; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.NO_CONTENT_CODE; @@ -62,6 +64,8 @@ import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; +import org.springframework.http.MediaType; +import org.springframework.http.ProblemDetail; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -75,6 +79,7 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import com.decathlon.idp_core.domain.constant.SearchConstraints; import com.decathlon.idp_core.domain.model.entity.Entity; import com.decathlon.idp_core.domain.model.entity.EntityFilter; import com.decathlon.idp_core.domain.model.entity.EntityPatch; @@ -89,6 +94,8 @@ import com.decathlon.idp_core.domain.service.entity_graph.EntityGraphService; import com.decathlon.idp_core.domain.service.filter.EntityFilterDslParser; import com.decathlon.idp_core.domain.service.search.SearchFilterParser; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.AuthorizedResource; +import com.decathlon.idp_core.infrastructure.adapters.api.configuration.SearchProperties; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerConfiguration.EntityPageResponse; import com.decathlon.idp_core.infrastructure.adapters.api.dto.in.EntityCreateDtoIn; import com.decathlon.idp_core.infrastructure.adapters.api.dto.in.EntityPatchDtoIn; @@ -99,12 +106,12 @@ import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity.EntityDtoOutFromEntityNodeMapper; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity.EntityDtoOutMapper; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity.SearchFilterMapper; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; @@ -119,6 +126,7 @@ /// - Provides paginated responses for efficient data transfer /// - Maps domain exceptions to appropriate HTTP status codes @RestController +@AuthorizedResource("entity") @RequestMapping("/api/v1/entities") @Tag(name = "Entities Management", description = "Operations related to entity management") @Validated @@ -133,6 +141,7 @@ public class EntityController { private final SearchFilterMapper searchFilterMapper; private final SearchFilterParser searchFilterParser; private final EntityGraphService entityGraphService; + private final SearchProperties searchProperties; // Validation message constants for relations_depth parameter private static final int RELATIONS_DEPTH_MIN = 1; @@ -153,6 +162,7 @@ public class EntityController { /// @param size number of entities per page for response size /// control /// @param templateIdentifier template filter for entity scope limitation + /// @param sort optional sort expression in the format `field,direction` /// @param q optional filter query string (e.g. /// `name:API;property.language=JAVA`) /// @return paginated entity DTOs matching the template and optional filter @@ -160,9 +170,9 @@ public class EntityController { @Operation(summary = ENDPOINT_GET_ENTITIES_SUMMARY, description = ENDPOINT_GET_ENTITIES_PAGINATED_DESCRIPTION) @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITIES_PAGINATED_SUCCESS, content = @Content(schema = @Schema(implementation = EntityPageResponse.class))) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_PAGINATION, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_QUERY, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @Parameter(name = "page", description = PARAM_PAGE_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "integer", defaultValue = "0"))) @Parameter(name = "size", description = PARAM_SIZE_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "integer", defaultValue = "20"))) @Parameter(name = "sort", description = PARAM_SORT_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "string", defaultValue = "identifier,asc"))) @@ -170,13 +180,14 @@ public class EntityController { @ResponseStatus(OK) @GetMapping("/{templateIdentifier}") public Page getEntities(@RequestParam(defaultValue = "0") int page, - @RequestParam(defaultValue = "20") int size, @PathVariable String templateIdentifier, - @RequestParam(required = false) String q) { - Pageable pageable = PageRequest.of(page, size); + @RequestParam(required = false) Integer size, @PathVariable String templateIdentifier, + @RequestParam(required = false) String sort, @RequestParam(required = false) String q) { + PaginationCriteria paginationCriteria = new PaginationCriteria(page, resolvePageSize(size), + sort); EntityFilter filter = entityFilterDslParser.parse(q); // Single transaction: pagination + batch relation fetch in one DB round trip - Page graphNodes = entityGraphService.getEntityGraphPageByTemplate(pageable, - templateIdentifier, filter, 1); + Page graphNodes = entityGraphService.getEntityGraphPageByTemplate( + paginationCriteria, templateIdentifier, filter, 1, searchProperties.maxPageSize()); return entityDtoOutFromEntityNodeMapper.toPageDto(graphNodes, templateIdentifier, 1); } @@ -206,29 +217,33 @@ public Page getEntities(@RequestParam(defaultValue = "0") int page * to 1) * @param relationsToDisplay * optional set of relation names to include; omit to include all + * @param includeRelationsProperties + * whether to include property values for related entities * @return entity DTO with full property and relationship data */ @Operation(summary = ENDPOINT_GET_ENTITY_BY_IDENTIFIER_SUMMARY, description = ENDPOINT_GET_ENTITY_BY_IDENTIFIER_DESCRIPTION) @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_FOUND, content = { @Content(schema = @Schema(implementation = EntityDtoOut.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @Parameter(name = "relations_depth", description = RELATIONS_DEPTH_DESCRIPTION, in = ParameterIn.QUERY, schema = @Schema(type = "integer", defaultValue = "1", minimum = "1", maximum = "6")) @Parameter(name = "relations_to_display", description = RELATIONS_TO_DISPLAY_DESCRIPTION, in = ParameterIn.QUERY, schema = @Schema(type = "array")) + @Parameter(name = "include_relations_properties", description = INCLUDE_RELATIONS_PROPERTIES_DESCRIPTION, in = ParameterIn.QUERY, schema = @Schema(type = "boolean", defaultValue = "false")) @GetMapping("/{templateIdentifier}/{entityIdentifier}") @ResponseStatus(OK) public EntityDtoOut getEntity(@PathVariable String templateIdentifier, @PathVariable String entityIdentifier, @Min(value = RELATIONS_DEPTH_MIN, message = RELATIONS_DEPTH_MIN_MESSAGE) @Max(value = RELATIONS_DEPTH_MAX, message = RELATIONS_DEPTH_MAX_MESSAGE) @RequestParam(name = "relations_depth", required = false, defaultValue = "1") Integer relationsDepth, - @RequestParam(name = "relations_to_display", required = false) Set relationsToDisplay) { + @RequestParam(name = "relations_to_display", required = false) Set relationsToDisplay, + @RequestParam(name = "include_relations_properties", defaultValue = "false") boolean includeRelationsProperties) { EntityGraphNode entityGraphNode = entityGraphService.getEntityGraph(templateIdentifier, entityIdentifier, - new EntityGraphQueryOptions(relationsDepth, false, true, + new EntityGraphQueryOptions(relationsDepth, includeRelationsProperties, true, relationsToDisplay == null ? Set.of() : relationsToDisplay, Set.of(), EntityGraphTraversalMode.DIRECT_LINEAGE)); return entityDtoOutFromEntityNodeMapper.toDto(entityGraphNode, templateIdentifier, - relationsDepth); + relationsDepth, includeRelationsProperties); } /// Creates a new entity for the specified template with validation. @@ -246,15 +261,17 @@ public EntityDtoOut getEntity(@PathVariable String templateIdentifier, @ApiResponse(responseCode = CREATED_CODE, description = RESPONSE_ENTITY_CREATED, content = { @Content(schema = @Schema(implementation = EntityDtoOut.class))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_ENTITY_DATA, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) - @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = @Content) - @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = @Content) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = { + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = { + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = CONFLICT_CODE, description = RESPONSE_ENTITY_CONFLICT, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_TEMPLATE_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = INTERNAL_SERVER_ERROR_CODE, description = RESPONSE_UNEXPECTED_SERVER_ERROR, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PostMapping("/{templateIdentifier}") @ResponseStatus(CREATED) public EntityDtoOut createEntity(@NotBlank @PathVariable String templateIdentifier, @@ -283,13 +300,15 @@ public EntityDtoOut createEntity(@NotBlank @PathVariable String templateIdentifi @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_UPDATED, content = { @Content(schema = @Schema(implementation = EntityDtoOut.class))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_ENTITY_DATA, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) - @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = @Content) - @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = @Content) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = { + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = { + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = INTERNAL_SERVER_ERROR_CODE, description = RESPONSE_UNEXPECTED_SERVER_ERROR, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PutMapping("/{templateIdentifier}/{entityIdentifier}") @ResponseStatus(OK) public EntityDtoOut updateEntity(@NotBlank @PathVariable String templateIdentifier, @@ -310,13 +329,15 @@ public EntityDtoOut updateEntity(@NotBlank @PathVariable String templateIdentifi @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_UPDATED, content = { @Content(schema = @Schema(implementation = EntityDtoOut.class))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_ENTITY_DATA, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) - @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = @Content) - @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = @Content) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = { + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = { + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = INTERNAL_SERVER_ERROR_CODE, description = RESPONSE_UNEXPECTED_SERVER_ERROR, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PatchMapping("/{templateIdentifier}/{entityIdentifier}") @ResponseStatus(OK) public EntityDtoOut patchEntity(@NotBlank @PathVariable String templateIdentifier, @@ -341,15 +362,17 @@ public EntityDtoOut patchEntity(@NotBlank @PathVariable String templateIdentifie @Operation(summary = ENDPOINT_DELETE_ENTITY_SUMMARY, description = ENDPOINT_DELETE_ENTITY_DESCRIPTION) @ApiResponse(responseCode = NO_CONTENT_CODE, description = RESPONSE_ENTITY_DELETED) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_ENTITY_DATA, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) - @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = @Content) - @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = @Content) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = { + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) + @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = { + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = CONFLICT_CODE, description = RESPONSE_ENTITY_RELATION_CONFLICT, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = INTERNAL_SERVER_ERROR_CODE, description = RESPONSE_UNEXPECTED_SERVER_ERROR, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @DeleteMapping("/{templateIdentifier}/{entityIdentifier}") @ResponseStatus(NO_CONTENT) public void deleteEntity(@NotBlank @PathVariable String templateIdentifier, @@ -367,20 +390,22 @@ public void deleteEntity(@NotBlank @PathVariable String templateIdentifier, /// @param searchRequest the search request body with filter, page, size, and /// sort /// @return paginated entity DTOs matching the filter - @Operation(summary = ENDPOINT_POST_SEARCH_SUMMARY, description = ENDPOINT_POST_SEARCH_DESCRIPTION) + @Operation(summary = ENDPOINT_POST_SEARCH_SUMMARY, description = ENDPOINT_POST_SEARCH_DESCRIPTION, requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(mediaType = "application/json", examples = @ExampleObject(name = "Entity search", value = ENTITY_SEARCH_REQUEST_EXAMPLE)))) @ApiResponse(responseCode = OK_CODE, description = RESPONSE_SEARCH_SUCCESS, content = @Content(schema = @Schema(implementation = EntityPageResponse.class))) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_SEARCH_QUERY, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PostMapping("/search") + @AuthorizedResource(value = "entity_search", readOnly = true) @ResponseStatus(OK) public Page searchEntities(@RequestBody EntitySearchRequestDtoIn searchRequest) { RawSearchFilterNode rawFilter = searchFilterMapper.toRaw(searchRequest.filter()); SearchFilterNode filter = searchFilterParser.parse(rawFilter); PaginationCriteria paginationCriteria = new PaginationCriteria(searchRequest.page(), - searchRequest.size(), searchRequest.sort()); + resolvePageSize(searchRequest.size()), searchRequest.sort()); + paginationCriteria.validateBounds(searchProperties.maxPageSize()); PaginatedResult result = entityService.searchEntities(filter, searchRequest.query(), - paginationCriteria); + paginationCriteria, searchProperties.maxPageSize()); Page page = toPageResponse(result.content(), paginationCriteria, result.totalElements()); return entityDtoOutMapper.fromEntitiesSearchPageToDtoPage(page); @@ -391,4 +416,12 @@ private Page toPageResponse(List content, PaginationCriteria criteria, Pageable pageable = PageRequest.of(criteria.page(), criteria.size()); return new PageImpl<>(content, pageable, totalElements); } + + /// Uses the requested size when present; otherwise the default size, capped at + /// the configured maximum so that omitting `size` never fails validation. + private int resolvePageSize(Integer requestedSize) { + return requestedSize != null + ? requestedSize + : Math.min(SearchConstraints.DEFAULT_PAGE_SIZE, searchProperties.maxPageSize()); + } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingController.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingController.java index e6eae749..eafefa5b 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingController.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingController.java @@ -3,17 +3,25 @@ import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.*; import static org.springframework.http.HttpStatus.*; +import java.util.Optional; + +import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; +import org.springframework.http.ProblemDetail; import org.springframework.web.bind.annotation.*; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; import com.decathlon.idp_core.domain.model.entity_mapping.DryRunResult; import com.decathlon.idp_core.domain.model.entity_mapping.EntityDynamicMapping; import com.decathlon.idp_core.domain.service.entity_dynamic_mapping.EntityDynamicMappingDryRunService; import com.decathlon.idp_core.domain.service.entity_dynamic_mapping.EntityDynamicMappingService; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.AuthorizedResource; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.RequestAuthorizer; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerConfiguration; import com.decathlon.idp_core.infrastructure.adapters.api.dto.in.EntityDynamicMappingCreateDtoIn; import com.decathlon.idp_core.infrastructure.adapters.api.dto.in.EntityDynamicMappingDryRunDtoIn; @@ -23,7 +31,6 @@ import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity_dynamic_mapping.EntityDynamicMappingDryRunDtoInMapper; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity_dynamic_mapping.EntityDynamicMappingDryRunDtoOutMapper; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity_dynamic_mapping.EntityDynamicMappingMapper; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -35,6 +42,7 @@ import lombok.RequiredArgsConstructor; @RestController +@AuthorizedResource("entity_dynamic_mapping") @RequiredArgsConstructor @RequestMapping("/api/v1/entity_dynamic_mappings") @Tag(name = "Entity dynamic mapping", description = "Operations related to entity dynamic mapping management") @@ -45,6 +53,7 @@ public class EntityDynamicMappingController { private final EntityDynamicMappingDryRunService dynamicMappingDryRunService; private final EntityDynamicMappingDryRunDtoOutMapper entityDynamicMappingDryRunDtoOutMapper; private final EntityDynamicMappingDryRunDtoInMapper entityDynamicMappingDryRunDtoInMapper; + private final RequestAuthorizer requestAuthorizer; @Operation(summary = ENDPOINT_POST_ENTITY_DYNAMIC_MAPPING_SUMMARY, description = ENDPOINT_POST_ENTITY_DYNAMIC_MAPPING_DESCRIPTION) @ApiResponse(responseCode = CREATED_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_CREATED) @@ -53,7 +62,11 @@ public class EntityDynamicMappingController { @PostMapping @ResponseStatus(CREATED) public EntityDynamicMappingDtoOut createDynamicMapping( - @Valid @RequestBody EntityDynamicMappingCreateDtoIn inboundWebhookMappingDtoIn) { + @Valid @RequestBody EntityDynamicMappingCreateDtoIn inboundWebhookMappingDtoIn, + HttpServletRequest request) { + authorizePrincipalMapping(request, AuthorizationAction.CREATE, + inboundWebhookMappingDtoIn.identifier(), + inboundWebhookMappingDtoIn.entityTemplateIdentifier()); EntityDynamicMapping entityDynamicMapping = dynamicMappingService .createEntityDynamicMapping(dynamicMappingMapper.toDomain(inboundWebhookMappingDtoIn)); return dynamicMappingMapper.fromEntityMappingToDto(entityDynamicMapping); @@ -62,7 +75,7 @@ public EntityDynamicMappingDtoOut createDynamicMapping( @Operation(summary = ENDPOINT_GET_ENTITY_DYNAMIC_MAPPING_PAGINATED_SUMMARY, description = ENDPOINT_GET_ENTITY_DYNAMIC_MAPPING_PAGINATED_DESCRIPTION) @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_PAGINATED_SUCCESS, content = @Content(schema = @Schema(implementation = SwaggerConfiguration.EntityDynamicMappingPageResponse.class))) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_PAGINATION, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @Parameter(name = "page", description = PARAM_PAGE_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "integer", defaultValue = "0"))) @Parameter(name = "size", description = PARAM_SIZE_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "integer", defaultValue = "20"))) @Parameter(name = "sort", description = PARAM_SORT_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "string", defaultValue = "identifier,asc"))) @@ -77,10 +90,14 @@ public Page getEntityDynamicMappingPaginated( @Operation(summary = ENDPOINT_DELETE_ENTITY_DYNAMIC_MAPPING_SUMMARY, description = ENDPOINT_DELETE_ENTITY_DYNAMIC_MAPPING_DESCRIPTION) @ApiResponse(responseCode = NO_CONTENT_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_DELETED) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ResponseStatus(NO_CONTENT) @DeleteMapping("/{identifier}") - public void deleteEntityDynamicMapping(@PathVariable String identifier) { + public void deleteEntityDynamicMapping(@PathVariable String identifier, + HttpServletRequest request) { + var mapping = dynamicMappingService.getEntityDynamicMapping(identifier); + authorizePrincipalMapping(request, AuthorizationAction.DELETE, identifier, + mapping.entityTemplateIdentifier()); dynamicMappingService.deleteEntityDynamicMapping(identifier); } @@ -88,7 +105,7 @@ public void deleteEntityDynamicMapping(@PathVariable String identifier) { @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_FOUND, content = { @Content(schema = @Schema(implementation = EntityDynamicMappingDtoOut.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @GetMapping("/{identifier}") @ResponseStatus(OK) public EntityDynamicMappingDtoOut getEntityDynamicMappingByIdentifier( @@ -102,30 +119,46 @@ public EntityDynamicMappingDtoOut getEntityDynamicMappingByIdentifier( @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_UPDATED, content = { @Content(schema = @Schema(implementation = EntityDynamicMappingDtoOut.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_UPDATE_INVALID_TEMPLATE, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = CONFLICT_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_UPDATE_CONFLICT, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PutMapping("/{identifier}") @ResponseStatus(OK) public EntityDynamicMappingDtoOut updateEntityDynamicMapping(@PathVariable String identifier, - @Valid @RequestBody EntityDynamicMappingUpdateDtoIn entityDynamicMappingDtoIn) { + @Valid @RequestBody EntityDynamicMappingUpdateDtoIn entityDynamicMappingDtoIn, + HttpServletRequest request) { + var existingMapping = dynamicMappingService.getEntityDynamicMapping(identifier); + authorizePrincipalMapping(request, AuthorizationAction.UPDATE, identifier, + existingMapping.entityTemplateIdentifier()); + authorizePrincipalMapping(request, AuthorizationAction.UPDATE, identifier, + entityDynamicMappingDtoIn.entityTemplateIdentifier()); return dynamicMappingMapper .fromEntityMappingToDto(dynamicMappingService.updateEntityDynamicMapping(identifier, dynamicMappingMapper.toDomainForUpdate(identifier, entityDynamicMappingDtoIn))); } + private void authorizePrincipalMapping(HttpServletRequest request, AuthorizationAction action, + String mappingIdentifier, String targetTemplateIdentifier) { + if (AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER.equals(targetTemplateIdentifier)) { + requestAuthorizer.authorize(request, action, + new AuthorizationResource(AuthorizationResource.ENTITY_DYNAMIC_MAPPING, + Optional.of(mappingIdentifier), Optional.of(targetTemplateIdentifier))); + } + } + @Operation(summary = ENDPOINT_POST_ENTITY_DYNAMIC_MAPPING_DRY_RUN_SUMMARY, description = ENDPOINT_POST_ENTITY_DYNAMIC_MAPPING_DRY_RUN_DESCRIPTION) @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_DRY_RUN_SUCCESS, content = { @Content(schema = @Schema(implementation = EntityDynamicMappingDryRunDtoOut.class))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_DATA, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_DRY_RUN_TEMPLATE_NOT_FOUND, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = UNPROCESSABLE_CONTENT_CODE, description = RESPONSE_ENTITY_DYNAMIC_MAPPING_DRY_RUN_VALIDATION_ERROR, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PostMapping("/dry-run") + @AuthorizedResource(value = "entity_dynamic_mapping_dry_run", readOnly = true) @ResponseStatus(OK) public EntityDynamicMappingDryRunDtoOut executeDryRun( @Valid @RequestBody EntityDynamicMappingDryRunDtoIn dryRunRequest) { diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityGraphController.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityGraphController.java index 17e896fe..fd1946a8 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityGraphController.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityGraphController.java @@ -1,5 +1,6 @@ package com.decathlon.idp_core.infrastructure.adapters.api.controller; +import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.BAD_REQUEST_CODE; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.ENDPOINT_GET_ENTITY_GRAPH_FLAT_DESCRIPTION; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.ENDPOINT_GET_ENTITY_GRAPH_FLAT_SUMMARY; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.NOT_FOUND_CODE; @@ -11,6 +12,7 @@ import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.PARAM_TRAVERSAL_MODE_DESCRIPTION; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.RESPONSE_ENTITY_GRAPH_FLAT_SUCCESS; import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.RESPONSE_ENTITY_NOT_FOUND_IDENTIFIER; +import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.RESPONSE_INVALID_GRAPH_QUERY; import static org.springframework.http.HttpStatus.OK; import java.util.List; @@ -18,6 +20,7 @@ import jakarta.validation.constraints.NotBlank; +import org.springframework.http.ProblemDetail; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -30,9 +33,9 @@ import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphQueryOptions; import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphTraversalMode; import com.decathlon.idp_core.domain.service.entity_graph.EntityGraphService; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.AuthorizedResource; import com.decathlon.idp_core.infrastructure.adapters.api.dto.out.entity_graph.EntityGraphFlatDtoOut; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity_graph.EntityGraphFlatDtoOutMapper; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -48,6 +51,7 @@ /// starting from a specified entity, suitable for frontend visualization tools /// such as React Flow, Vis.js, and Cytoscape. @RestController +@AuthorizedResource("entity") @RequestMapping("/api/v1/entities") @RequiredArgsConstructor @Validated @@ -77,7 +81,8 @@ public class EntityGraphController { @ResponseStatus(OK) @Operation(summary = ENDPOINT_GET_ENTITY_GRAPH_FLAT_SUMMARY, description = ENDPOINT_GET_ENTITY_GRAPH_FLAT_DESCRIPTION, responses = { @ApiResponse(responseCode = OK_CODE, description = RESPONSE_ENTITY_GRAPH_FLAT_SUCCESS, content = @Content(schema = @Schema(implementation = EntityGraphFlatDtoOut.class))), - @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_NOT_FOUND_IDENTIFIER, content = @Content(schema = @Schema(implementation = ErrorResponse.class)))}) + @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_GRAPH_QUERY, content = @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))), + @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_ENTITY_NOT_FOUND_IDENTIFIER, content = @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class)))}) public EntityGraphFlatDtoOut getEntityGraph(@PathVariable @NotBlank String templateIdentifier, @PathVariable @NotBlank String entityIdentifier, @Parameter(description = PARAM_DEPTH_DESCRIPTION) @RequestParam(defaultValue = "1") int depth, diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateController.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateController.java index bd32c898..dd98ba88 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateController.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateController.java @@ -29,11 +29,16 @@ import static org.springframework.http.HttpStatus.NO_CONTENT; import static org.springframework.http.HttpStatus.OK; +import java.util.Optional; + +import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ProblemDetail; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -44,15 +49,18 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; import com.decathlon.idp_core.domain.model.entity_template.EntityTemplate; import com.decathlon.idp_core.domain.service.entity_template.EntityTemplateService; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.AuthorizedResource; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.RequestAuthorizer; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerConfiguration.TemplatePageResponse; import com.decathlon.idp_core.infrastructure.adapters.api.dto.in.EntityTemplateCreateDtoIn; import com.decathlon.idp_core.infrastructure.adapters.api.dto.in.EntityTemplateUpdateDtoIn; import com.decathlon.idp_core.infrastructure.adapters.api.dto.out.entity_template.EntityTemplateDtoOut; import com.decathlon.idp_core.infrastructure.adapters.api.handler.ApiExceptionHandler; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity_template.EntityTemplateMapper; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -81,6 +89,7 @@ /// paginated listing, identifier-based lookup, creation with uniqueness validation, /// updates with conflict resolution, and safe deletion with referential checks. @RestController +@AuthorizedResource("entity_template") @RequiredArgsConstructor @RequestMapping("/api/v1/entity-templates") @Tag(name = "Entities Templates Management", description = "Operations related to entity template management") @@ -88,6 +97,7 @@ public class EntityTemplateController { private final EntityTemplateService entityTemplateService; private final EntityTemplateMapper templateMapper; + private final RequestAuthorizer requestAuthorizer; /// Retrieves paginated entity templates for administrative interfaces. /// @@ -98,7 +108,7 @@ public class EntityTemplateController { @Operation(summary = ENDPOINT_GET_TEMPLATES_PAGINATED_SUMMARY, description = ENDPOINT_GET_TEMPLATES_PAGINATED_DESCRIPTION) @ApiResponse(responseCode = OK_CODE, description = RESPONSE_TEMPLATES_PAGINATED_SUCCESS, content = @Content(schema = @Schema(implementation = TemplatePageResponse.class))) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_PAGINATION, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @Parameter(name = "page", description = PARAM_PAGE_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "integer", defaultValue = "0"))) @Parameter(name = "size", description = PARAM_SIZE_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "integer", defaultValue = "20"))) @Parameter(name = "sort", description = PARAM_SORT_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "string", defaultValue = "identifier,asc"))) @@ -119,7 +129,7 @@ public Page getTemplatesPaginated( @ApiResponse(responseCode = OK_CODE, description = RESPONSE_TEMPLATE_FOUND, content = { @Content(schema = @Schema(implementation = EntityTemplateDtoOut.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_TEMPLATE_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @GetMapping("/{identifier}") @ResponseStatus(OK) public EntityTemplateDtoOut getTemplateByIdentifier(@PathVariable String identifier) { @@ -137,11 +147,18 @@ public EntityTemplateDtoOut getTemplateByIdentifier(@PathVariable String identif @ApiResponse(responseCode = CREATED_CODE, description = RESPONSE_TEMPLATE_CREATED, content = { @Content(schema = @Schema(implementation = EntityTemplateDtoOut.class))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_TEMPLATE_DATA, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PostMapping @ResponseStatus(CREATED) public EntityTemplateDtoOut createTemplate( - @Valid @RequestBody EntityTemplateCreateDtoIn entityTemplateCreateDtoIn) { + @Valid @RequestBody EntityTemplateCreateDtoIn entityTemplateCreateDtoIn, + HttpServletRequest request) { + if (AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER + .equals(entityTemplateCreateDtoIn.getIdentifier())) { + requestAuthorizer.authorize(request, AuthorizationAction.CREATE, + new AuthorizationResource(AuthorizationResource.ENTITY_TEMPLATE, + Optional.of(entityTemplateCreateDtoIn.getIdentifier()), Optional.empty())); + } EntityTemplate entityTemplate = entityTemplateService .createEntityTemplate(templateMapper.fromDtoToEntityTemplate(entityTemplateCreateDtoIn)); return templateMapper.fromEntityTemplatetoDto(entityTemplate); @@ -157,7 +174,7 @@ public EntityTemplateDtoOut createTemplate( @ApiResponse(responseCode = OK_CODE, description = RESPONSE_TEMPLATE_UPDATED, content = { @Content(schema = @Schema(implementation = EntityTemplateDtoOut.class))}) @ApiResponse(responseCode = "404", description = RESPONSE_TEMPLATE_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PutMapping("/{identifier}") public EntityTemplateDtoOut updateTemplate(@PathVariable(name = "identifier") String identifier, @RequestBody @Valid EntityTemplateUpdateDtoIn entityTemplateUpdateDtoIn) { @@ -176,9 +193,9 @@ public EntityTemplateDtoOut updateTemplate(@PathVariable(name = "identifier") St @Operation(summary = ENDPOINT_DELETE_TEMPLATE_SUMMARY, description = ENDPOINT_DELETE_TEMPLATE_DESCRIPTION) @ApiResponse(responseCode = NO_CONTENT_CODE, description = RESPONSE_TEMPLATE_DELETED) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = "Cannot delete template: it is a target for other relations", content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_TEMPLATE_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ResponseStatus(NO_CONTENT) @DeleteMapping("/{identifier}") public void deleteTemplate(@PathVariable String identifier) { diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/InboundWebhookConfigurationController.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/InboundWebhookConfigurationController.java index 1405f0a8..2961b38a 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/InboundWebhookConfigurationController.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/InboundWebhookConfigurationController.java @@ -8,16 +8,18 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; +import org.springframework.http.ProblemDetail; import org.springframework.web.bind.annotation.*; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; import com.decathlon.idp_core.domain.model.inbound_connectors.webhook.WebhookConnector; import com.decathlon.idp_core.domain.service.webhook.WebhookConnectorService; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.AuthorizedResource; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerConfiguration; import com.decathlon.idp_core.infrastructure.adapters.api.dto.in.InboundWebhookCreateDtoIn; import com.decathlon.idp_core.infrastructure.adapters.api.dto.in.InboundWebhookUpdateDtoIn; import com.decathlon.idp_core.infrastructure.adapters.api.dto.out.webhook.InboundWebhookDtoOut; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.connector.webhook.InboundWebhookMapper; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -30,6 +32,7 @@ /// REST controller exposing inbound webhook configuration management endpoints. @RestController +@AuthorizedResource(AuthorizationResource.INBOUND_WEBHOOK_CONFIGURATION) @RequiredArgsConstructor @RequestMapping("/api/v1/inbound_webhooks") @Tag(name = "Inbound Webhook Management", description = "Operations for managing inbound webhook connector configurations") @@ -59,7 +62,7 @@ public InboundWebhookDtoOut createInboundWebhook( @Operation(summary = ENDPOINT_GET_WEBHOOK_CONNECTOR_PAGINATED_SUMMARY, description = ENDPOINT_GET_WEBHOOK_CONNECTOR_PAGINATED_DESCRIPTION) @ApiResponse(responseCode = OK_CODE, description = RESPONSE_WEBHOOK_CONNECTOR_PAGINATED_SUCCESS, content = @Content(schema = @Schema(implementation = SwaggerConfiguration.WebhookConnectorPageResponse.class))) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = RESPONSE_INVALID_PAGINATION, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @Parameter(name = "page", description = PARAM_PAGE_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "integer", defaultValue = "0"))) @Parameter(name = "size", description = PARAM_SIZE_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "integer", defaultValue = "20"))) @Parameter(name = "sort", description = PARAM_SORT_DESCRIPTION, in = ParameterIn.QUERY, content = @Content(schema = @Schema(type = "string", defaultValue = "identifier,asc"))) @@ -74,7 +77,7 @@ public Page getWebhooksPaginated( @Operation(summary = ENDPOINT_DELETE_WEBHOOK_CONNECTOR_SUMMARY, description = ENDPOINT_DELETE_WEBHOOK_CONNECTOR_DESCRIPTION) @ApiResponse(responseCode = NO_CONTENT_CODE, description = RESPONSE_WEBHOOK_CONNECTOR_DELETED) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_WEBHOOK_CONNECTOR_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ResponseStatus(NO_CONTENT) @DeleteMapping("/{identifier}") public void deleteWebhookConnector(@PathVariable String identifier) { @@ -85,7 +88,7 @@ public void deleteWebhookConnector(@PathVariable String identifier) { @ApiResponse(responseCode = OK_CODE, description = RESPONSE_WEBHOOK_CONNECTOR_FOUND, content = { @Content(schema = @Schema(implementation = InboundWebhookDtoOut.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_WEBHOOK_CONNECTOR_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @GetMapping("/{identifier}") @ResponseStatus(OK) public InboundWebhookDtoOut getWebhookConnectorByIdentifier(@PathVariable String identifier) { @@ -97,11 +100,11 @@ public InboundWebhookDtoOut getWebhookConnectorByIdentifier(@PathVariable String @ApiResponse(responseCode = OK_CODE, description = RESPONSE_WEBHOOK_CONNECTOR_UPDATED, content = { @Content(schema = @Schema(implementation = InboundWebhookDtoOut.class))}) @ApiResponse(responseCode = NOT_FOUND_CODE, description = RESPONSE_WEBHOOK_CONNECTOR_NOT_FOUND_IDENTIFIER, content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = BAD_REQUEST_CODE, description = "Invalid request payload", content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @ApiResponse(responseCode = CONFLICT_CODE, description = "Webhook connector name already exists", content = { - @Content(schema = @Schema(implementation = ErrorResponse.class))}) + @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))}) @PutMapping("/{identifier}") @ResponseStatus(OK) public InboundWebhookDtoOut putWebhookConnector(@PathVariable String identifier, diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/PrincipalController.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/PrincipalController.java index 8faf06d5..b917f921 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/PrincipalController.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/PrincipalController.java @@ -10,6 +10,7 @@ import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.UNAUTHORIZED_CODE; import static org.springframework.http.HttpStatus.OK; +import org.springframework.http.ProblemDetail; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @@ -17,13 +18,14 @@ import org.springframework.web.bind.annotation.RestController; import com.decathlon.idp_core.domain.exception.principal.PrincipalNotFoundException; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; import com.decathlon.idp_core.domain.model.entity.Entity; import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; import com.decathlon.idp_core.domain.service.principal.PrincipalProvisioningService; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.AuthorizedResource; import com.decathlon.idp_core.infrastructure.adapters.api.dto.out.entity.EntityDtoOut; import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity.EntityDtoOutMapper; import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; @@ -43,6 +45,7 @@ /// **Design rationale:** Separates principal self-service from general entity /// management. Uses dedicated `/principals/me` path to clearly signal intent. @RestController +@AuthorizedResource("principal") @RequestMapping("/api/v1/entities/principals") @RequiredArgsConstructor @Tag(name = "Principals", description = "Principal identity and profile management") @@ -53,6 +56,7 @@ public class PrincipalController { private final EntityDtoOutMapper entityDtoOutMapper; @GetMapping("/me") + @AuthorizedResource(AuthorizationResource.PRINCIPAL_SELF) @ResponseStatus(OK) @Operation(summary = "Get current authenticated principal", description = """ Returns the Principal entity of the currently authenticated actor (human or service account). @@ -71,14 +75,14 @@ Returns the Principal entity of the currently authenticated actor (human or serv - Service account validation """) @ApiResponse(responseCode = OK_CODE, description = "Principal entity retrieved successfully", content = @Content(mediaType = "application/json", schema = @Schema(implementation = EntityDtoOut.class))) - @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))) - @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))) - @ApiResponse(responseCode = NOT_FOUND_CODE, description = "Principal not found in catalog (JIT provisioning may have failed)", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))) - @ApiResponse(responseCode = INTERNAL_SERVER_ERROR_CODE, description = RESPONSE_UNEXPECTED_SERVER_ERROR, content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))) + @ApiResponse(responseCode = UNAUTHORIZED_CODE, description = RESPONSE_UNAUTHORIZED, content = @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))) + @ApiResponse(responseCode = FORBIDDEN_CODE, description = RESPONSE_INSUFFICIENT_RIGHTS, content = @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))) + @ApiResponse(responseCode = NOT_FOUND_CODE, description = "Principal not found in catalog (JIT provisioning may have failed)", content = @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))) + @ApiResponse(responseCode = INTERNAL_SERVER_ERROR_CODE, description = RESPONSE_UNEXPECTED_SERVER_ERROR, content = @Content(mediaType = org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class))) public EntityDtoOut getCurrentPrincipal(Authentication authentication) { PrincipalInfo principalInfo = principalExtractor.extractPrincipalInfo(authentication); - Entity principal = provisioningService.getPrincipal(principalInfo.identifier()) + Entity principal = provisioningService.findPrincipal(principalInfo.identifier()) .orElseThrow(() -> new PrincipalNotFoundException(principalInfo.identifier())); return entityDtoOutMapper.fromEntity(principal); diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/in/EntitySearchRequestDtoIn.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/in/EntitySearchRequestDtoIn.java index 945e83a7..311a3b0d 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/in/EntitySearchRequestDtoIn.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/in/EntitySearchRequestDtoIn.java @@ -28,7 +28,7 @@ /// }, /// "page": 0, /// "size": 20, -/// "sort": "identifier:asc" +/// "sort": "identifier,asc" /// } /// ``` @Schema(description = SwaggerDescription.SCHEMA_ENTITY_SEARCH_REQUEST_IN) @@ -42,11 +42,8 @@ public record EntitySearchRequestDtoIn( @Schema(description = SwaggerDescription.PARAM_SIZE_DESCRIPTION, defaultValue = "20", example = "20") Integer size, - @Schema(description = SwaggerDescription.PARAM_SORT_DESCRIPTION, example = "identifier:asc") String sort) { + @Schema(description = SwaggerDescription.PARAM_SORT_DESCRIPTION, example = "identifier,asc") String sort) { public EntitySearchRequestDtoIn { - if (size == null) { - size = 20; - } if (page == null) { page = 0; } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/in/InboundWebhookSecurityContractDtoIn.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/in/InboundWebhookSecurityContractDtoIn.java index ee59b552..ed0a1462 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/in/InboundWebhookSecurityContractDtoIn.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/in/InboundWebhookSecurityContractDtoIn.java @@ -1,17 +1,12 @@ package com.decathlon.idp_core.infrastructure.adapters.api.dto.in; -import static com.decathlon.idp_core.domain.constant.ValidationMessages.WEBHOOK_CONNECTOR_SECURITY_CONFIG_MANDATORY; -import static com.decathlon.idp_core.domain.constant.ValidationMessages.WEBHOOK_CONNECTOR_SECURITY_TYPE_MANDATORY; - import java.util.Map; -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.NotNull; - /// Security contract request payload represented as `{ type, config }`. -public record InboundWebhookSecurityContractDtoIn( - @NotBlank(message = WEBHOOK_CONNECTOR_SECURITY_TYPE_MANDATORY) String type, - @NotNull(message = WEBHOOK_CONNECTOR_SECURITY_CONFIG_MANDATORY) Map config) { +/// +/// `type` may be omitted for disabled connectors, which the mapper interprets as +/// `NONE`. `config` is optional for `NONE` and mandatory for other strategies. +public record InboundWebhookSecurityContractDtoIn(String type, Map config) { public InboundWebhookSecurityContractDtoIn { config = config != null ? Map.copyOf(config) : null; diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/out/entity/EntitySummaryDto.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/out/entity/EntitySummaryDto.java index d8147d29..8b1366c6 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/out/entity/EntitySummaryDto.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/dto/out/entity/EntitySummaryDto.java @@ -1,8 +1,16 @@ package com.decathlon.idp_core.infrastructure.adapters.api.dto.out.entity; +import static com.decathlon.idp_core.infrastructure.adapters.api.configuration.SwaggerDescription.FIELD_RELATION_ENTITY_PROPERTIES; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; +import io.swagger.v3.oas.annotations.media.Schema; + /** * Represents a summary of an entity for use in collections and relations. * @@ -15,5 +23,15 @@ public record EntitySummaryDto(String identifier, String name, - String templateIdentifier) { + String templateIdentifier, + + @JsonInclude(Include.NON_NULL) @Schema(description = FIELD_RELATION_ENTITY_PROPERTIES) Map properties) { + + public EntitySummaryDto(String identifier, String name, String templateIdentifier) { + this(identifier, name, templateIdentifier, null); + } + + public EntitySummaryDto { + properties = properties == null ? null : Map.copyOf(properties); + } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/exception/MissingPrincipalIdentifierException.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/exception/MissingPrincipalIdentifierException.java new file mode 100644 index 00000000..5200e2bc --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/exception/MissingPrincipalIdentifierException.java @@ -0,0 +1,22 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.exception; + +/// Indicates that an authenticated principal is missing its configured identifier claim. +public class MissingPrincipalIdentifierException extends RuntimeException { + + private final String claimName; + + /// Creates a failure for a missing or blank principal identifier. + /// + /// @param claimName configured claim expected to identify the principal + public MissingPrincipalIdentifierException(String claimName) { + super("Required principal identifier claim '" + claimName + "' is missing or blank"); + this.claimName = claimName; + } + + /// Returns the configured claim that was missing or blank. + /// + /// @return principal identifier claim name + public String getClaimName() { + return claimName; + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiErrorResponseWriter.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiErrorResponseWriter.java new file mode 100644 index 00000000..b9c6e063 --- /dev/null +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiErrorResponseWriter.java @@ -0,0 +1,55 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.handler; + +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Instant; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ProblemDetail; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import lombok.RequiredArgsConstructor; + +/// Writes the standard ProblemDetail response from servlet filters. +@Component +@RequiredArgsConstructor +public class ApiErrorResponseWriter { + + private final ObjectMapper objectMapper; + + /// Writes an error status and the standard ProblemDetail response. + /// + /// @param request servlet request that produced the error + /// @param response servlet response to populate + /// @param status HTTP status for the error + /// @param description human-readable explanation of the error + /// @throws IOException if the response body cannot be written + public void write(HttpServletRequest request, HttpServletResponse response, HttpStatus status, + String description) throws IOException { + ProblemDetail problemDetail = ProblemDetail.forStatus(status); + problemDetail.setType(URI.create("about:blank")); + problemDetail.setTitle(status.getReasonPhrase()); + problemDetail.setDetail(description); + problemDetail.setInstance(URI.create(request.getRequestURI())); + problemDetail.setProperty("error", status.name()); + problemDetail.setProperty("error_description", description); + problemDetail.setProperty("timestamp", Instant.now().toString()); + ObjectNode responseBody = objectMapper.valueToTree(problemDetail); + responseBody.remove("properties"); + problemDetail.getProperties() + .forEach((name, value) -> responseBody.set(name, objectMapper.valueToTree(value))); + + response.setStatus(status.value()); + response.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + objectMapper.writeValue(response.getOutputStream(), responseBody); + } +} diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiExceptionHandler.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiExceptionHandler.java index 7627cd64..ed7b8822 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiExceptionHandler.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiExceptionHandler.java @@ -1,660 +1,329 @@ package com.decathlon.idp_core.infrastructure.adapters.api.handler; +import static java.util.Map.entry; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.CONFLICT; +import static org.springframework.http.HttpStatus.FORBIDDEN; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; import static org.springframework.http.HttpStatus.NOT_FOUND; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; +import static org.springframework.http.HttpStatus.UNPROCESSABLE_CONTENT; -import java.util.List; +import java.time.Instant; +import java.util.Arrays; import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; import jakarta.validation.ConstraintViolation; import jakarta.validation.ConstraintViolationException; +import org.springframework.beans.TypeMismatchException; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingPathVariableException; -import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; import org.springframework.web.method.annotation.HandlerMethodValidationException; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.NoHandlerFoundException; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import com.decathlon.idp_core.domain.constant.ValidationMessages; +import com.decathlon.idp_core.domain.exception.authorization.PrincipalNotAuthorizedException; import com.decathlon.idp_core.domain.exception.entity.EntityAlreadyExistsException; import com.decathlon.idp_core.domain.exception.entity.EntityDeletionBlockedException; import com.decathlon.idp_core.domain.exception.entity.EntityNotFoundException; import com.decathlon.idp_core.domain.exception.entity.EntityValidationException; -import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.*; -import com.decathlon.idp_core.domain.exception.entity_template.*; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingAlreadyInUseException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingConfigurationException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingHasNoPropertiesException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingHasNoRelationsException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingJsltErrorException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingNotFoundException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.ExpressionEvaluationFailedException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateIdentifierCannotChangeException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateIsRelationTargetException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateNameAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateNotFoundException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateUsedByDynamicMappingException; +import com.decathlon.idp_core.domain.exception.entity_template.PropertyDefinitionRulesConflictException; +import com.decathlon.idp_core.domain.exception.entity_template.PropertyNameAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.entity_template.PropertyNameNotFoundEntityTemplatePropertiesException; +import com.decathlon.idp_core.domain.exception.entity_template.PropertyTypeChangeException; +import com.decathlon.idp_core.domain.exception.entity_template.RelationCannotTargetItselfException; +import com.decathlon.idp_core.domain.exception.entity_template.RelationNameAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.entity_template.RelationNameNotFoundEntityTemplateRelationsException; +import com.decathlon.idp_core.domain.exception.entity_template.RelationTargetTemplateChangeException; +import com.decathlon.idp_core.domain.exception.entity_template.TargetTemplateNotFoundException; import com.decathlon.idp_core.domain.exception.filter.InvalidFilterDslException; +import com.decathlon.idp_core.domain.exception.mock.MockSecurityConfigurationException; +import com.decathlon.idp_core.domain.exception.principal.PrincipalCreationException; import com.decathlon.idp_core.domain.exception.principal.PrincipalNotFoundException; import com.decathlon.idp_core.domain.exception.search.InvalidSearchQueryException; -import com.decathlon.idp_core.domain.exception.webhook.*; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; +import com.decathlon.idp_core.domain.exception.webhook.WebhookAuthenticationException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookConfigurationMissingException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookConnectorAlreadyExistException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookConnectorConfigurationException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookConnectorNotFoundException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookConnectorTitleAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookDisabledException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException; import lombok.extern.slf4j.Slf4j; -import tools.jackson.core.JacksonException; -import tools.jackson.databind.exc.InvalidFormatException; -import tools.jackson.databind.exc.MismatchedInputException; -/// Global exception handler providing centralized error handling for all API -/// endpoints. -/// -/// **Infrastructure error handling strategy:** Intercepts domain and validation -/// exceptions and converts them to appropriate HTTP responses with consistent -/// error formatting. Ensures API consumers receive standardized error messages -/// regardless of internal failures. -/// -/// **Exception mapping approach:** -/// - Domain exceptions → HTTP 404/409 with business-meaningful messages -/// - Validation exceptions → HTTP 400 with field-specific error details -/// - JSON parsing errors → HTTP 400 with user-friendly parsing messages -/// - Generic exceptions → HTTP 500 with safe internal error responses -/// -/// **Error response standardization:** All errors follow consistent -/// [ErrorResponse] format with appropriate HTTP status codes and logged for -/// monitoring/debugging purposes. +/** + * Maps Spring MVC API exceptions to ProblemDetail responses. Camel webhook + * ingestion uses its own handler to return the same response contract. + */ @Slf4j -@ControllerAdvice -public class ApiExceptionHandler { - +@RestControllerAdvice +public class ApiExceptionHandler extends ResponseEntityExceptionHandler { + + private static final String PROPERTY_ERROR = "error"; + private static final String PROPERTY_ERROR_DESCRIPTION = "error_description"; + private static final String PROPERTY_TIMESTAMP = "timestamp"; + private static final String GENERIC_ERROR_DETAIL = "An unexpected error occurred. Please try again later."; + + /// Maps domain exceptions to HTTP statuses without placing HTTP semantics in + /// the domain layer. + private static final Map, HttpStatus> STATUS_BY_EXCEPTION = Map + .ofEntries(entry(InvalidFilterDslException.class, BAD_REQUEST), + entry(InvalidSearchQueryException.class, BAD_REQUEST), + entry(EntityTemplateIdentifierCannotChangeException.class, BAD_REQUEST), + entry(PropertyDefinitionRulesConflictException.class, BAD_REQUEST), + entry( + com.decathlon.idp_core.domain.exception.property.PropertyDefinitionRulesConflictException.class, + BAD_REQUEST), + entry(PropertyNameAlreadyExistsException.class, BAD_REQUEST), + entry(RelationNameAlreadyExistsException.class, BAD_REQUEST), + entry(TargetTemplateNotFoundException.class, BAD_REQUEST), + entry(EntityTemplateIsRelationTargetException.class, BAD_REQUEST), + entry(PropertyTypeChangeException.class, BAD_REQUEST), + entry(RelationTargetTemplateChangeException.class, BAD_REQUEST), + entry(RelationCannotTargetItselfException.class, BAD_REQUEST), + entry(EntityValidationException.class, BAD_REQUEST), + entry(EntityDynamicMappingConfigurationException.class, BAD_REQUEST), + entry(PropertyNameNotFoundEntityTemplatePropertiesException.class, UNPROCESSABLE_CONTENT), + entry(WebhookSecurityConfigurationException.class, BAD_REQUEST), + entry(WebhookConnectorConfigurationException.class, BAD_REQUEST), + entry(MockSecurityConfigurationException.class, BAD_REQUEST), + entry(WebhookAuthenticationException.class, UNAUTHORIZED), + entry(EntityTemplateNotFoundException.class, NOT_FOUND), + entry(EntityNotFoundException.class, NOT_FOUND), + entry(PrincipalNotFoundException.class, NOT_FOUND), + entry(WebhookConnectorNotFoundException.class, NOT_FOUND), + entry(EntityDynamicMappingNotFoundException.class, NOT_FOUND), + entry(EntityTemplateAlreadyExistsException.class, CONFLICT), + entry(EntityTemplateNameAlreadyExistsException.class, CONFLICT), + entry(EntityAlreadyExistsException.class, CONFLICT), + entry(EntityDeletionBlockedException.class, CONFLICT), + entry(EntityDynamicMappingAlreadyExistsException.class, CONFLICT), + entry(EntityDynamicMappingAlreadyInUseException.class, CONFLICT), + entry(WebhookConnectorAlreadyExistException.class, CONFLICT), + entry(EntityTemplateUsedByDynamicMappingException.class, CONFLICT), + entry(WebhookConnectorTitleAlreadyExistsException.class, CONFLICT), + entry(ExpressionEvaluationFailedException.class, UNPROCESSABLE_CONTENT), + entry(EntityDynamicMappingJsltErrorException.class, UNPROCESSABLE_CONTENT), + entry(RelationNameNotFoundEntityTemplateRelationsException.class, UNPROCESSABLE_CONTENT), + entry(EntityDynamicMappingHasNoPropertiesException.class, UNPROCESSABLE_CONTENT), + entry(EntityDynamicMappingHasNoRelationsException.class, UNPROCESSABLE_CONTENT), + entry(PrincipalCreationException.class, INTERNAL_SERVER_ERROR), + entry(WebhookConfigurationMissingException.class, INTERNAL_SERVER_ERROR), + entry(PrincipalNotAuthorizedException.class, FORBIDDEN), + entry(WebhookDisabledException.class, FORBIDDEN)); + + /** + * Prevents direct instantiation because Spring manages this exception handler. + */ private ApiExceptionHandler() { } - /// Handles domain exception when entity templates are not found. - /// - /// **HTTP mapping:** Maps domain EntityTemplateNotFoundException to HTTP 404 - /// status with business-meaningful error message for API consumers. - @ExceptionHandler(EntityTemplateNotFoundException.class) - public ResponseEntity handleTemplateNotFoundException( - EntityTemplateNotFoundException ex) { - log.warn("Template not found: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(NOT_FOUND.name(), ex.getMessage()); - return ResponseEntity.status(NOT_FOUND).body(errorResponse); - } - - /// Handles domain exception for malformed filter query strings (`q=` DSL). - /// - /// **HTTP mapping:** Maps domain [InvalidFilterDslException] to HTTP 400 Bad - /// Request - /// so API consumers receive clear feedback about invalid `q` parameter syntax. - @ExceptionHandler(InvalidFilterDslException.class) - public ResponseEntity handleInvalidFilterDslException( - InvalidFilterDslException ex) { - log.warn("Invalid filter query: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); - } - - /// Handles domain exception for malformed search filter trees or free-text - /// query strings. - /// - /// **HTTP mapping:** Maps domain [InvalidSearchQueryException] to HTTP 400 Bad - /// Request - /// so API consumers receive clear feedback about invalid search request syntax. - @ExceptionHandler(InvalidSearchQueryException.class) - public ResponseEntity handleInvalidSearchQueryException( - InvalidSearchQueryException ex) { - log.warn("Invalid search query: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); - } - - /// Handles domain exception when entity templates already exist. - /// - /// **HTTP mapping:** Maps domain EntityTemplateAlreadyExistsException to HTTP - /// 409 status indicating business rule conflict for duplicate identifiers. - @ExceptionHandler(EntityTemplateAlreadyExistsException.class) - public ResponseEntity handleEntityTemplateAlreadyExistsException( - EntityTemplateAlreadyExistsException ex) { - log.warn("Entity entityTemplateIdentifier already exists: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); - } - - /// Handles domain exception when entity entityTemplateIdentifier names already - /// exist. - /// - /// **HTTP mapping:** Maps domain EntityTemplateNameAlreadyExistsException to - /// HTTP 409 status indicating business rule conflict for duplicate - /// entityTemplateIdentifier names. - @ExceptionHandler(EntityTemplateNameAlreadyExistsException.class) - public ResponseEntity handleEntityTemplateNameAlreadyExistsException( - EntityTemplateNameAlreadyExistsException ex) { - log.warn("Entity entityTemplateIdentifier name already exists: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); - } - - /// Handles domain exception when attempting to change an entity - /// entityTemplateIdentifier - /// identifier. - /// - /// **HTTP mapping:** Maps domain EntityTemplateIdentifierCannotChangeException - /// to HTTP 400 status indicating validation error for immutable - /// identifier field. - @ExceptionHandler(EntityTemplateIdentifierCannotChangeException.class) - public ResponseEntity handleEntityTemplateIdentifierCannotChangeException( - EntityTemplateIdentifierCannotChangeException ex) { - log.warn("Entity entityTemplateIdentifier identifier cannot be changed: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse); - } - - /// Handles domain exception for wrong entity entityTemplateIdentifier property - /// rules. - /// - /// **HTTP mapping:** Maps domain PropertyDefinitionRulesConflictException to - /// HTTP 400 status indicating validation error for wrong property rules. - @ExceptionHandler(PropertyDefinitionRulesConflictException.class) - public ResponseEntity handleWrongPropertyRulesException( - PropertyDefinitionRulesConflictException ex) { - log.warn("Wrong Entity entityTemplateIdentifier property rules: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse); - } - - /// Handles domain exception when property names are duplicated within a - /// entityTemplateIdentifier. - /// - /// **HTTP mapping:** Maps domain PropertyNameAlreadyExistsException to HTTP 400 - /// status indicating validation error for duplicate property names. - @ExceptionHandler(PropertyNameAlreadyExistsException.class) - public ResponseEntity handlePropertyNameAlreadyExistsException( - PropertyNameAlreadyExistsException ex) { - log.warn("Duplicate property name: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); - } - - /// Handles domain exception when relation names are duplicated within a - /// entityTemplateIdentifier. - /// - /// **HTTP mapping:** Maps domain RelationNameAlreadyExistsException to HTTP 400 - /// status indicating validation error for duplicate relation names. - @ExceptionHandler(RelationNameAlreadyExistsException.class) - public ResponseEntity handleRelationNameAlreadyExistsException( - RelationNameAlreadyExistsException ex) { - log.warn("Duplicate relation name: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); - } - - /// Handles domain exception when a relation references a non-existent target - /// entityTemplateIdentifier. - /// - /// **HTTP mapping:** Maps domain TargetTemplateNotFoundException to HTTP 400 - /// status indicating validation error for missing target - /// entityTemplateIdentifier. - @ExceptionHandler(TargetTemplateNotFoundException.class) - public ResponseEntity handleTargetTemplateNotFoundException( - TargetTemplateNotFoundException ex) { - log.warn("Target entityTemplateIdentifier not found: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); - } - - /// Handles domain exception when attempting to delete a template that is still - /// referenced as a relation target in another template. - /// - /// **HTTP mapping:** Maps domain [EntityTemplateIsRelationTargetException] to - /// HTTP 400 Bad Request to signal a business rule violation that must be - /// resolved by the caller before retrying the deletion. - @ExceptionHandler(EntityTemplateIsRelationTargetException.class) - public ResponseEntity handleEntityTemplateIsRelationTargetException( - EntityTemplateIsRelationTargetException ex) { - log.warn("Template deletion blocked – still a relation target: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); + /** + * Converts request-body validation errors into a structured bad-request + * response. + */ + @Override + protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, + HttpHeaders headers, org.springframework.http.HttpStatusCode statusCode, WebRequest request) { + log.warn("Method argument validation error: {}", ex.getMessage()); + String errorMessage = ex.getBindingResult().getFieldErrors().stream() + .map(org.springframework.context.MessageSourceResolvable::getDefaultMessage) + .collect(Collectors.joining(", ")); + return ResponseEntity.status(statusCode).headers(headers) + .body(buildProblemDetail(HttpStatus.valueOf(statusCode.value()), errorMessage, request)); } - /// Handles domain exception when type changes are attempted. - /// - /// **HTTP mapping:** Maps domain PropertyTypeChangeException to HTTP 400 status - /// indicating validation error for type changes. - @ExceptionHandler(PropertyTypeChangeException.class) - public ResponseEntity handleTypeChangeException(PropertyTypeChangeException ex) { - log.warn("Type change error: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); + /** + * Reports a required path variable that could not be resolved from the request. + */ + @Override + protected ResponseEntity handleMissingPathVariable(MissingPathVariableException ex, + HttpHeaders headers, org.springframework.http.HttpStatusCode statusCode, WebRequest request) { + log.warn("Missing path variable: {}", ex.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).headers(headers) + .body(buildProblemDetail(HttpStatus.BAD_REQUEST, + "Missing required path variable: " + ex.getVariableName(), request)); } - /// Handles domain exception when relation target entityTemplateIdentifier - /// changes are - /// attempted. - /// - /// **HTTP mapping:** Maps domain RelationTargetTemplateChangeException to HTTP - /// 400 status indicating validation error for immutable target - /// entityTemplateIdentifier field. - @ExceptionHandler(RelationTargetTemplateChangeException.class) - public ResponseEntity handleRelationTargetTemplateChangeException( - RelationTargetTemplateChangeException ex) { - log.warn("Relation target entityTemplateIdentifier change error: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); + /** Reports requests for which no matching HTTP handler exists. */ + @Override + protected ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException ex, + HttpHeaders headers, org.springframework.http.HttpStatusCode statusCode, WebRequest request) { + log.warn("No handler found or missing path variable: {}", ex.getMessage()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).headers(headers).body(buildProblemDetail( + HttpStatus.NOT_FOUND, "Malformed request URL or missing path variable.", request)); } - /// Handles domain exception when a relation's target entityTemplateIdentifier - /// identifier is the - /// entityTemplateIdentifier itself. - /// - /// **HTTP mapping:** Maps domain RelationCannotTargetItselfException to HTTP - /// 400 - /// status indicating validation error for self-referential relations. - @ExceptionHandler(RelationCannotTargetItselfException.class) - public ResponseEntity handleRelationCannotTargetItselfException( - RelationCannotTargetItselfException ex) { - log.warn("Relation self-reference error: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); + /** Maps registered domain exceptions to ProblemDetail responses. */ + @ExceptionHandler(RuntimeException.class) + public ProblemDetail handleDomainException(RuntimeException ex) { + HttpStatus status = STATUS_BY_EXCEPTION.get(ex.getClass()); + if (status == null || status.is5xxServerError()) { + return handleUnexpectedException(ex); + } + log.warn("{}: {}", ex.getClass().getSimpleName(), ex.getMessage()); + return buildProblemDetail(status, ex.getMessage(), null); } - /// Handles validation exceptions from Spring MVC handler method parameters. - /// - /// **Error aggregation:** Combines multiple validation error messages into a - /// single user-friendly response with HTTP 400 status for client correction. - @ExceptionHandler(HandlerMethodValidationException.class) - public ResponseEntity handleHandlerMethodValidationException( - HandlerMethodValidationException ex) { + /** Converts method-parameter validation failures into a structured response. */ + @Override + protected ResponseEntity handleHandlerMethodValidationException( + HandlerMethodValidationException ex, HttpHeaders headers, HttpStatusCode statusCode, + WebRequest request) { log.warn("Handler method validation error: {}", ex.getMessage()); String errorMessage = ex.getAllErrors().stream() .map(org.springframework.context.MessageSourceResolvable::getDefaultMessage) .collect(Collectors.joining(", ")); - return createErrorResponse(HttpStatus.BAD_REQUEST, errorMessage); - } - - /// Handles domain exception when entities already exist. - /// - /// **HTTP mapping:** Maps domain EntityAlreadyExistsException to HTTP 409 - /// status - /// indicating business rule conflict for duplicate entities. - @ExceptionHandler(EntityAlreadyExistsException.class) - public ResponseEntity handleEntityAlreadyExistsException( - EntityAlreadyExistsException ex) { - log.warn("Entity already exists: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); - } - - /// Handles domain exception when entity validation fails. - /// - /// **HTTP mapping:** Maps domain EntityValidationException to HTTP 400 status - /// with aggregated validation error messages for client correction. - @ExceptionHandler(EntityValidationException.class) - public ResponseEntity handleEntityValidationException( - EntityValidationException ex) { - log.warn("Entity validation failed: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); - } - - /// Handles Spring MVC request body validation failures. - /// - /// **Field-level errors:** Extracts and aggregates field validation errors from - /// request body binding into comprehensive HTTP 400 error response. - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity handleMethodArgumentNotValidException( - MethodArgumentNotValidException ex) { - log.warn("Method argument validation error: {}", ex.getMessage()); - - String errorMessage = ex.getBindingResult().getFieldErrors().stream() - .map(org.springframework.context.MessageSourceResolvable::getDefaultMessage) - .collect(Collectors.joining(", ")); - - return createErrorResponse(HttpStatus.BAD_REQUEST, errorMessage); - } - - /// Handles JSON parsing and deserialization errors from request bodies. - /// - /// **User-friendly parsing:** Converts technical JSON parsing errors into - /// readable messages, especially for enum validation and format issues. - @ExceptionHandler(HttpMessageNotReadableException.class) - public ResponseEntity handleHttpMessageNotReadableException( - HttpMessageNotReadableException ex) { - log.warn("HTTP message not readable: {}", ex.getMessage()); - - if (ex.getCause()instanceof MismatchedInputException mismatch - && !(ex.getCause() instanceof InvalidFormatException)) { - String fieldPath = extractLastFieldNameFromPath(mismatch.getPath()); - String targetType = extractTargetType(mismatch.getOriginalMessage()); - - if (!targetType.isEmpty() && !fieldPath.isEmpty()) { - return createErrorResponse(HttpStatus.BAD_REQUEST, - "Invalid type for '" + fieldPath + "': expected " + targetType); - } + return ResponseEntity.status(HttpStatus.BAD_REQUEST).headers(headers) + .body(buildProblemDetail(HttpStatus.BAD_REQUEST, errorMessage, request)); + } + + @Override + protected ResponseEntity handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, + HttpStatusCode statusCode, WebRequest request) { + if (ex instanceof MethodArgumentTypeMismatchException mismatch) { + String errorMessage = switch (mismatch.getName()) { + case "page" -> ValidationMessages.PAGE_INDEX_NOT_INTEGER; + case "size" -> ValidationMessages.PAGE_SIZE_NOT_INTEGER; + default -> defaultTypeMismatchMessage(mismatch); + }; + log.warn("Request parameter type mismatch: {}", errorMessage); + return ResponseEntity.status(statusCode).headers(headers) + .body(buildProblemDetail(HttpStatus.BAD_REQUEST, errorMessage, request)); } - - String errorMessage = parseHttpMessageNotReadableError(ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, errorMessage); + return super.handleTypeMismatch(ex, headers, statusCode, request); } - /// Extracts the deepest (last) field name from a Jackson path reference list. - /// - /// Jackson populates `MismatchedInputException.getPath()` with references from - /// the root to the failing field. The last named reference is the most specific - /// field name to show in the error message. - private String extractLastFieldNameFromPath(List path) { - if (path == null || path.isEmpty()) { - return ""; + private static String defaultTypeMismatchMessage(MethodArgumentTypeMismatchException mismatch) { + String errorMessage = "Invalid value '%s' for parameter '%s'.".formatted(mismatch.getValue(), + mismatch.getName()); + Class requiredType = mismatch.getRequiredType(); + if (requiredType != null && requiredType.isEnum()) { + errorMessage += " Allowed values: " + Arrays.toString(requiredType.getEnumConstants()) + "."; + } else if (requiredType != null) { + errorMessage += " Expected type: " + requiredType.getSimpleName() + "."; } - return path.reversed().stream().map(JacksonException.Reference::getPropertyName) - .filter(name -> name != null && !name.isBlank()).findFirst().orElse(""); - } - - /// Handles invalid dynamic mapping targetIdentifiersExpressions (JSLT) provided - /// in webhook - /// configuration. - /// - /// **HTTP mapping:** Maps domain mapping configuration failures to HTTP 400, - /// because clients can fix these targetIdentifiersExpressions and retry. - @ExceptionHandler(EntityDynamicMappingConfigurationException.class) - public ResponseEntity handleEntityDynamicMappingConfigurationException( - EntityDynamicMappingConfigurationException ex) { - log.warn("Invalid entity dynamic mapping configuration: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); - } - - /// Handles JSLT expression evaluation failures (both primary and fallback - /// attempts failed). - /// - /// **HTTP mapping:** Maps to HTTP 422 Unprocessable Entity because the request - /// body is syntactically valid, but the mapping expression cannot be evaluated. - @ExceptionHandler(ExpressionEvaluationFailedException.class) - public ResponseEntity handleExpressionEvaluationFailedException( - ExpressionEvaluationFailedException ex) { - log.warn("Expression evaluation failed for '{}': {}", ex.getExpression(), ex.getReason()); - return createErrorResponse(HttpStatus.UNPROCESSABLE_CONTENT, ex.getMessage()); - } - - @ExceptionHandler(EntityDynamicMappingJsltErrorException.class) - public ResponseEntity handleEntityDynamicMappingJsltErrorException( - EntityDynamicMappingJsltErrorException ex) { - log.warn("JSLT error in entity dynamic mapping: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.UNPROCESSABLE_CONTENT, ex.getMessage()); - } - - @ExceptionHandler(PropertyNameNotFoundEntityTemplatePropertiesException.class) - public ResponseEntity handlePropertyNameNotFoundEntityTemplatePropertiesException( - PropertyNameNotFoundEntityTemplatePropertiesException ex) { - log.warn("Webhook mapping references unknown property: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.UNPROCESSABLE_CONTENT, ex.getMessage()); - } - - @ExceptionHandler(RelationNameNotFoundEntityTemplateRelationsException.class) - public ResponseEntity handleRelationNameNotFoundEntityTemplateRelationsException( - RelationNameNotFoundEntityTemplateRelationsException ex) { - log.warn("Webhook mapping references unknown relation: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.UNPROCESSABLE_CONTENT, ex.getMessage()); + return errorMessage; } - @ExceptionHandler(EntityDynamicMappingHasNoPropertiesException.class) - public ResponseEntity handleEntityDynamicMappingHasNoPropertiesException( - EntityDynamicMappingHasNoPropertiesException ex) { - log.warn("Dynamic mapping is missing required properties: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.UNPROCESSABLE_CONTENT, ex.getMessage()); - } - - @ExceptionHandler(EntityDynamicMappingHasNoRelationsException.class) - public ResponseEntity handleEntityDynamicMappingHasNoRelationsException( - EntityDynamicMappingHasNoRelationsException ex) { - log.warn("Dynamic mapping is missing required relations: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.UNPROCESSABLE_CONTENT, ex.getMessage()); - } - - @ExceptionHandler(WebhookSecurityConfigurationException.class) - public ResponseEntity handleWebhookSecurityConfigurationException( - WebhookSecurityConfigurationException ex) { - log.warn("Invalid webhook security configuration: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage()); - } - - /// Handles domain exception when entities are not found. - /// - /// **HTTP mapping:** Maps domain EntityNotFoundException to HTTP 404 status - /// with - /// specific entity context for API consumers. - @ExceptionHandler(EntityNotFoundException.class) - public ResponseEntity handleEntityNotFoundException(EntityNotFoundException ex) { - ErrorResponse errorResponse = new ErrorResponse(NOT_FOUND.name(), ex.getMessage()); - return ResponseEntity.status(NOT_FOUND).body(errorResponse); - } - - /// Handles principal not found exception when JIT provisioning fails. - /// - /// **HTTP mapping:** Maps PrincipalNotFoundException to HTTP 404 status - /// indicating the authenticated principal does not have a catalog entry. - @ExceptionHandler(PrincipalNotFoundException.class) - public ResponseEntity handlePrincipalNotFoundException( - PrincipalNotFoundException ex) { - log.warn("Principal not found: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(NOT_FOUND.name(), ex.getMessage()); - return ResponseEntity.status(NOT_FOUND).body(errorResponse); - } - - /// Handles Bean Validation constraint violations from domain model validation. - /// - /// **Error aggregation:** Combines multiple constraint violation messages into - /// single user-friendly response with HTTP 400 status for client correction. @ExceptionHandler(ConstraintViolationException.class) - public ResponseEntity handleConstraintViolationException( - ConstraintViolationException ex) { + public ProblemDetail handleConstraintViolationException(ConstraintViolationException ex) { log.warn("Validation constraint violation: {}", ex.getMessage()); - String errorMessage = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage) .collect(Collectors.joining(", ")); - return createErrorResponse(HttpStatus.BAD_REQUEST, errorMessage); - } - /// Handles domain exception when entity deletion is blocked by required - /// relations. - /// - /// **HTTP mapping:** Maps domain EntityDeletionBlockedException to HTTP 409 - /// status indicating business rule conflict where required relations prevent - /// deletion. - @ExceptionHandler(EntityDeletionBlockedException.class) - public ResponseEntity handleEntityDeletionBlockedException( - EntityDeletionBlockedException ex) { - log.warn("Entity deletion blocked: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.CONFLICT, ex.getMessage()); + return buildProblemDetail(HttpStatus.BAD_REQUEST, errorMessage, null); } - /// Handles missing path variables in the request URL. - /// - /// **HTTP mapping:** Maps MissingPathVariableException to HTTP 400 - /// status indicating a malformed request URL from the client. - @ExceptionHandler(MissingPathVariableException.class) - public ResponseEntity handleMissingPathVariableException( - MissingPathVariableException ex) { - log.warn("Missing path variable: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.BAD_REQUEST, - "Missing required path variable: " + ex.getVariableName()); + /** Converts database integrity conflicts into a safe HTTP 409 response. */ + @ExceptionHandler(DataIntegrityViolationException.class) + public ProblemDetail handleDataIntegrityViolationException(DataIntegrityViolationException ex) { + log.warn("Data integrity violation: {}", ex.getMostSpecificCause().getMessage()); + return buildProblemDetail(HttpStatus.CONFLICT, + "The request conflicts with the current state of the resource", null); } - /// Handles cases where a truncated URL matches no route, often caused by - /// missing trailing path variables. - /// - /// **HTTP mapping:** Maps NoHandlerFoundException to HTTP 400 - /// to align with missing identifier logic and pass integration tests. - @ExceptionHandler(NoHandlerFoundException.class) - public ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException ex) { - log.warn("No handler found or missing path variable: {}", ex.getMessage()); - return createErrorResponse(NOT_FOUND, "Malformed request URL or missing path variable."); + /** Returns a safe response for checked or otherwise unexpected exceptions. */ + @ExceptionHandler(Exception.class) + public ProblemDetail handleGenericException(Exception ex) { + return handleUnexpectedException(ex); } - private String parseHttpMessageNotReadableError(String originalMessage) { - if (originalMessage == null) { - return "Invalid request body format"; - } - - if (originalMessage.contains("Cannot deserialize value")) { - return parseDeserializationError(originalMessage); - } else if (originalMessage.contains("Required request body is missing")) { - return "Request body is required"; - } else if (originalMessage.contains("JSON parse error")) { - return "Invalid JSON format in request body"; - } - - return "Invalid request body format"; + private ProblemDetail handleUnexpectedException(Exception ex) { + log.error("Unexpected error occurred: {}", ex.getMessage(), ex); + return buildProblemDetail(INTERNAL_SERVER_ERROR, GENERIC_ERROR_DETAIL, null); } - private String parseDeserializationError(String originalMessage) { - if (originalMessage.contains("not one of the values accepted for Enum class")) { - return parseEnumDeserializationError(originalMessage); + /** + * Adds the API error contract fields to framework-generated problem details. + */ + @Override + protected ResponseEntity createResponseEntity(Object body, HttpHeaders headers, + HttpStatusCode statusCode, WebRequest request) { + if (body instanceof ProblemDetail problemDetail) { + enrichProblemDetail(problemDetail, statusCode, request); } - return parseTypeDeserializationError(originalMessage); + return super.createResponseEntity(body, headers, statusCode, request); } - private String parseTypeDeserializationError(String originalMessage) { - String targetType = extractTargetType(originalMessage); - String invalidValue = extractInvalidValueFromString(originalMessage); - - if (!targetType.isEmpty() && !invalidValue.isEmpty()) { - return "Invalid value '" + invalidValue + "' for property, expected " + targetType; - } else if (!targetType.isEmpty()) { - return "Invalid type: expected " + targetType; + private void enrichProblemDetail(ProblemDetail problemDetail, HttpStatusCode statusCode, + WebRequest request) { + Map properties = problemDetail.getProperties(); + if (properties == null || !properties.containsKey(PROPERTY_ERROR)) { + HttpStatus status = HttpStatus.resolve(statusCode.value()); + problemDetail.setProperty(PROPERTY_ERROR, + status != null ? status.name() : Integer.toString(statusCode.value())); } - return "Cannot deserialize request body property"; - } - - private String extractTargetType(String message) { - Pattern typePattern = Pattern.compile("Cannot deserialize value of type `([^`]+)`"); - Matcher matcher = typePattern.matcher(message); - if (matcher.find()) { - String fullType = matcher.group(1); - String rawType = fullType.contains("<") - ? fullType.substring(0, fullType.indexOf('<')) - : fullType; - return rawType.substring(rawType.lastIndexOf('.') + 1); + if (properties == null || !properties.containsKey(PROPERTY_ERROR_DESCRIPTION)) { + problemDetail.setProperty(PROPERTY_ERROR_DESCRIPTION, problemDetail.getDetail()); } - return ""; - } - - private String extractInvalidValueFromString(String message) { - Pattern valuePattern = Pattern.compile("from String \"([^\"]+)\""); - Matcher matcher = valuePattern.matcher(message); - if (matcher.find()) { - return matcher.group(1); + if (properties == null || !properties.containsKey(PROPERTY_TIMESTAMP)) { + problemDetail.setProperty(PROPERTY_TIMESTAMP, Instant.now()); } - return ""; - } - - private String parseEnumDeserializationError(String originalMessage) { - String enumTypeName = getPropertyNameFromEnumType(originalMessage); - String invalidValue = extractInvalidValueFromString(originalMessage); - - if (!enumTypeName.isEmpty() && !invalidValue.isEmpty()) { - return "Invalid value '" + invalidValue + "' for property '" + enumTypeName + "'"; - } else if (!enumTypeName.isEmpty()) { - return "Invalid value for property '" + enumTypeName + "'"; + if (problemDetail.getInstance() == null + && request instanceof ServletWebRequest servletRequest) { + problemDetail.setInstance(java.net.URI.create(servletRequest.getRequest().getRequestURI())); } - return "Invalid enum value in request body"; } - private static final Map ENUM_TYPE_TO_PROPERTY = Map.of("PropertyType", "type", - "PropertyFormat", "format"); - - private static final Pattern ENUM_CLASS_PATTERN = Pattern - .compile("Cannot deserialize value of type `(?:[\\w.]+\\.)?(\\w+)`"); - - private String getPropertyNameFromEnumType(String message) { - Matcher matcher = ENUM_CLASS_PATTERN.matcher(message); - if (matcher.find()) { - String enumType = matcher.group(1); - return ENUM_TYPE_TO_PROPERTY.getOrDefault(enumType, ""); + /** + * Builds the common RFC 9457 problem-detail representation returned by this + * handler. + */ + private ProblemDetail buildProblemDetail(HttpStatus status, String detail, WebRequest request) { + ProblemDetail problemDetail = ProblemDetail.forStatus(status); + problemDetail.setTitle(status.getReasonPhrase()); + problemDetail.setDetail(detail); + String path = resolveRequestPath(request); + if (path != null) { + problemDetail.setInstance(java.net.URI.create(path)); } - return ""; - } - - /// Handles all unexpected exceptions as safety fallback. - /// - /// **Security consideration:** Returns generic error message to prevent - /// information leakage while logging full exception details for - /// internal debugging. - @ExceptionHandler(Exception.class) - public ResponseEntity handleGenericException(Exception ex) { - log.error("Unexpected error occurred: {}", ex.getMessage(), ex); - - String errorMessage = "An unexpected error occurred. Please try again later."; - return createErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, errorMessage); - } - - /// Handles webhook signature and credential validation failures. - /// - /// HTTP mapping: Maps WebhookAuthenticationException to HTTP 401 Unauthorized. - @ExceptionHandler(WebhookAuthenticationException.class) - public ResponseEntity handleWebhookAuthenticationException( - WebhookAuthenticationException ex) { - log.warn("Webhook authentication failed: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.UNAUTHORIZED.name(), - ex.getMessage()); - return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse); - } - - /// Handles missing webhook connector configuration. - /// - /// HTTP mapping: Maps WebhookConnectorNotFoundException to HTTP 404 Not Found. - @ExceptionHandler(WebhookConnectorNotFoundException.class) - public ResponseEntity handleWebhookConnectorNotFoundException( - WebhookConnectorNotFoundException ex) { - log.warn("Webhook connector not found: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(NOT_FOUND.name(), ex.getMessage()); - return ResponseEntity.status(NOT_FOUND).body(errorResponse); - } - - /// Handles a webhook connector referencing a non-existent entity dynamic - /// mapping. - /// - /// HTTP mapping: Maps EntityDynamicMappingNotFoundException to HTTP 404 Not - /// Found, because the referenced mapping must be created beforehand. - @ExceptionHandler(EntityDynamicMappingNotFoundException.class) - public ResponseEntity handleEntityDynamicMappingNotFoundException( - EntityDynamicMappingNotFoundException ex) { - log.warn("Referenced entity dynamic mapping not found: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(NOT_FOUND.name(), ex.getMessage()); - return ResponseEntity.status(NOT_FOUND).body(errorResponse); - } - - /// Handles creation of a dynamic mapping whose identifier already exists. - /// - /// HTTP mapping: Maps EntityDynamicMappingAlreadyExistsException to HTTP 409 - /// Conflict, surfacing the uniqueness violation with business meaning. - @ExceptionHandler(EntityDynamicMappingAlreadyExistsException.class) - public ResponseEntity handleEntityDynamicMappingAlreadyExistsException( - EntityDynamicMappingAlreadyExistsException ex) { - log.warn("Entity dynamic mapping identifier conflict: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); - } - - @ExceptionHandler(EntityDynamicMappingAlreadyInUseException.class) - public ResponseEntity handleEntityDynamicMappingAlreadyInUseException( - EntityDynamicMappingAlreadyInUseException ex) { - log.warn("Entity dynamic mapping already in use: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); - } - - /// Handles webhook connector identifier duplication conflicts. - @ExceptionHandler(WebhookConnectorAlreadyExistException.class) - public ResponseEntity handleWebhookConnectorAlreadyExistException( - WebhookConnectorAlreadyExistException ex) { - log.warn("Webhook connector identifier conflict: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); - } - - @ExceptionHandler(EntityTemplateUsedByDynamicMappingException.class) - public ResponseEntity handleTemplateAlreadyMappedInWebhookConfiguration( - EntityTemplateUsedByDynamicMappingException ex) { - log.warn("Entity entityTemplateIdentifier in use by webhook mapping conflict: {}", - ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); - } - - /// Handles webhook connector name duplication conflicts. - @ExceptionHandler(WebhookConnectorTitleAlreadyExistsException.class) - public ResponseEntity handleWebhookConnectorTitleAlreadyExistsException( - WebhookConnectorTitleAlreadyExistsException ex) { - log.warn("Webhook connector name conflict: {}", ex.getMessage()); - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.name(), ex.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); - } - - private static ResponseEntity createErrorResponse(HttpStatus httpStatus, - String errorMessage) { - return new ResponseEntity<>(new ErrorResponse(httpStatus.name(), errorMessage), httpStatus); + problemDetail.setProperty(PROPERTY_ERROR, status.name()); + problemDetail.setProperty(PROPERTY_ERROR_DESCRIPTION, detail); + problemDetail.setProperty(PROPERTY_TIMESTAMP, Instant.now()); + return problemDetail; + } + + /** + * Resolves the request path from the given request or, for handlers that do not + * receive one, from the current servlet request context. + */ + private static String resolveRequestPath(WebRequest request) { + WebRequest effective = request; + if (effective == null + && RequestContextHolder.getRequestAttributes()instanceof ServletRequestAttributes attrs) { + effective = new ServletWebRequest(attrs.getRequest()); + } + return effective == null ? null : effective.getDescription(false).replace("uri=", ""); } - } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/connector/webhook/InboundWebhookMapper.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/connector/webhook/InboundWebhookMapper.java index 76aa51e4..9268db52 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/connector/webhook/InboundWebhookMapper.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/connector/webhook/InboundWebhookMapper.java @@ -5,6 +5,7 @@ import org.springframework.stereotype.Component; +import com.decathlon.idp_core.domain.constant.ValidationMessages; import com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException; import com.decathlon.idp_core.domain.model.entity_mapping.EntityDynamicMapping; import com.decathlon.idp_core.domain.model.enums.WebhookSecurityType; @@ -36,7 +37,8 @@ public class InboundWebhookMapper { public WebhookConnector toDomain(InboundWebhookCreateDtoIn dto, List resolvedMappings) { return new WebhookConnector(null, dto.identifier(), dto.name(), dto.description(), - dto.enabled(), safeMappings(resolvedMappings), toDomain(dto.security())); + dto.enabled(), safeMappings(resolvedMappings), + toDomain(dto.security(), dto.enabled() && !safeMappings(resolvedMappings).isEmpty())); } /// Converts API update payload to domain aggregate using the path identifier as @@ -50,7 +52,8 @@ public WebhookConnector toDomain(InboundWebhookCreateDtoIn dto, public WebhookConnector toDomainForUpdate(String identifier, InboundWebhookUpdateDtoIn dto, List resolvedMappings) { return new WebhookConnector(null, identifier, dto.name(), dto.description(), dto.enabled(), - safeMappings(resolvedMappings), toDomain(dto.security())); + safeMappings(resolvedMappings), + toDomain(dto.security(), dto.enabled() && !safeMappings(resolvedMappings).isEmpty())); } /// Converts domain aggregate to API response payload. @@ -70,11 +73,19 @@ private List safeMappings(List mappi return mappings == null ? List.of() : List.copyOf(mappings); } - private WebhookSecurity toDomain(InboundWebhookSecurityContractDtoIn security) { + private WebhookSecurity toDomain(InboundWebhookSecurityContractDtoIn security, boolean enabled) { if (security == null) { return new WebhookSecurity(WebhookSecurityType.NONE, Map.of()); } + if (security.type() == null || security.type().isBlank()) { + if (!enabled) { + return new WebhookSecurity(WebhookSecurityType.NONE, safeMap(security.config())); + } + throw new WebhookSecurityConfigurationException( + ValidationMessages.WEBHOOK_CONNECTOR_SECURITY_TYPE_MANDATORY); + } + var type = parseSecurityType(security.type()); var config = safeMap(security.config()); diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity/EntityDtoOutFromEntityNodeMapper.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity/EntityDtoOutFromEntityNodeMapper.java index 107fc27d..a14547f7 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity/EntityDtoOutFromEntityNodeMapper.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity/EntityDtoOutFromEntityNodeMapper.java @@ -63,6 +63,21 @@ public class EntityDtoOutFromEntityNodeMapper { /// relationship collection /// @return a fully mapped, flat [EntityDtoOut] object public EntityDtoOut toDto(EntityGraphNode root, String entityTemplateIdentifier, int maxDepth) { + return toDto(root, entityTemplateIdentifier, maxDepth, false); + } + + /// Converts a graph to the entity DTO and optionally includes relation + /// properties. + /// + /// @param root the starting root node of the entity graph + /// @param entityTemplateIdentifier the template key used for root property + /// definitions + /// @param maxDepth the maximum depth for relationship collection + /// @param includeRelationsProperties whether related entities include their + /// property values + /// @return the mapped entity DTO, or null when the root is null + public EntityDtoOut toDto(EntityGraphNode root, String entityTemplateIdentifier, int maxDepth, + boolean includeRelationsProperties) { if (root == null) { return null; } @@ -70,20 +85,28 @@ public EntityDtoOut toDto(EntityGraphNode root, String entityTemplateIdentifier, EntityTemplate entityTemplate = entityTemplateService .getEntityTemplateByIdentifier(entityTemplateIdentifier); - return toDto(root, entityTemplate, maxDepth); + return toDto(root, entityTemplate, maxDepth, includeRelationsProperties); } /// Internal orchestrator handling property conversions and initiating /// directional graph traversals. private EntityDtoOut toDto(EntityGraphNode root, EntityTemplate entityTemplate, int maxDepth) { + return toDto(root, entityTemplate, maxDepth, false); + } + + private EntityDtoOut toDto(EntityGraphNode root, EntityTemplate entityTemplate, int maxDepth, + boolean includeRelationsProperties) { if (root == null) { return null; } Map properties = mapPropertiesFromGraphNode(root, entityTemplate); + Map templatesByIdentifier = new HashMap<>(); + templatesByIdentifier.put(entityTemplate.identifier(), entityTemplate); var state = new TraversalState(root.identifier(), new HashMap<>(), new HashMap<>(), - new HashMap<>(), new HashSet<>()); + new HashMap<>(), new HashSet<>(), includeRelationsProperties, templatesByIdentifier, + new HashMap<>()); // Initiate directional traversals independently starting from root at depth 0 traverseOutbound(root, 0, maxDepth, state); @@ -139,7 +162,7 @@ public Page toPageDto(Page graphNodesPage, /// @param maxDepth maximum allowable depth boundary /// @param state shared accumulator state tracking visited depths and /// emitted edge signatures - private static void traverseOutbound(EntityGraphNode node, int currentDepth, int maxDepth, + private void traverseOutbound(EntityGraphNode node, int currentDepth, int maxDepth, TraversalState state) { String nodeId = nodeId(node.templateIdentifier(), node.identifier()); @@ -160,8 +183,7 @@ private static void traverseOutbound(EntityGraphNode node, int currentDepth, int if (shouldCollectRelations && isNotRoot && state.emittedEdgeSignatures().add(signature)) { state.relationsMap().computeIfAbsent(relation.name(), k -> new LinkedHashSet<>()) - .add(new EntitySummaryDto(target.identifier(), target.name(), - target.templateIdentifier())); + .add(toSummaryDto(target, state)); } if (currentDepth < maxDepth) { @@ -181,7 +203,7 @@ private static void traverseOutbound(EntityGraphNode node, int currentDepth, int /// @param maxDepth maximum allowable depth boundary /// @param state shared accumulator state tracking visited depths and /// emitted edge signatures - private static void traverseInbound(EntityGraphNode node, int currentDepth, int maxDepth, + private void traverseInbound(EntityGraphNode node, int currentDepth, int maxDepth, TraversalState state) { String nodeId = nodeId(node.templateIdentifier(), node.identifier()); @@ -202,8 +224,7 @@ private static void traverseInbound(EntityGraphNode node, int currentDepth, int if (shouldCollectRelations && isNotRoot && state.emittedEdgeSignatures().add(signature)) { state.relationsMap().computeIfAbsent(relation.name(), k -> new LinkedHashSet<>()) - .add(new EntitySummaryDto(source.identifier(), source.name(), - source.templateIdentifier())); + .add(toSummaryDto(source, state)); } if (currentDepth < maxDepth) { @@ -222,6 +243,21 @@ private static String nodeId(String templateIdentifier, String identifier) { return templateIdentifier + ":" + identifier; } + private EntitySummaryDto toSummaryDto(EntityGraphNode node, TraversalState state) { + if (!state.includeRelationsProperties()) { + return new EntitySummaryDto(node.identifier(), node.name(), node.templateIdentifier()); + } + + String nodeId = nodeId(node.templateIdentifier(), node.identifier()); + return state.relatedEntitiesByNodeId().computeIfAbsent(nodeId, _ -> { + EntityTemplate template = state.templatesByIdentifier().computeIfAbsent( + node.templateIdentifier(), entityTemplateService::getEntityTemplateByIdentifier); + Map properties = mapPropertiesFromGraphNode(node, template); + return new EntitySummaryDto(node.identifier(), node.name(), node.templateIdentifier(), + properties); + }); + } + /// Maps properties from a graph node using the provided template definition for /// type conversion. /// @@ -258,6 +294,8 @@ private Map mapPropertiesFromGraphNode(EntityGraphNode graphNode /// signatures readable and manage state efficiently across directional passes. private record TraversalState(String rootIdentifier, Map> relationsMap, Map visitedOutboundDepths, - Map visitedInboundDepths, Set emittedEdgeSignatures) { + Map visitedInboundDepths, Set emittedEdgeSignatures, + boolean includeRelationsProperties, Map templatesByIdentifier, + Map relatedEntitiesByNodeId) { } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity_template/EntityTemplateMapper.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity_template/EntityTemplateMapper.java index d64da394..3bd877b4 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity_template/EntityTemplateMapper.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity_template/EntityTemplateMapper.java @@ -110,7 +110,6 @@ public EntityTemplateDtoOut fromEntityTemplatetoDto(EntityTemplate entity) { /// This is a convenience method for bulk conversion operations, particularly /// useful /// for paginated results and list endpoints. - ///

/// /// @param entities the list of domain entities to convert, may be null /// @return a list of converted EntityTemplateDtoOut objects, empty list if diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/PrincipalExtractor.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/PrincipalExtractor.java index d696ef5f..06568578 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/PrincipalExtractor.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/PrincipalExtractor.java @@ -35,27 +35,11 @@ /// IdP-specific claim names and this extractor's internal logic. Configure `app.security.authentication.user-claim-mappings` /// in `application.yml` to match your IdP's token structure. /// -/// **Service Account Detection:** -/// Detecting M2M tokens reliably is challenging because different IdPs signal M2M differently: -/// - OAuth2 standard: `grant_type=client_credentials` (non-standard in JWT claims) -/// - Auth0 custom: May include `gty` or explicit `service_name` claim -/// - Keycloak custom: May use different claim structures -/// -/// This extractor supports two modes configured via `app.security.authentication.service-account-detection.mode`: -/// 1. **Strict Mode (Recommended):** Checks for a single, definitive claim (for example, `token_type=m2m`) -/// - Prevents false positives where human users are misclassified as service accounts -/// - Requires IdP or API gateway to inject a clear M2M indicator -/// 2. **Legacy Mode:** Falls back to loose OR logic checking multiple claims -/// - Maintains backwards compatibility with existing deployments -/// - Prone to false positives (for example, human user with `client_id` present) -/// -/// **Recommendation for production deployments:** -/// - Configure a **definitive claim** in your IdP or API gateway that unambiguously identifies M2M tokens -/// - Switch to **strict mode** to prevent security-critical misclassifications -/// - Document the expected claim structure for your IdP in the configuration +/// JWT kind and identifiers use the provider-specific +/// `app.security.authentication.principal-extraction` configuration. OAuth2/OIDC +/// user extraction continues to use `AuthenticationProperties`. /// /// @see AuthenticationProperties -/// @see AuthenticationProperties.ServiceAccountDetection @Service @RequiredArgsConstructor public class PrincipalExtractor { diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/strategies/JwtPrincipalExtractionStrategy.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/strategies/JwtPrincipalExtractionStrategy.java index b87af68b..efc73a99 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/strategies/JwtPrincipalExtractionStrategy.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/strategies/JwtPrincipalExtractionStrategy.java @@ -1,16 +1,12 @@ package com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies; -import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.CLIENT_CREDENTIALS; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.CLIENT_ID; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.EMAIL; -import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.GRANT_TYPE; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.GROUPS; -import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.GTY; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.NAME; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.ORIGIN; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.PREFERRED_USERNAME; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.SERVICE_NAME; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AZP; import java.util.HashMap; import java.util.List; @@ -24,15 +20,20 @@ import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; import com.decathlon.idp_core.domain.model.principal.PrincipalKind; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.AuthenticationProperties; +import com.decathlon.idp_core.infrastructure.adapters.api.configuration.PrincipalExtractionProperties; +import com.decathlon.idp_core.infrastructure.adapters.api.exception.MissingPrincipalIdentifierException; import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractionStrategy; @Component public class JwtPrincipalExtractionStrategy implements PrincipalExtractionStrategy { private final AuthenticationProperties authProperties; + private final PrincipalExtractionProperties extractionProperties; - public JwtPrincipalExtractionStrategy(AuthenticationProperties authProperties) { + public JwtPrincipalExtractionStrategy(AuthenticationProperties authProperties, + PrincipalExtractionProperties extractionProperties) { this.authProperties = authProperties; + this.extractionProperties = extractionProperties; } @Override @@ -43,193 +44,66 @@ public boolean supports(Authentication authentication) { @Override public PrincipalInfo extract(Authentication authentication) { JwtAuthenticationToken jwtToken = (JwtAuthenticationToken) authentication; - var claims = jwtToken.getToken().getClaims(); - String sub = jwtToken.getToken().getSubject(); + Map claims = new HashMap<>(jwtToken.getToken().getClaims()); + Optional.ofNullable(jwtToken.getToken().getSubject()) + .ifPresent(subject -> claims.putIfAbsent("sub", subject)); + boolean isHuman = extractionProperties.humanIndicatorClaims().stream().map(claims::get) + .anyMatch(JwtPrincipalExtractionStrategy::hasNonblankValue); - boolean isServiceAccount = detectServiceAccount(claims, sub); - - if (isServiceAccount) { - return extractServiceAccountFromJwt(sub, claims); - } - return extractHumanFromJwt(sub, claims); + return isHuman ? extractHumanFromJwt(claims) : extractMachineFromJwt(claims); } - /// Detects if the JWT token belongs to a service account (M2M) based on - /// configured strategy. - /// - /// **Strict Mode (Recommended):** - /// Checks for a single, definitive claim configured in - /// `app.security.authentication.service-account-detection.definitive-claim-name`. - /// Example: If configured to check `token_type=m2m`, returns true only if that - /// exact claim is present and has that value. - /// Benefits: Prevents false positives and security-critical misclassifications. - /// Risks: Requires IdP or API gateway to inject the definitive claim. - /// - /// **Legacy Mode (Backwards Compatibility):** - /// Falls back to loose OR conditions checking multiple optional claims. - /// Checks: `grant_type=client_credentials` OR `service_name` exists OR - /// `sub==client_id` - /// Benefits: Works without reconfiguration for existing deployments. - /// Risks: Prone to false positives (e.g., human user classified as M2M). - /// - /// @param claims the JWT claims map - /// @param sub the subject claim value - /// @return true if the token is identified as a service account, false - /// otherwise - private boolean detectServiceAccount(Map claims, String sub) { - AuthenticationProperties.ServiceAccountDetection config = authProperties - .serviceAccountDetection(); - - if (!config.enabled()) { - return false; - } - - if ("strict".equalsIgnoreCase(config.mode())) { - return detectServiceAccountStrict(claims, config); - } - - // Legacy mode (default for backwards compatibility) - return detectServiceAccountLegacy(claims, sub); + private static boolean hasNonblankValue(Object value) { + return value != null && !value.toString().isBlank(); } - /// Strict mode service account detection: checks for a single definitive claim. - /// Example: `token_type=m2m` or `account_type=service` - /// - /// @param claims the JWT claims map - /// @param config the service account detection configuration - /// @return true only if the definitive claim is present and has the expected - /// value - private boolean detectServiceAccountStrict(Map claims, - AuthenticationProperties.ServiceAccountDetection config) { - Object claimValue = claims.get(config.definitiveClaimName()); - if (claimValue == null) { - return false; - } - return config.definitiveClaimValue().equals(claimValue.toString()); - } - - /// Legacy mode service account detection: checks multiple claims with OR logic. - /// Fallback behavior for backwards compatibility. - /// - /// Checks: - /// 1. grant_type or gty = "client_credentials" (OAuth2 standard) - /// 2. service_name claim exists (Auth0 / custom IdP) - /// 3. sub equals client_id or azp (subject is the OAuth2 client itself) - /// - /// **Warning:** This logic is prone to false positives. Strongly recommend - /// upgrading - /// to strict mode for production deployments. - /// - /// @param claims the JWT claims map - /// @param sub the subject claim value - /// @return true if any legacy condition indicates M2M - private boolean detectServiceAccountLegacy(Map claims, String sub) { - AuthenticationProperties.ServiceAccountDetection config = authProperties - .serviceAccountDetection(); - - List fallbackClaims = config.legacyFallbackClaims(); - - if (fallbackClaims.contains(GRANT_TYPE)) { - String grantTypeClaim = authProperties.userClaimMappings().get(GRANT_TYPE); - String gtyClaim = authProperties.userClaimMappings().get(GTY); - - String grantType = Optional.ofNullable(claims.get(grantTypeClaim)) - .or(() -> Optional.ofNullable(gtyClaim) - .flatMap(claim -> Optional.ofNullable(claims.get(claim)))) - .map(Object::toString).orElse(null); - - if (CLIENT_CREDENTIALS.equals(grantType)) { - return true; - } - } - - if (fallbackClaims.contains(SERVICE_NAME)) { - String serviceNameClaim = authProperties.userClaimMappings().get(SERVICE_NAME); - if (serviceNameClaim != null && claims.containsKey(serviceNameClaim)) { - return true; - } - } - - if (fallbackClaims.contains(CLIENT_ID)) { - String clientIdClaim = authProperties.userClaimMappings().get(CLIENT_ID); - String azpClaim = authProperties.userClaimMappings().get(AZP); - - String clientId = Optional.ofNullable(clientIdClaim) - .flatMap(claim -> Optional.ofNullable(claims.get(claim))) - .or(() -> Optional.ofNullable(azpClaim) - .flatMap(claim -> Optional.ofNullable(claims.get(claim)))) - .map(Object::toString).orElse(null); - - return clientId != null && clientId.equals(sub); - } - - return false; - } - - private PrincipalInfo extractHumanFromJwt(String sub, Map claims) { + private PrincipalInfo extractHumanFromJwt(Map claims) { + String identifierClaim = extractionProperties.human().idClaim(); + String identifier = requiredClaim(claims, identifierClaim); Map claimMappings = authProperties.userClaimMappings(); - // Try to extract preferred username, fallback to sub - String preferredUsernameClaim = claimMappings.get(PREFERRED_USERNAME); - String identifier = Optional.ofNullable(preferredUsernameClaim) - .flatMap(c -> Optional.ofNullable(claims.get(c))).map(Object::toString).orElse(sub); - - // Try to extract name, fallback to identifier - String nameClaim = claimMappings.get(NAME); - String name = Optional.ofNullable(nameClaim).flatMap(c -> Optional.ofNullable(claims.get(c))) - .map(Object::toString).orElse(identifier); + Optional preferredUsername = mappedClaim(claims, claimMappings, PREFERRED_USERNAME); + String name = mappedClaim(claims, claimMappings, NAME).or(() -> preferredUsername) + .orElse(identifier); Map attributes = new HashMap<>(); + mappedClaim(claims, claimMappings, EMAIL).ifPresent(value -> attributes.put(EMAIL, value)); - // Extract email if present - String emailClaim = claimMappings.get(EMAIL); - if (emailClaim != null) { - Optional.ofNullable(claims.get(emailClaim)).map(Object::toString) - .ifPresent(email -> attributes.put(EMAIL, email)); - } - - List groups = extractGroups(claims); - - return new PrincipalInfo(identifier, PrincipalKind.HUMAN, name, attributes, groups); + return new PrincipalInfo(identifier, PrincipalKind.HUMAN, name, attributes, + extractGroups(claims)); } - private PrincipalInfo extractServiceAccountFromJwt(String sub, Map claims) { + private PrincipalInfo extractMachineFromJwt(Map claims) { + String identifierClaim = extractionProperties.machine().idClaim(); + String machineId = requiredClaim(claims, identifierClaim); + String identifier = extractionProperties.machine().idPrefix() + machineId; Map claimMappings = authProperties.userClaimMappings(); - // Extract client_id or azp, fallback to sub - String clientIdClaim = claimMappings.get(CLIENT_ID); - String azpClaim = claimMappings.get(AZP); - - String clientId = Optional.ofNullable(clientIdClaim) - .flatMap(c -> Optional.ofNullable(claims.get(c))) - .or(() -> Optional.ofNullable(azpClaim).flatMap(c -> Optional.ofNullable(claims.get(c)))) - .map(Object::toString).orElse(sub); - - // Try to extract service_name or name, fallback to clientId - String serviceNameClaim = claimMappings.get(SERVICE_NAME); - String nameClaim = claimMappings.get(NAME); - - String serviceName = Optional.ofNullable(serviceNameClaim) - .flatMap(c -> Optional.ofNullable(claims.get(c))) - .or(() -> Optional.ofNullable(nameClaim).flatMap(c -> Optional.ofNullable(claims.get(c)))) - .map(Object::toString).orElse(clientId); + String clientId = mappedClaim(claims, claimMappings, CLIENT_ID).orElse(machineId); + String serviceName = mappedClaim(claims, claimMappings, SERVICE_NAME) + .or(() -> mappedClaim(claims, claimMappings, NAME)).orElse(clientId); Map attributes = new HashMap<>(); attributes.put(CLIENT_ID, clientId); + mappedClaim(claims, Map.of(ORIGIN, ORIGIN), ORIGIN) + .ifPresent(value -> attributes.put(ORIGIN, value)); - // Extract origin if present (non-standard, IdP-specific) - String originValue = Optional.ofNullable(claims.get(ORIGIN)).map(Object::toString).orElse(null); - if (originValue != null) { - attributes.put(ORIGIN, originValue); - } + return new PrincipalInfo(identifier, PrincipalKind.SERVICE_ACCOUNT, serviceName, attributes, + extractGroups(claims)); + } - List groups = extractGroups(claims); + private String requiredClaim(Map claims, String claimName) { + return Optional.ofNullable(claims.get(claimName)).map(String::valueOf) + .filter(value -> !value.isBlank()) + .orElseThrow(() -> new MissingPrincipalIdentifierException(claimName)); + } - return new PrincipalInfo(clientId, PrincipalKind.SERVICE_ACCOUNT, serviceName, attributes, - groups); + private Optional mappedClaim(Map claims, + Map claimMappings, String mappingName) { + return Optional.ofNullable(claimMappings.get(mappingName)).map(claims::get) + .filter(JwtPrincipalExtractionStrategy::hasNonblankValue).map(String::valueOf); } - @SuppressWarnings("unchecked") private List extractGroups(Map claims) { Map claimMappings = authProperties.userClaimMappings(); String groupsClaim = claimMappings.get(GROUPS); diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/strategies/OAuth2UserPrincipalExtractionStrategy.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/strategies/OAuth2UserPrincipalExtractionStrategy.java index 1e11cf1f..f72415a3 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/strategies/OAuth2UserPrincipalExtractionStrategy.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/principal/strategies/OAuth2UserPrincipalExtractionStrategy.java @@ -4,7 +4,6 @@ import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.GROUPS; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.NAME; import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.PREFERRED_USERNAME; -import static com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.PrincipalStrategiesConstants.SUB; import java.util.HashMap; import java.util.List; @@ -19,6 +18,7 @@ import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; import com.decathlon.idp_core.domain.model.principal.PrincipalKind; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.AuthenticationProperties; +import com.decathlon.idp_core.infrastructure.adapters.api.exception.MissingPrincipalIdentifierException; import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractionStrategy; /// Strategy for extracting principal information from OAuth2 and OpenID Connect (OIDC) users. @@ -62,19 +62,18 @@ private PrincipalInfo extractFromOAuth2User(OAuth2User oauth2User) { Map claimMappings = authProperties.userClaimMappings(); - // Standard OAuth2 user extraction using dynamic claims - String subClaim = claimMappings.getOrDefault(SUB, SUB); - String sub = Optional.ofNullable(oauth2User.getAttribute(subClaim)).map(String::valueOf) - .orElse(oauth2User.getName()); + String identifier = Optional.ofNullable(oauth2User.getName()).filter(value -> !value.isBlank()) + .orElseThrow(() -> new MissingPrincipalIdentifierException("name")); String preferredUsernameClaim = claimMappings.getOrDefault(PREFERRED_USERNAME, PREFERRED_USERNAME); - String identifier = Optional.ofNullable(oauth2User.getAttribute(preferredUsernameClaim)) - .map(String::valueOf).filter(value -> !value.isBlank()).orElse(sub); + Optional preferredUsername = Optional + .ofNullable(oauth2User.getAttribute(preferredUsernameClaim)).map(String::valueOf) + .filter(value -> !value.isBlank()); String nameClaim = claimMappings.getOrDefault(NAME, NAME); String name = Optional.ofNullable(oauth2User.getAttribute(nameClaim)).map(String::valueOf) - .filter(value -> !value.isBlank()).orElse(identifier); + .filter(value -> !value.isBlank()).or(() -> preferredUsername).orElse(identifier); Map attributes = new HashMap<>(); String emailClaim = claimMappings.getOrDefault(EMAIL, EMAIL); @@ -94,11 +93,12 @@ private PrincipalInfo extractFromOAuth2User(OAuth2User oauth2User) { /// is accurately extracted from OIDC claims, which are standardized across /// compliant identity providers. private PrincipalInfo extractFromOidcUser(OidcUser oidcUser) { - String sub = oidcUser.getSubject(); - String identifier = Optional.ofNullable(oidcUser.getPreferredUsername()).orElse(sub); + String identifier = Optional.ofNullable(oidcUser.getSubject()).filter(value -> !value.isBlank()) + .orElseThrow(() -> new MissingPrincipalIdentifierException("sub")); String name = Optional.ofNullable(oidcUser.getFullName()) - .or(() -> Optional.ofNullable(oidcUser.getGivenName())).orElse(identifier); + .or(() -> Optional.ofNullable(oidcUser.getGivenName())) + .or(() -> Optional.ofNullable(oidcUser.getPreferredUsername())).orElse(identifier); Map attributes = new HashMap<>(); Optional.ofNullable(oidcUser.getEmail()).map(String::valueOf) diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltEngine.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltEngine.java index 9bb53104..7a41bb21 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltEngine.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltEngine.java @@ -1,9 +1,16 @@ package com.decathlon.idp_core.infrastructure.adapters.entity_mapping.jslt; import java.util.Collection; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.springframework.stereotype.Component; +import com.decathlon.idp_core.domain.constant.JsltConstraints; import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingJsltErrorException; import com.decathlon.idp_core.infrastructure.adapters.entity_mapping.engine.ExpressionEngine; import com.fasterxml.jackson.databind.JsonNode; @@ -11,9 +18,17 @@ import com.schibsted.spt.data.jslt.Function; import com.schibsted.spt.data.jslt.Parser; +/// JSLT expression engine with DoS protections: expression length is bounded and +/// each evaluation runs under a timeout. +/// +/// JSLT does not honor thread interruption, so a timed-out evaluation is +/// cancelled and may keep running on its virtual thread until it finishes. @Component public class JsltEngine implements ExpressionEngine { + private static final ExecutorService EVALUATION_EXECUTOR = Executors + .newVirtualThreadPerTaskExecutor(); + private final Collection customFunctions; // Creates a JSLT engine with the custom functions discovered by Spring. @@ -28,6 +43,7 @@ public Expression compile(String expression) { @Override public void validateExpression(String expression) { + checkExpressionLength(expression); try { compile(expression); } catch (Exception exception) { @@ -35,12 +51,43 @@ public void validateExpression(String expression) { } } + /// Evaluates a JSLT transformation expression against an input JSON payload. + /// + /// Validates that the expression does not exceed + /// [JsltConstraints#MAX_EXPRESSION_LENGTH] and executes the evaluation + /// asynchronously within a configured timeout + /// ([JsltConstraints#EVALUATION_TIMEOUT_MS] ms). If the execution exceeds the + /// timeout, fails, or is interrupted, the underlying task is cancelled. + /// + /// @param expression the JSLT expression to compile and apply + /// @param payload the target [JsonNode] payload to be transformed + /// @return the transformed [JsonNode] result + /// @throws EntityDynamicMappingJsltErrorException if the expression length + /// exceeds the maximum limit, the evaluation times out, compilation or + /// execution fails, or the operation is interrupted @Override public JsonNode evaluate(String expression, JsonNode payload) { + checkExpressionLength(expression); + Future future = EVALUATION_EXECUTOR.submit(() -> compile(expression).apply(payload)); try { - return compile(expression).apply(payload); - } catch (Exception exception) { - throw new EntityDynamicMappingJsltErrorException(exception.getMessage()); + return future.get(JsltConstraints.EVALUATION_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (TimeoutException _) { + future.cancel(true); + throw new EntityDynamicMappingJsltErrorException( + "JSLT evaluation exceeded timeout of " + JsltConstraints.EVALUATION_TIMEOUT_MS + " ms"); + } catch (ExecutionException exception) { + throw new EntityDynamicMappingJsltErrorException(exception.getCause().getMessage()); + } catch (InterruptedException _) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw new EntityDynamicMappingJsltErrorException("JSLT evaluation was interrupted"); + } + } + + private void checkExpressionLength(String expression) { + if (expression != null && expression.length() > JsltConstraints.MAX_EXPRESSION_LENGTH) { + throw new EntityDynamicMappingJsltErrorException("JSLT expression exceeds maximum length of " + + JsltConstraints.MAX_EXPRESSION_LENGTH + " characters"); } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltMappingEngineAdapter.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltMappingEngineAdapter.java index 4086832d..00141bdd 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltMappingEngineAdapter.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltMappingEngineAdapter.java @@ -1,5 +1,7 @@ package com.decathlon.idp_core.infrastructure.adapters.entity_mapping.jslt; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -10,6 +12,7 @@ import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; +import com.decathlon.idp_core.domain.constant.JsltConstraints; import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingConfigurationException; import com.decathlon.idp_core.domain.model.entity.Entity; import com.decathlon.idp_core.domain.model.entity.Property; @@ -17,7 +20,9 @@ import com.decathlon.idp_core.domain.model.entity_mapping.EntityDynamicMapping; import com.decathlon.idp_core.domain.model.entity_mapping.RelationMapping; import com.decathlon.idp_core.domain.port.MappingEnginePort; +import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -216,12 +221,52 @@ public Map extractProperties(String rawPayload, .collect(Collectors.toUnmodifiableMap(Property::name, Property::value)); } - /// Parses raw JSON and translates parsing failures to a domain exception. + /// Enforces payload limits, then parses raw JSON and translates parsing + /// failures + /// to a domain exception. Size and depth are checked before the tree is built + /// so + /// oversized or deeply nested input is rejected cheaply. private JsonNode parsePayload(String rawPayload) { + checkPayloadSize(rawPayload); + checkJsonDepth(rawPayload); try { return objectMapper.readTree(rawPayload); } catch (JsonProcessingException e) { throw new EntityDynamicMappingConfigurationException("Failed to parse JSON payload", e); } } + + /// Rejects payloads whose UTF-8 encoding exceeds the configured maximum size. + private void checkPayloadSize(String rawPayload) { + if (rawPayload != null + && rawPayload.getBytes(StandardCharsets.UTF_8).length > JsltConstraints.MAX_PAYLOAD_BYTES) { + throw new EntityDynamicMappingConfigurationException( + "JSON payload exceeds maximum size of " + JsltConstraints.MAX_PAYLOAD_BYTES + " bytes"); + } + } + + /// Streams over the payload tokens and rejects nesting deeper than the + /// configured + /// maximum, without materializing the tree. + private void checkJsonDepth(String rawPayload) { + if (rawPayload == null) { + return; + } + try (JsonParser parser = objectMapper.getFactory().createParser(rawPayload)) { + int depth = 0; + for (JsonToken token = parser.nextToken(); token != null; token = parser.nextToken()) { + if (token.isStructStart()) { + depth++; + if (depth > JsltConstraints.MAX_JSON_DEPTH) { + throw new EntityDynamicMappingConfigurationException( + "JSON payload exceeds maximum depth of " + JsltConstraints.MAX_JSON_DEPTH); + } + } else if (token.isStructEnd()) { + depth--; + } + } + } catch (IOException e) { + throw new EntityDynamicMappingConfigurationException("Failed to parse JSON payload", e); + } + } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/configuration/IngestionConstants.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/configuration/IngestionConstants.java index da294999..59ac2035 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/configuration/IngestionConstants.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/configuration/IngestionConstants.java @@ -1,12 +1,9 @@ package com.decathlon.idp_core.infrastructure.adapters.ingestion.configuration; -/** - * Shared constants for the ingestion infrastructure adapter. - * - *

- * Centralizing these values avoids duplicated literals across route - * configuration, processors, and exception mapping. - */ +/// Shared constants for the ingestion infrastructure adapter. +/// +/// Centralizing these values avoids duplicated literals across route +/// configuration, processors, and exception mapping. public final class IngestionConstants { public static final String CONNECTOR_IDENTIFIER_PROPERTY = "connectorIdentifier"; diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/exception_handler/WebhookExceptionHandlerHelper.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/exception_handler/WebhookExceptionHandlerHelper.java index dccca106..710aec6c 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/exception_handler/WebhookExceptionHandlerHelper.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/exception_handler/WebhookExceptionHandlerHelper.java @@ -1,19 +1,22 @@ package com.decathlon.idp_core.infrastructure.adapters.ingestion.exception_handler; -import static com.decathlon.idp_core.infrastructure.adapters.ingestion.configuration.IngestionConstants.APPLICATION_JSON; import static com.decathlon.idp_core.infrastructure.adapters.ingestion.configuration.IngestionConstants.CONNECTOR_IDENTIFIER_PROPERTY; import static com.decathlon.idp_core.infrastructure.adapters.ingestion.configuration.IngestionConstants.UNKNOWN_VALUE; +import java.net.URI; +import java.time.Instant; + import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.Message; import org.apache.camel.builder.RouteBuilder; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ProblemDetail; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import com.decathlon.idp_core.domain.exception.webhook.WebhookAuthenticationException; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -32,6 +35,7 @@ public class WebhookExceptionHandlerHelper { private static final String STRUCTURED_LOG_MESSAGE = "webhook_ingestion_error code={} status={} connector_identifier={} exception_type={} message={}"; + private static final String PROBLEM_INSTANCE_PROPERTY = "webhookProblemInstance"; private final ObjectMapper objectMapper; @@ -45,8 +49,9 @@ public void registerHandler(RouteBuilder routeBuilder, public void registerHandler(RouteBuilder routeBuilder, Class exceptionType, WebhookErrorCode error, boolean exposeExceptionMessage) { - routeBuilder.onException(exceptionType).handled(true).removeHeaders("*") - .process(exchange -> setJsonErrorResponse(exchange, error, exposeExceptionMessage)) + routeBuilder.onException(exceptionType).handled(true).process(this::captureRequestUri) + .removeHeaders("*") + .process(exchange -> setProblemDetailResponse(exchange, error, exposeExceptionMessage)) .process(exchange -> logHandledException(exchange, error.logLevel(), error.code(), error.httpStatus().value())); } @@ -66,15 +71,48 @@ public void registerHandlers(RouteBuilder routeBuilder, WebhookErrorCode error, } } - private void setJsonErrorResponse(Exchange exchange, WebhookErrorCode error, + private void setProblemDetailResponse(Exchange exchange, WebhookErrorCode error, boolean exposeExceptionMessage) throws JsonProcessingException { HttpStatus httpStatus = error.httpStatus(); String errorDescription = resolveErrorDescription(exchange, error, exposeExceptionMessage); - ErrorResponse errorResponse = new ErrorResponse(error.code(), errorDescription); + ProblemDetail problemDetail = ProblemDetail.forStatus(httpStatus); + problemDetail.setType(URI.create("about:blank")); + problemDetail.setTitle(httpStatus.getReasonPhrase()); + problemDetail.setDetail(errorDescription); + String requestUri = exchange.getProperty(PROBLEM_INSTANCE_PROPERTY, String.class); + if (StringUtils.hasText(requestUri)) { + problemDetail.setInstance(URI.create(requestUri)); + } + problemDetail.setProperty("error", error.code()); + problemDetail.setProperty("error_description", errorDescription); + problemDetail.setProperty("timestamp", Instant.now().toString()); + + var responseBody = objectMapper.createObjectNode(); + responseBody.put("type", problemDetail.getType().toString()); + responseBody.put("title", problemDetail.getTitle()); + responseBody.put("status", problemDetail.getStatus()); + responseBody.put("detail", problemDetail.getDetail()); + if (problemDetail.getInstance() != null) { + responseBody.put("instance", problemDetail.getInstance().toString()); + } + problemDetail.getProperties() + .forEach((name, value) -> responseBody.set(name, objectMapper.valueToTree(value))); + Message message = exchange.getMessage(); message.setHeader(Exchange.HTTP_RESPONSE_CODE, httpStatus.value()); - message.setHeader(Exchange.CONTENT_TYPE, APPLICATION_JSON); - message.setBody(objectMapper.writeValueAsString(errorResponse)); + message.setHeader(Exchange.CONTENT_TYPE, MediaType.APPLICATION_PROBLEM_JSON_VALUE); + message.setBody(objectMapper.writeValueAsString(responseBody)); + } + + private void captureRequestUri(Exchange exchange) { + Message message = exchange.getMessage(); + String requestUri = message.getHeader(Exchange.HTTP_PATH, String.class); + if (!StringUtils.hasText(requestUri)) { + requestUri = message.getHeader(Exchange.HTTP_URI, String.class); + } + if (StringUtils.hasText(requestUri)) { + exchange.setProperty(PROBLEM_INSTANCE_PROPERTY, requestUri); + } } private String resolveErrorDescription(Exchange exchange, WebhookErrorCode error, diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/IngestionProcessor.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/IngestionProcessor.java index 3b6c6cb2..42273189 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/IngestionProcessor.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/IngestionProcessor.java @@ -1,17 +1,21 @@ package com.decathlon.idp_core.infrastructure.adapters.ingestion.processor; import java.util.List; +import java.util.Set; import org.springframework.stereotype.Component; import com.decathlon.idp_core.domain.exception.entity.EntityNotFoundException; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; import com.decathlon.idp_core.domain.model.entity.Entity; import com.decathlon.idp_core.domain.model.entity.EntityPatch; +import com.decathlon.idp_core.domain.model.entity.Property; import com.decathlon.idp_core.domain.model.entity_mapping.EntityDynamicMapping; import com.decathlon.idp_core.domain.model.inbound_connectors.webhook.WebhookConnector; import com.decathlon.idp_core.domain.port.MappingEnginePort; import com.decathlon.idp_core.domain.service.entity.EntityService; +import io.opentelemetry.api.trace.Span; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -20,6 +24,10 @@ @RequiredArgsConstructor public class IngestionProcessor { + private static final String SPAN_ATTRIBUTE_WEBHOOK_IDENTIFIER = "idp.webhook.identifier"; + private static final Set PROTECTED_PRINCIPAL_PROPERTIES = Set.of("kind", "is_admin", + "is_idp_user"); + private final MappingEnginePort mappingEngine; private final EntityService entityService; @@ -37,11 +45,12 @@ public class IngestionProcessor { /// @param webhookConnectorConfiguration the connector with mapping definitions /// @param payload the raw JSON payload from the webhook public void ingest(String payload, WebhookConnector webhookConnectorConfiguration) { - log.info("Starting ingestion for webhook connector: {}", - webhookConnectorConfiguration.identifier()); + String connectorIdentifier = webhookConnectorConfiguration.identifier(); + Span.current().setAttribute(SPAN_ATTRIBUTE_WEBHOOK_IDENTIFIER, connectorIdentifier); + + log.info("Starting ingestion for webhook connector: {}", connectorIdentifier); webhookConnectorConfiguration.mappings().forEach(mapping -> applyMapping(payload, mapping)); - log.info("Completed ingestion for webhook connector: {}", - webhookConnectorConfiguration.identifier()); + log.info("Completed ingestion for webhook connector: {}", connectorIdentifier); } /// Applies a single mapping to the payload and persists the resulting entity. @@ -52,14 +61,14 @@ public void ingest(String payload, WebhookConnector webhookConnectorConfiguratio /// @param mapping the mapping definition to apply private void applyMapping(String payload, EntityDynamicMapping mapping) { log.debug("Applying mapping for template: {} with action: {}", mapping.identifier(), mapping.action()); - Entity entity = mappingEngine.mapToEntity(payload, mapping); + Entity mappedEntity = mappingEngine.mapToEntity(payload, mapping); - if (entity == null) { + if (mappedEntity == null) { log.debug("Mapping filter excluded payload for template: {}", mapping.entityTemplateIdentifier()); return; } - + Entity entity = protectPrincipalProperties(mappedEntity); switch (mapping.action()) { case UPDATE_ENTITY -> handleUpdate(entity); case UPDATE_PROPERTIES -> handleUpdateProperties(entity); @@ -72,6 +81,16 @@ private void applyMapping(String payload, EntityDynamicMapping mapping) { mapping.action(), entity.identifier(), entity.templateIdentifier()); } + private Entity protectPrincipalProperties(Entity entity) { + if (!AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER.equals(entity.templateIdentifier())) { + return entity; + } + List properties = entity.properties().stream() + .filter(property -> !PROTECTED_PRINCIPAL_PROPERTIES.contains(property.name())).toList(); + return new Entity(entity.id(), entity.templateIdentifier(), entity.name(), entity.identifier(), + properties, entity.relations()); + } + /// Handles the Update action for an entity. /// /// If the entity exists, it is patched with the new data. If the entity does diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/SecurityProcessor.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/SecurityProcessor.java index bed34cd3..104f4ea4 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/SecurityProcessor.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/SecurityProcessor.java @@ -12,6 +12,7 @@ import com.decathlon.idp_core.infrastructure.adapters.ingestion.exception.WebhookSecurityException; import com.decathlon.idp_core.infrastructure.adapters.ingestion.security.WebhookRequestAuthenticator; +import io.opentelemetry.api.trace.Span; import lombok.extern.slf4j.Slf4j; @Component @@ -19,6 +20,9 @@ public class SecurityProcessor { private static final String WEBHOOK_AUTHENTICATION_FAILED_MESSAGE = "Webhook authentication failed"; + private static final String SPAN_ATTRIBUTE_WEBHOOK_IDENTIFIER = "idp.webhook.identifier"; + private static final String SPAN_ATTRIBUTE_SECURITY_RESULT = "idp.webhook.security.result"; + private static final String RESULT_SUCCESS = "SUCCESS"; private final List strategies; @@ -28,24 +32,34 @@ public SecurityProcessor(List strategies) { public void validate(Map headers, byte[] rawPayload, WebhookConnector webhookConnector) { + String webhookIdentifier = webhookConnector.identifier(); + Span.current().setAttribute(SPAN_ATTRIBUTE_WEBHOOK_IDENTIFIER, webhookIdentifier); + WebhookSecurity security = webhookConnector.security(); if (security == null || security.type() == WebhookSecurityType.NONE) { + Span.current().setAttribute(SPAN_ATTRIBUTE_SECURITY_RESULT, RESULT_SUCCESS); return; } - WebhookSecurityStrategy strategy = strategies.stream() - .filter(candidate -> candidate.supports(security.type())).findFirst() - .orElseThrow(() -> new WebhookSecurityException(WEBHOOK_AUTHENTICATION_FAILED_MESSAGE)); + try { + WebhookSecurityStrategy strategy = strategies.stream() + .filter(candidate -> candidate.supports(security.type())).findFirst() + .orElseThrow(() -> new WebhookSecurityException(WEBHOOK_AUTHENTICATION_FAILED_MESSAGE)); - if (!(strategy instanceof WebhookRequestAuthenticator authenticator)) { - throw new WebhookSecurityException(WEBHOOK_AUTHENTICATION_FAILED_MESSAGE); - } + if (!(strategy instanceof WebhookRequestAuthenticator authenticator)) { + throw new WebhookSecurityException(WEBHOOK_AUTHENTICATION_FAILED_MESSAGE); + } - authenticator.validateRequest(headers, rawPayload == null ? new byte[0] : rawPayload, - security.config()); + authenticator.validateRequest(headers, rawPayload == null ? new byte[0] : rawPayload, + security.config()); - log.debug("Webhook security validation passed for connector '{}' with strategy '{}'.", - webhookConnector.identifier(), security.type()); + Span.current().setAttribute(SPAN_ATTRIBUTE_SECURITY_RESULT, RESULT_SUCCESS); + log.debug("Webhook security validation passed for connector '{}' with strategy '{}'.", + webhookIdentifier, security.type()); + } catch (RuntimeException exception) { + Span.current().setAttribute(SPAN_ATTRIBUTE_SECURITY_RESULT, "REJECTED"); + throw exception; + } } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/JwtBearerSecurityValidator.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/JwtBearerSecurityValidator.java index 466e1d38..2ac0f026 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/JwtBearerSecurityValidator.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/JwtBearerSecurityValidator.java @@ -21,6 +21,9 @@ import com.decathlon.idp_core.infrastructure.adapters.ingestion.exception.WebhookAuthForbiddenException; import com.decathlon.idp_core.infrastructure.adapters.ingestion.exception.WebhookAuthUnauthorizedException; +import lombok.extern.slf4j.Slf4j; + +@Slf4j @Component public class JwtBearerSecurityValidator implements @@ -37,8 +40,10 @@ public class JwtBearerSecurityValidator private static final String KEY_EXPECTED_AUDIENCE_CAMEL_CASE = "expectedAudience"; private static final String BEARER_PREFIX = "Bearer "; - private static final String CLIENT_CLAIM_AZP = "azp"; - private static final String CLIENT_CLAIM_EMAIL = "email"; + private static final String CALLER_RESULT_ACCEPTED = "ACCEPTED"; + private static final String CALLER_RESULT_REJECTED = "REJECTED"; + private static final String CLAIM_EMAIL = "email"; + private static final int MAX_LOGGED_CALLER_LENGTH = 128; private final WebhookJwtDecoderProvider jwtDecoderProvider; private final Set allowedJwksHosts; @@ -81,9 +86,9 @@ public void validateConfiguration(Map config) { "Invalid client_id_field for JWT_BEARER security: runtime environment references are not supported"); } - if (!CLIENT_CLAIM_AZP.equals(clientIdField) && !CLIENT_CLAIM_EMAIL.equals(clientIdField)) { + if (!StringUtils.hasText(clientIdField)) { throw new WebhookSecurityConfigurationException( - "Invalid client_id_field for JWT_BEARER security: must be 'azp' (Client ID) or 'email' (Service Account)"); + "Invalid client_id_field for JWT_BEARER security: must be a non-empty claim name"); } String clientIdValues = WebhookSecurityConfigurationUtils.required(config, @@ -137,18 +142,52 @@ public void validateRequest(Map headers, byte[] rawPayload, String actualCallerIdentity = jwt.getClaimAsString(clientIdField); if (!StringUtils.hasText(actualCallerIdentity)) { - throw new WebhookAuthForbiddenException("JWT missing required claim: " + clientIdField); + logCallerOutcome(clientIdField, null, CALLER_RESULT_REJECTED); + throw new WebhookAuthUnauthorizedException("JWT missing required claim: " + clientIdField); } Set allowedIdentities = parseAllowedClientIdValues(clientIdValues); if (!allowedIdentities.contains(actualCallerIdentity)) { + logCallerOutcome(clientIdField, actualCallerIdentity, CALLER_RESULT_REJECTED); throw new WebhookAuthForbiddenException( "JWT client or service account identifier was rejected"); } if (StringUtils.hasText(optionalExpectedAudience)) { - validateAudienceClaim(jwt, optionalExpectedAudience); + try { + validateAudienceClaim(jwt, optionalExpectedAudience); + } catch (WebhookAuthForbiddenException exception) { + logCallerOutcome(clientIdField, actualCallerIdentity, CALLER_RESULT_REJECTED); + throw exception; + } + } + + logCallerOutcome(clientIdField, actualCallerIdentity, CALLER_RESULT_ACCEPTED); + } + + /// Logs the caller identity and the validation outcome. The token itself is + /// never logged. The caller value is omitted when the identifying claim is + /// `email`, because an email address is personal data. + private void logCallerOutcome(String claimName, String caller, String result) { + String loggedCaller = resolveLoggedCaller(claimName, caller); + if (CALLER_RESULT_ACCEPTED.equals(result)) { + log.info("webhook_jwt_caller claim={} caller={} result={}", claimName, loggedCaller, result); + } else { + log.warn("webhook_jwt_caller claim={} caller={} result={}", claimName, loggedCaller, result); + } + } + + private String resolveLoggedCaller(String claimName, String caller) { + if (caller == null) { + return ""; + } + if (CLAIM_EMAIL.equalsIgnoreCase(claimName)) { + return ""; } + String sanitized = caller.replaceAll("\\p{Cntrl}", "_"); + return sanitized.length() > MAX_LOGGED_CALLER_LENGTH + ? sanitized.substring(0, MAX_LOGGED_CALLER_LENGTH) + : sanitized; } /// Validates the jwks_uri to prevent SSRF attacks. @@ -220,8 +259,8 @@ private String resolveRequiredClientIdField(Map config) { } catch (WebhookSecurityConfigurationException _) { throw new WebhookSecurityConfigurationException( "Missing required JWT_BEARER config key. Expected one of: client_id_field, clientIdField. " - + "Allowed values: 'azp' (Client ID) or 'email' (Service Account). " - + "Example: \"client_id_field\": \"email\""); + + "Value must be a non-empty JWT claim name (for example 'client_id', 'azp', 'email'). " + + "Example: \"client_id_field\": \"client_id\""); } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookSecurityConfiguration.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookSecurityConfiguration.java index ad63954f..2506e92d 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookSecurityConfiguration.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookSecurityConfiguration.java @@ -1,10 +1,19 @@ package com.decathlon.idp_core.infrastructure.adapters.ingestion.security; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/// Enables binding of webhook security configuration properties. +import com.decathlon.idp_core.domain.model.inbound_connectors.webhook.WebhookSecurityValidationPolicy; + +/// Enables binding and mapping of webhook security configuration properties. @Configuration @EnableConfigurationProperties(WebhookSecurityProperties.class) public class WebhookSecurityConfiguration { + + @Bean + public WebhookSecurityValidationPolicy webhookSecurityValidationPolicy( + WebhookSecurityProperties webhookSecurityProperties) { + return new WebhookSecurityValidationPolicy(webhookSecurityProperties.allowNone()); + } } diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookSecurityProperties.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookSecurityProperties.java index 11d44a4c..25ab7a01 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookSecurityProperties.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookSecurityProperties.java @@ -4,13 +4,15 @@ import java.util.Set; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; -/// Externalized JWKS security configuration for webhook authentication. +/// Externalized security configuration for webhook authentication. /// /// The `allowedJwksHosts` allow-list is intentionally small and explicit so teams can permit /// trusted issuers without hardcoding hostnames in the validator. @ConfigurationProperties(prefix = "idp.security.webhook") -public record WebhookSecurityProperties(Set allowedJwksHosts) { +public record WebhookSecurityProperties(Set allowedJwksHosts, + @DefaultValue("false") boolean allowNone) { public WebhookSecurityProperties { allowedJwksHosts = allowedJwksHosts == null diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/persistence/PostgresEntityAdapter.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/persistence/PostgresEntityAdapter.java index a9bfb2b4..e35a4f71 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/persistence/PostgresEntityAdapter.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/persistence/PostgresEntityAdapter.java @@ -11,7 +11,6 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Component; @@ -22,7 +21,9 @@ import com.decathlon.idp_core.domain.model.search.PaginatedResult; import com.decathlon.idp_core.domain.model.search.PaginationCriteria; import com.decathlon.idp_core.domain.model.search.SearchFilterNode; +import com.decathlon.idp_core.domain.model.search.SortCriteria; import com.decathlon.idp_core.domain.port.EntityRepositoryPort; +import com.decathlon.idp_core.domain.service.search.SortParameterParser; import com.decathlon.idp_core.infrastructure.adapters.persistence.mapper.EntityPersistenceMapper; import com.decathlon.idp_core.infrastructure.adapters.persistence.model.entity.EntityJpaEntity; import com.decathlon.idp_core.infrastructure.adapters.persistence.repository.JpaEntityRepository; @@ -138,28 +139,17 @@ public PaginatedResult search(SearchFilterNode filter, String query, } private Pageable buildPageable(PaginationCriteria criteria) { - if (criteria.sort() == null || criteria.sort().isBlank()) { - return PageRequest.of(criteria.page(), criteria.size()); - } - - Sort sort = parseSortExpression(criteria.sort()); - return PageRequest.of(criteria.page(), criteria.size(), sort); + return SortParameterParser.parse(criteria.sort()) + .map(sortCriteria -> PageRequest.of(criteria.page(), criteria.size(), + toSpringSort(sortCriteria))) + .orElseGet(() -> PageRequest.of(criteria.page(), criteria.size())); } - private Sort parseSortExpression(String sortExpression) { - String[] parts = sortExpression.split(":"); - String property = parts[0].trim(); - - if (parts.length == 1) { - return Sort.by(Direction.ASC, property); - } - - String direction = parts[1].trim().toLowerCase(); - return switch (direction) { - case "asc" -> Sort.by(Direction.ASC, property); - case "desc" -> Sort.by(Direction.DESC, property); - default -> Sort.by(Direction.ASC, property); - }; + private Sort toSpringSort(SortCriteria criteria) { + Sort.Direction direction = criteria.direction() == SortCriteria.Direction.ASC + ? Sort.Direction.ASC + : Sort.Direction.DESC; + return Sort.by(direction, criteria.field()); } public List findEntitiesRelated(String targetIdentifier) { diff --git a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/UserIdentityProviderHolder.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/UserIdentityProviderHolder.java index e1ef17b2..7e47cbb1 100644 --- a/src/main/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/UserIdentityProviderHolder.java +++ b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/UserIdentityProviderHolder.java @@ -4,20 +4,18 @@ import jakarta.annotation.PostConstruct; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.decathlon.idp_core.infrastructure.adapters.api.auth.UserIdentityProvider; +import com.decathlon.idp_core.domain.port.audit.AuditIdentityProviderPort; @Component public class UserIdentityProviderHolder { - private static final AtomicReference userIdentityProvider = new AtomicReference<>(); + private static final AtomicReference userIdentityProvider = new AtomicReference<>(); - private final UserIdentityProvider injectedProvider; + private final AuditIdentityProviderPort injectedProvider; - @Autowired - UserIdentityProviderHolder(final UserIdentityProvider injectedProvider) { + UserIdentityProviderHolder(final AuditIdentityProviderPort injectedProvider) { this.injectedProvider = injectedProvider; } @@ -27,8 +25,8 @@ public class UserIdentityProviderHolder { /// initialized, which should not happen in normal operation. /// This design allows us to bridge the gap between Spring-managed beans and /// Hibernate's non-Spring-managed listeners. - public static UserIdentityProvider getUserIdentityProvider() { - UserIdentityProvider provider = userIdentityProvider.get(); + public static AuditIdentityProviderPort getUserIdentityProvider() { + AuditIdentityProviderPort provider = userIdentityProvider.get(); if (provider == null) { throw new IllegalStateException( "UserIdentityProviderHolder not initialized. Spring context may not be loaded."); diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml index 978d8674..8ab3c6eb 100644 --- a/src/main/resources/application-local.yml +++ b/src/main/resources/application-local.yml @@ -41,15 +41,31 @@ app: # ${app.idp-core-prefix-url}/login/oauth2/code/github in the OAuth app settings. idp-core-prefix-url: http://localhost:8084 security: + principal-provisioning: + mode: ${IDP_PRINCIPAL_PROVISIONING_MODE:LINK_ONLY} + authorization: + mode: GLOBAL + # Comma-separated immutable principal identifiers for emergency access, even before JIT provisioning. + global-principal-identifiers: ${IDP_SUPER_ADMIN_IDENTIFIER:},${IDP_PLATFORM_ADMIN_IDENTIFIER:} + # Optional human-access gate; when set, the named principal property must be true. + required-principal-property: ${IDP_REQUIRED_PRINCIPAL_PROPERTY:} authentication: jwt: + # Enable to take in custom JWT tokens for authentication in local development enabled: false oauth2-login: - enabled: true + enabled: false mock: enabled: false + principal-extraction: + human-indicator-claims: + - ${IDP_AUTH_JWT_HUMAN_INDICATOR_CLAIM:email} + human: + id-claim: ${IDP_AUTH_JWT_HUMAN_ID_CLAIM:email} + machine: + id-claim: ${IDP_AUTH_JWT_MACHINE_ID_CLAIM:client_id} + id-prefix: ${IDP_AUTH_JWT_MACHINE_ID_PREFIX:} user-claim-mappings: - sub: id preferred_username: login name: name email: email @@ -57,19 +73,15 @@ logging: level: # Application log level, defaults to INFO. Override per environment via LOG_LEVEL env var. com.decathlon: ${LOG_LEVEL:DEBUG} + com.decathlon.idp_core.infrastructure.adapters.api.auth: DEBUG # Suppresses noisy Spring context startup logs at WARN level. - org.springframework.context.support: WARN + org.springframework.context.support: DEBUG # Suppresses a specific repetitive bean registration delegate log line. org.springframework.context.support.PostProcessorRegistrationDelegate: ERROR org.hibernate.SQL: INFO org.hibernate.stat: WARN org.hibernate.type.descriptor.sql.BasicBinder: TRACE -camel: - component: - platform-http: - engine: "servlet" - management: tracing: enabled: false diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index a443a8ec..788a8d2d 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -111,6 +111,11 @@ springdoc: urls-primary-name: internal app: + relations: + # STRICT rejects unresolved targets; TOLERANT filters them from optional relations. + target-validation-mode: ${APP_RELATIONS_TARGET_VALIDATION_MODE:STRICT} + # Maximum number of items returned per page by search and listing endpoints. + max-page-size: ${MAX_PAGE_SIZE:500} ingestion: webhook: base-path: /webhooks @@ -118,24 +123,43 @@ app: # Base URL of this service, used to build self-referencing links. idp-core-prefix-url: ${IDP_CORE_PREFIX_URL} security: - roles: - # Baseline role assigned to all authenticated principals during V1 phase. - baseline-role: ${APP_SECURITY_ROLES_BASELINE_ROLE:*} + principal-provisioning: + mode: ${IDP_PRINCIPAL_PROVISIONING_MODE:LINK_ONLY} + authorization: + mode: GLOBAL + # Comma-separated immutable principal identifiers for emergency access + global-principal-identifiers: ${IDP_SUPER_ADMIN_IDENTIFIER:},${IDP_PLATFORM_ADMIN_IDENTIFIER:} + # Optional human-access gate; when set, the given boolean property in the user's Principal must be true. + required-principal-property: ${IDP_REQUIRED_PRINCIPAL_PROPERTY:} # Authentication configuration - externalized for multi-IdP support # See docs/src/concepts/authentication.md for comprehensive documentation authentication: jwt: enabled: true + # Expected `iss` claim. When set, tokens from any other issuer are rejected. + issuer-uri: ${OAUTH_ISSUER_URI:} + # Comma-separated accepted `aud` values. When set, a token must carry at least one of them, + # which rejects tokens issued by the same identity provider for other applications. + audiences: ${OAUTH_AUDIENCES:} api-key: enabled: false mock: enabled: false + # JWT kind-specific identifier claims and human-token indicators. + principal-extraction: + human-indicator-claims: + - ${IDP_AUTH_JWT_HUMAN_INDICATOR_CLAIM:email} + human: + id-claim: ${IDP_AUTH_JWT_HUMAN_ID_CLAIM:email} + machine: + id-claim: ${IDP_AUTH_JWT_MACHINE_ID_CLAIM:client_id} + id-prefix: ${IDP_AUTH_JWT_MACHINE_ID_PREFIX:} + # JWT claim mappings for different Identity Providers (Auth0, Keycloak, Azure AD, etc.) # See docs/src/concepts/authentication.md - JWT Claim Mappings section user-claim-mappings: - sub: sub preferred_username: preferred_username name: name email: email @@ -146,19 +170,7 @@ app: gty: gty service_name: service_name - # Service account detection - identify M2M vs. human user tokens - # See docs/src/concepts/authentication.md - Service Account Detection section - service-account-detection: - enabled: true - mode: legacy - definitive-claim-name: token_type - definitive-claim-value: m2m - # Simplified list binding. Overriding via env var requires a comma-separated string: - # export APP_SECURITY_AUTHENTICATION_SERVICE_ACCOUNT_DETECTION_LEGACY_FALLBACK_CLAIMS="grant_type,service_name,client_id" - legacy-fallback-claims: grant_type,service_name,client_id - # JIT Provisioning excluded paths - # Simplified list binding. Overriding via env var requires a comma-separated string: - # export APP_SECURITY_AUTHENTICATION_JIT_PROVISIONING_EXCLUDED_PATHS="/,/actuator/**,/swagger-ui/**,/swagger-ui.html,/v3/api-docs/**" + # JIT Provisioning excluded paths. Override with a comma-separated environment value. jit-provisioning-excluded-paths: /,/actuator/**,/swagger-ui/**,/swagger-ui.html,/v3/api-docs/** idp: @@ -167,6 +179,9 @@ idp: # Comma-separated allow-list for trusted JWKS hosts. # Example: ALLOWED_JWKS_HOSTS=github.com,auth.decathlon.com allowed-jwks-hosts: ${ALLOWED_JWKS_HOSTS:} + # Allows webhook connectors with security type NONE (unauthenticated). Disabled by default. + # Example: IDP_WEBHOOK_SECURITY_ALLOW_NONE=true + allow-none: ${IDP_WEBHOOK_SECURITY_ALLOW_NONE:false} logging: level: @@ -180,18 +195,34 @@ logging: management: tracing: - # Tracing is disabled by default and only enabled via environment variables (OTEL_TRACING_ENABLED). - enabled: false sampling: - probability: 1.0 # 100% des traces + # Fraction of traces kept (1.0 = 100%). Standard OTel variable. + probability: ${OTEL_TRACES_SAMPLER_ARG:0.1} + export: + enabled: ${OTEL_TRACING_ENABLED:false} + # Trace OTLP export lives under management.opentelemetry.tracing.export.otlp.* (see below). otlp: + metrics: + export: + # Metrics export is opt-in. Signal-specific variables win over the generic ones. + url: ${OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:${OTEL_EXPORTER_OTLP_ENDPOINT:http://localhost:4318}/v1/metrics} + enabled: ${OTEL_METRICS_EXPORT_ENABLED:false} + transport: ${OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:${OTEL_EXPORTER_OTLP_PROTOCOL:http/protobuf}} + opentelemetry: tracing: - endpoint: ${OPEN_TELEMETRY_URL:""} - headers: - swagger: - enabled: ${APP_SECURITY_SWAGGER_ENABLED:true} - authorization: ${OPEN_TELEMETRY_TOKEN:""} + export: + otlp: + # Boot does not append /v1/traces itself: the full traces URL is required for HTTP. + endpoint: ${OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:${OTEL_EXPORTER_OTLP_ENDPOINT:http://localhost:4318}/v1/traces} + # Boot's transport enum only accepts http or grpc (not the OTel value http/protobuf). + transport: ${OTEL_EXPORTER_OTLP_TRACES_TRANSPORT:${OTEL_EXPORTER_OTLP_PROTOCOL:http}} + # Extra attributes (for example X-Datadog-Org, X-Backend) are set by the user + # through OTEL_RESOURCE_ATTRIBUTES, not hard-coded here. + resource-attributes: + deployment.environment: ${OTEL_ENV:local} + service.namespace: ${OTEL_SERVICE_NAMESPACE:idp-core} + service.name: ${OTEL_SERVICE_NAME:internal-developer-platform} endpoints: web: @@ -222,22 +253,7 @@ management: # Avoids leaking internal infrastructure info to unauthenticated callers. show-details: when_authorized + camel: - component: - platform-http: - engine: "servlet" - # Never expose the health "details" map (e.g. database product name/version, - # validation query, disk space paths). Only UP/DOWN status is shown. - show-details: never - # Still surface per-component status (e.g. db: UP/DOWN) so direct - # dependencies can be checked, without leaking their details. - show-components: always - health: - diskspace: - # DiskSpace is not a direct dependency and its free/threshold values - # are not relevant to consumers checking service health. - enabled: false - ssl: - # SSL certificate/chain info is internal infrastructure detail and - # must not be exposed via actuator. - enabled: false + opentelemetry2: + enabled: true diff --git a/src/main/resources/db/migration/V7_2__add_entity_relations_relation_id_index.sql b/src/main/resources/db/migration/V7_2__add_entity_relations_relation_id_index.sql new file mode 100644 index 00000000..c1161944 --- /dev/null +++ b/src/main/resources/db/migration/V7_2__add_entity_relations_relation_id_index.sql @@ -0,0 +1,6 @@ +-- Inbound graph traversal joins entity_relations on relation_id: +-- relation_target_entities (by target_entity_uuid) -> entity_relations (by relation_id) -> entity +-- The only indexes on entity_relations start with entity_id (primary key and idx_entity_relations_entity_id), +-- so that join fell back to a sequential scan for every node of the traversal frontier. +-- The recursive graph query runs on every entity list page, so the scan was paid on each list call. +CREATE INDEX IF NOT EXISTS idx_entity_relations_relation_id ON entity_relations (relation_id); diff --git a/src/test/java/com/decathlon/idp_core/AbstractIntegrationTest.java b/src/test/java/com/decathlon/idp_core/AbstractIntegrationTest.java index 4b68eced..756bd456 100644 --- a/src/test/java/com/decathlon/idp_core/AbstractIntegrationTest.java +++ b/src/test/java/com/decathlon/idp_core/AbstractIntegrationTest.java @@ -42,6 +42,7 @@ import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.reactive.function.client.WebClient; import org.testcontainers.containers.JdbcDatabaseContainer; @@ -76,6 +77,17 @@ public abstract class AbstractIntegrationTest { public static MockServerClient mockServerClient; + protected ResultMatcher problemDetailResponse(HttpStatus expectedStatus) { + return result -> { + jsonPath("$.title").value(expectedStatus.getReasonPhrase()).match(result); + jsonPath("$.status").value(expectedStatus.value()).match(result); + jsonPath("$.detail").isNotEmpty().match(result); + jsonPath("$.error").value(expectedStatus.name()).match(result); + jsonPath("$.error_description").isNotEmpty().match(result); + jsonPath("$.timestamp").isNotEmpty().match(result); + }; + } + protected AbstractIntegrationTest() { this.objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); @@ -184,7 +196,8 @@ public MvcResult postBadRequestAndAssertEquals(String path, String jsonBodyfileP .perform( MockMvcRequestBuilders.post(path).contentType(APPLICATION_JSON).accept(APPLICATION_JSON) .with(csrf()).content(getJsonTestFileContent(jsonBodyfilePath))) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()).andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) + .andExpect(jsonPath("$.error").value("BAD_REQUEST")) .andExpect(jsonPath("$.error_description").value(errorDescription)).andReturn(); } @@ -205,7 +218,8 @@ public MvcResult postBadRequestAndAssertContains(String path, String jsonBodyfil .perform( MockMvcRequestBuilders.post(path).contentType(APPLICATION_JSON).accept(APPLICATION_JSON) .with(csrf()).content(getJsonTestFileContent(jsonBodyfilePath))) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()).andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) + .andExpect(jsonPath("$.error").value("BAD_REQUEST")) .andExpect(jsonPath("$.error_description").value(containsString(errorDescription))) .andReturn(); @@ -226,7 +240,8 @@ public MvcResult postConflictAndAssertContains(String path, String jsonBodyfileP .perform( MockMvcRequestBuilders.post(path).contentType(APPLICATION_JSON).accept(APPLICATION_JSON) .with(csrf()).content(getJsonTestFileContent(jsonBodyfilePath))) - .andExpect(status().isConflict()).andExpect(jsonPath("$.error").value("CONFLICT")) + .andExpect(status().isConflict()).andExpect(problemDetailResponse(HttpStatus.CONFLICT)) + .andExpect(jsonPath("$.error").value("CONFLICT")) .andExpect(jsonPath("$.error_description").value(containsString(errorDescription))) .andReturn(); diff --git a/src/test/java/com/decathlon/idp_core/SecurityConfigurationTest.java b/src/test/java/com/decathlon/idp_core/SecurityConfigurationTest.java index 083083f6..0fbc8a6e 100644 --- a/src/test/java/com/decathlon/idp_core/SecurityConfigurationTest.java +++ b/src/test/java/com/decathlon/idp_core/SecurityConfigurationTest.java @@ -1,6 +1,7 @@ package com.decathlon.idp_core; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -14,7 +15,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.web.cors.CorsConfiguration; @@ -22,7 +22,6 @@ import com.decathlon.idp_core.infrastructure.adapters.api.configuration.CorsProperties; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.SecurityConfiguration; -import com.decathlon.idp_core.infrastructure.adapters.api.configuration.SecurityRoleProperties; @ExtendWith(MockitoExtension.class) class SecurityConfigurationTest { @@ -30,30 +29,22 @@ class SecurityConfigurationTest { @Mock private CorsProperties corsProperties; - @Mock - private SecurityRoleProperties securityRoleProperties; - @InjectMocks private SecurityConfiguration securityConfiguration; @Test - void jwtAuthenticationConverter_shouldAssignBaselineRole() { - // Arrange - when(securityRoleProperties.baselineRole()).thenReturn("ROLE_SUPER_ADMIN"); - + void jwtAuthenticationConverter_shouldNotAssignUniversalBaselineAuthority() { Jwt jwt = Jwt.withTokenValue("mock-jwt-token").header("alg", "none").claim("sub", "user-id-123") - .build(); + .claim("scope", "read write").build(); - // Act JwtAuthenticationConverter converter = securityConfiguration.jwtAuthenticationConverter(); var authenticationToken = converter.convert(jwt); - // Assert assertNotNull(authenticationToken, "Authentication token should not be null"); - assertTrue( - authenticationToken.getAuthorities() - .contains(new SimpleGrantedAuthority("ROLE_SUPER_ADMIN")), - "The configured baseline role must be assigned to the principal"); + assertTrue(authenticationToken.getAuthorities().stream() + .anyMatch(authority -> authority.getAuthority().equals("SCOPE_read"))); + assertFalse(authenticationToken.getAuthorities().stream() + .anyMatch(authority -> authority.getAuthority().equals("*"))); } @Test diff --git a/src/test/java/com/decathlon/idp_core/architecture/HexagonalArchitectureTest.java b/src/test/java/com/decathlon/idp_core/architecture/HexagonalArchitectureTest.java index 75efd01c..80cf6ac9 100644 --- a/src/test/java/com/decathlon/idp_core/architecture/HexagonalArchitectureTest.java +++ b/src/test/java/com/decathlon/idp_core/architecture/HexagonalArchitectureTest.java @@ -43,7 +43,7 @@ class HexagonalArchitectureTest { "org.springframework.web..", "org.springframework.data.jpa..", "org.springframework.data.repository..", "org.springframework.http..", "org.hibernate..", "org.mapstruct..", "com.schibsted..", "com.fasterxml.jackson..", "org.apache.kafka..", - "java.net.http..",}; + "java.net.http..", "org.springframework.beans.."}; // --------------------------------------------------------------------------------------- // 1. Hexagonal constraints diff --git a/src/test/java/com/decathlon/idp_core/architecture/MaintainabilityArchitectureTest.java b/src/test/java/com/decathlon/idp_core/architecture/MaintainabilityArchitectureTest.java index b5f63541..d7775fc9 100644 --- a/src/test/java/com/decathlon/idp_core/architecture/MaintainabilityArchitectureTest.java +++ b/src/test/java/com/decathlon/idp_core/architecture/MaintainabilityArchitectureTest.java @@ -7,6 +7,15 @@ import static com.tngtech.archunit.library.GeneralCodingRules.NO_CLASSES_SHOULD_USE_JAVA_UTIL_LOGGING; import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.decathlon.idp_core.infrastructure.adapters.api.handler.ApiExceptionHandler; +import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests; import com.tngtech.archunit.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; @@ -101,6 +110,36 @@ class MaintainabilityArchitectureTest { .resideInAnyPackage(EXCEPTION_PACKAGE, INFRASTRUCTURE_EXCEPTION_PACKAGE) .because("exceptions are either business (domain) or technical (infrastructure adapter)"); + /// Every domain runtime exception must have an HTTP status mapping. + @ArchTest + static void allDomainExceptionsAreRegistered(JavaClasses importedClasses) + throws NoSuchFieldException, IllegalAccessException { + Field statusByExceptionField = ApiExceptionHandler.class + .getDeclaredField("STATUS_BY_EXCEPTION"); + statusByExceptionField.setAccessible(true); + Map statusByException = (Map) statusByExceptionField.get(null); + Set mappedExceptionNames = new HashSet<>(); + for (Object key : statusByException.keySet()) { + if (key instanceof Class exceptionClass) { + mappedExceptionNames.add(exceptionClass.getName()); + } + } + + var unregistered = new ArrayList(); + for (JavaClass javaClass : importedClasses) { + if (javaClass.getPackageName().startsWith(BASE_PACKAGE + ".domain.exception") + && javaClass.isAssignableTo(RuntimeException.class) + && !mappedExceptionNames.contains(javaClass.getName())) { + unregistered.add(javaClass.getName()); + } + } + + if (!unregistered.isEmpty()) { + throw new AssertionError("The following domain exceptions are not registered in " + + "ApiExceptionHandler.STATUS_BY_EXCEPTION: " + unregistered); + } + } + // --------------------------------------------------------------------------------------- // 4. Naming & placement conventions // --------------------------------------------------------------------------------------- diff --git a/src/test/java/com/decathlon/idp_core/domain/service/authorization/GlobalAuthorizationServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/authorization/GlobalAuthorizationServiceTest.java new file mode 100644 index 00000000..b69fefa6 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/domain/service/authorization/GlobalAuthorizationServiceTest.java @@ -0,0 +1,367 @@ +package com.decathlon.idp_core.domain.service.authorization; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import com.decathlon.idp_core.domain.exception.authorization.PrincipalNotAuthorizedException; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationMode; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationRequest; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; +import com.decathlon.idp_core.domain.model.entity.Entity; +import com.decathlon.idp_core.domain.model.entity.Property; +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; +import com.decathlon.idp_core.domain.model.principal.PrincipalKind; + +class GlobalAuthorizationServiceTest { + + private static final String PRINCIPAL_IDENTIFIER = "platform-user"; + private static final String REQUIRED_PRINCIPAL_PROPERTY = "is_idp_user"; + private static final AuthorizationResource CATALOG = new AuthorizationResource("entity", + Optional.of("api-one"), Optional.of("api")); + private static final AuthorizationResource WEBHOOK_CONFIGURATION = new AuthorizationResource( + AuthorizationResource.INBOUND_WEBHOOK_CONFIGURATION, Optional.of("connector"), + Optional.empty()); + + private final GlobalAuthorizationService authorizationService = new GlobalAuthorizationService(); + private AuthorizationPolicy policy; + private PrincipalInfo humanPrincipal; + + @BeforeEach + void setUp() { + policy = new AuthorizationPolicy(AuthorizationMode.GLOBAL, Set.of("break-glass-user"), + Optional.of(REQUIRED_PRINCIPAL_PROPERTY)); + humanPrincipal = principal(PRINCIPAL_IDENTIFIER, PrincipalKind.HUMAN); + } + + @ParameterizedTest(name = "{1} {2} allowed={4}") + @MethodSource("authorizationMatrix") + void shouldApplyGlobalAuthorizationMatrix(PrincipalInfo principal, AuthorizationAction action, + AuthorizationResource resource, Optional principalEntity, boolean allowed) { + var request = request(principal, action, resource, principalEntity); + + if (allowed) { + assertThatCode(() -> authorizationService.authorize(request, policy)) + .doesNotThrowAnyException(); + } else { + assertThatThrownBy(() -> authorizationService.authorize(request, policy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + } + + private static Stream authorizationMatrix() { + AuthorizationResource entity = new AuthorizationResource("entity", Optional.of("item"), + Optional.of("service")); + AuthorizationResource template = new AuthorizationResource("entity_template", + Optional.of("service"), Optional.empty()); + AuthorizationResource entitySearch = new AuthorizationResource("entity_search", + Optional.empty(), Optional.empty()); + AuthorizationResource webhook = new AuthorizationResource( + AuthorizationResource.INBOUND_WEBHOOK_CONFIGURATION, Optional.of("hook"), Optional.empty()); + AuthorizationResource mapping = new AuthorizationResource("entity_dynamic_mapping", + Optional.of("mapping"), Optional.empty()); + AuthorizationResource audit = new AuthorizationResource("audit", Optional.empty(), + Optional.empty()); + AuthorizationResource principalResource = new AuthorizationResource("principal", + Optional.of("user"), Optional.empty()); + AuthorizationResource principalSelf = new AuthorizationResource( + AuthorizationResource.PRINCIPAL_SELF, Optional.empty(), Optional.empty()); + List readOnlyResources = List.of(entity, entitySearch, template, + principalSelf); + List deniedResources = List.of(webhook, mapping, audit, + principalResource); + List actions = List.of(AuthorizationAction.READ, + AuthorizationAction.CREATE, AuthorizationAction.UPDATE, AuthorizationAction.DELETE); + + PrincipalInfo human = principal("regular-human", PrincipalKind.HUMAN); + PrincipalInfo serviceAccount = principal("service-client", PrincipalKind.SERVICE_ACCOUNT); + PrincipalInfo admin = principal("catalog-admin", PrincipalKind.HUMAN); + Entity activeHuman = principalEntity(false, "true", "true"); + Entity inactiveHuman = principalEntity(false, "false", "false"); + Entity servicePrincipal = new Entity(UUID.randomUUID(), "principal", "Service", + "service-client", List.of(new Property(null, "kind", "SERVICE_ACCOUNT"), + new Property(null, "is_admin", "false")), + List.of()); + Entity adminPrincipal = new Entity(UUID.randomUUID(), "principal", "Admin", "catalog-admin", + List.of(new Property(null, "kind", "HUMAN"), new Property(null, "is_admin", "true")), + List.of()); + + Stream.Builder cases = Stream.builder(); + for (AuthorizationAction action : actions) { + for (AuthorizationResource resource : readOnlyResources) { + cases.add(Arguments.of(human, action, resource, Optional.of(activeHuman), + action == AuthorizationAction.READ)); + cases.add(Arguments.of(serviceAccount, action, resource, Optional.of(servicePrincipal), + action == AuthorizationAction.READ)); + cases.add(Arguments.of(admin, action, resource, Optional.of(adminPrincipal), true)); + } + for (AuthorizationResource resource : deniedResources) { + cases.add(Arguments.of(human, action, resource, Optional.of(activeHuman), false)); + cases.add( + Arguments.of(serviceAccount, action, resource, Optional.of(servicePrincipal), false)); + cases.add(Arguments.of(admin, action, resource, Optional.of(adminPrincipal), true)); + } + } + cases.add( + Arguments.of(human, AuthorizationAction.READ, entity, Optional.of(inactiveHuman), false)); + cases.add(Arguments.of(human, AuthorizationAction.READ, entity, Optional.empty(), false)); + return cases.build(); + } + + @Test + void shouldAllowBreakGlassPrincipalBeforeCheckingCatalogAdmin() { + var request = request(principal("break-glass-user", PrincipalKind.HUMAN), + AuthorizationAction.DELETE, CATALOG, Optional.empty()); + + assertThatCode(() -> authorizationService.authorize(request, policy)) + .doesNotThrowAnyException(); + } + + @Test + void shouldAllowPrincipalWithIsAdminSetToTrueForCrudExceptAuditWrites() { + for (AuthorizationAction action : crudActions()) { + var request = request(humanPrincipal, action, WEBHOOK_CONFIGURATION, + Optional.of(principalEntity("true"))); + + assertThatCode(() -> authorizationService.authorize(request, policy)) + .doesNotThrowAnyException(); + } + } + + @Test + void shouldAllowCatalogAdministratorForAllAuditActions() { + AuthorizationResource audit = new AuthorizationResource("audit", Optional.empty(), + Optional.empty()); + for (AuthorizationAction action : crudActions()) { + var request = request(humanPrincipal, action, audit, Optional.of(principalEntity("true"))); + + assertThatCode(() -> authorizationService.authorize(request, policy)) + .doesNotThrowAnyException(); + } + } + + @Test + void shouldAllowPlatformAdministratorToDeletePrincipalEntities() { + AuthorizationResource principalResource = new AuthorizationResource("entity", + Optional.of("subject-123"), Optional.of("principal")); + var request = request(humanPrincipal, AuthorizationAction.DELETE, principalResource, + Optional.of(principalEntity("true"))); + + assertThatCode(() -> authorizationService.authorize(request, policy)) + .doesNotThrowAnyException(); + } + + @Test + void shouldAllowServiceAccountReadsOnlyOnEntityAndTemplateResources() { + AuthorizationResource entityTemplate = new AuthorizationResource("entity_template", + Optional.of("api"), Optional.empty()); + for (AuthorizationResource resource : List.of(CATALOG, entityTemplate)) { + var request = request(serviceAccount(), AuthorizationAction.READ, resource, Optional.empty()); + assertThatCode(() -> authorizationService.authorize(request, policy)) + .doesNotThrowAnyException(); + } + + for (AuthorizationAction action : crudActions()) { + var request = request(serviceAccount(), action, WEBHOOK_CONFIGURATION, Optional.empty()); + assertThatThrownBy(() -> authorizationService.authorize(request, policy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + } + + @Test + void shouldRejectServiceAccountWritesToPrincipalRecordsAndTemplate() { + List protectedResources = List.of( + new AuthorizationResource("entity", Optional.of("subject-123"), + Optional.of(AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER)), + new AuthorizationResource("principal", Optional.of("subject-123"), Optional.empty()), + new AuthorizationResource("entity_template", + Optional.of(AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER), Optional.empty()), + new AuthorizationResource("entity_dynamic_mapping", Optional.of("principal-mapping"), + Optional.of(AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER)), + new AuthorizationResource(AuthorizationResource.INBOUND_WEBHOOK_CONFIGURATION, + Optional.of("webhook"), + Optional.of(AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER))); + + for (AuthorizationResource resource : protectedResources) { + for (AuthorizationAction action : List.of(AuthorizationAction.CREATE, + AuthorizationAction.UPDATE, AuthorizationAction.DELETE)) { + var request = request(serviceAccount(), action, resource, Optional.empty()); + assertThatThrownBy(() -> authorizationService.authorize(request, policy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + } + } + + @Test + void shouldRejectHumanAndServiceAccountAccessToNonReadOnlyResources() { + for (AuthorizationResource resource : List.of(WEBHOOK_CONFIGURATION, + new AuthorizationResource("entity_dynamic_mapping", Optional.of("mapping"), + Optional.empty()), + new AuthorizationResource("audit", Optional.empty(), Optional.empty()))) { + for (PrincipalInfo principal : List.of(humanPrincipal, serviceAccount())) { + var request = request(principal, AuthorizationAction.READ, resource, + Optional.of(principalEntity("false", "true"))); + assertThatThrownBy(() -> authorizationService.authorize(request, policy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + } + } + + @Test + void shouldAllowBreakGlassPrincipalToManagePrincipalRecordsWithoutCatalogEntity() { + AuthorizationResource principalResource = new AuthorizationResource("entity", + Optional.of("subject-123"), Optional.of("principal")); + var request = request(principal("break-glass-user", PrincipalKind.HUMAN), + AuthorizationAction.UPDATE, principalResource, Optional.empty()); + + assertThatCode(() -> authorizationService.authorize(request, policy)) + .doesNotThrowAnyException(); + } + + @Test + void shouldAllowReadOperationsForNonAdminHumans() { + var request = request(humanPrincipal, AuthorizationAction.READ, CATALOG, + Optional.of(principalEntity("false", "true"))); + + assertThatCode(() -> authorizationService.authorize(request, policy)) + .doesNotThrowAnyException(); + } + + @Test + void shouldUseConfiguredPrincipalPropertyForHumanAccess() { + var configuredPolicy = new AuthorizationPolicy(AuthorizationMode.GLOBAL, Set.of(), + Optional.of("employee_enabled")); + Entity eligiblePrincipal = new Entity(UUID.randomUUID(), "principal", "Platform User", + PRINCIPAL_IDENTIFIER, List.of(new Property(null, "is_admin", "false"), + new Property(null, "employee_enabled", "true")), + List.of()); + var request = request(humanPrincipal, AuthorizationAction.READ, CATALOG, + Optional.of(eligiblePrincipal)); + + assertThatCode(() -> authorizationService.authorize(request, configuredPolicy)) + .doesNotThrowAnyException(); + } + + @Test + void shouldNotRequirePrincipalPropertyWhenGateIsNotConfigured() { + var ungatedPolicy = new AuthorizationPolicy(AuthorizationMode.GLOBAL, Set.of(), + Optional.empty()); + var request = request(humanPrincipal, AuthorizationAction.READ, CATALOG, Optional.empty()); + + assertThatCode(() -> authorizationService.authorize(request, ungatedPolicy)) + .doesNotThrowAnyException(); + } + + @Test + void shouldKeepHumanWritesDeniedWhenGateIsNotConfigured() { + var ungatedPolicy = new AuthorizationPolicy(AuthorizationMode.GLOBAL, Set.of(), + Optional.empty()); + var request = request(humanPrincipal, AuthorizationAction.UPDATE, CATALOG, Optional.empty()); + + assertThatThrownBy(() -> authorizationService.authorize(request, ungatedPolicy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + + @Test + void shouldRejectHumanWithoutRequiredPropertyEvenForReadOperations() { + for (Optional principalEntity : List.>of(Optional.empty(), + Optional.of(principalEntity("false", "false")))) { + var request = request(humanPrincipal, AuthorizationAction.READ, CATALOG, principalEntity); + + assertThatThrownBy(() -> authorizationService.authorize(request, policy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + } + + @Test + void shouldRejectWriteOperationsForNonAdminHumans() { + var request = request(humanPrincipal, AuthorizationAction.UPDATE, CATALOG, + Optional.of(principalEntity("false", "true"))); + + assertThatThrownBy(() -> authorizationService.authorize(request, policy)) + .isInstanceOf(PrincipalNotAuthorizedException.class) + .hasMessageContaining(PRINCIPAL_IDENTIFIER); + } + + @Test + void shouldRejectAdminFlagOnNonPrincipalEntity() { + Entity nonPrincipalEntity = new Entity(UUID.randomUUID(), "team", "Platform User", + PRINCIPAL_IDENTIFIER, List.of(new Property(null, "is_admin", "true"), + new Property(null, REQUIRED_PRINCIPAL_PROPERTY, "true")), + List.of()); + var request = request(humanPrincipal, AuthorizationAction.UPDATE, CATALOG, + Optional.of(nonPrincipalEntity)); + + assertThatThrownBy(() -> authorizationService.authorize(request, policy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + + @Test + void shouldRejectUnsupportedActionsEvenForBreakGlassPrincipal() { + var request = request(principal("break-glass-user", PrincipalKind.HUMAN), + AuthorizationAction.UNSUPPORTED, CATALOG, Optional.empty()); + + assertThatThrownBy(() -> authorizationService.authorize(request, policy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + + @Test + void shouldRejectModesThatAreNotImplementedYet() { + var futureModePolicy = new AuthorizationPolicy(AuthorizationMode.RBAC, Set.of(), + Optional.of(REQUIRED_PRINCIPAL_PROPERTY)); + var request = request(humanPrincipal, AuthorizationAction.READ, CATALOG, Optional.empty()); + + assertThatThrownBy(() -> authorizationService.authorize(request, futureModePolicy)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + } + + private AuthorizationRequest request(PrincipalInfo principal, AuthorizationAction action, + AuthorizationResource resource, Optional principalEntity) { + return new AuthorizationRequest(principal, principalEntity, action, resource); + } + + private List crudActions() { + return List.of(AuthorizationAction.CREATE, AuthorizationAction.READ, AuthorizationAction.UPDATE, + AuthorizationAction.DELETE); + } + + private static PrincipalInfo principal(String identifier, PrincipalKind kind) { + return new PrincipalInfo(identifier, kind, "Platform User", null, null); + } + + private PrincipalInfo serviceAccount() { + return principal(PRINCIPAL_IDENTIFIER, PrincipalKind.SERVICE_ACCOUNT); + } + + private Entity principalEntity(String isAdmin) { + return principalEntity(isAdmin, "false"); + } + + private Entity principalEntity(String isAdmin, String isDigitalTeammate) { + return new Entity(UUID.randomUUID(), "principal", "Platform User", PRINCIPAL_IDENTIFIER, + List.of(new Property(null, "is_admin", isAdmin), + new Property(null, REQUIRED_PRINCIPAL_PROPERTY, isDigitalTeammate)), + List.of()); + } + + private static Entity principalEntity(boolean isAdmin, String isDigitalTeammate, String kind) { + return new Entity(UUID.randomUUID(), "principal", "Platform User", "regular-human", + List.of(new Property(null, "kind", kind), + new Property(null, "is_admin", Boolean.toString(isAdmin)), + new Property(null, REQUIRED_PRINCIPAL_PROPERTY, isDigitalTeammate)), + List.of()); + } +} diff --git a/src/test/java/com/decathlon/idp_core/domain/service/entity/EntityServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/entity/EntityServiceTest.java index f612aac7..bbd585b6 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/entity/EntityServiceTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/entity/EntityServiceTest.java @@ -9,6 +9,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -21,6 +22,7 @@ import java.util.Optional; import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -33,7 +35,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.test.util.ReflectionTestUtils; -import com.decathlon.idp_core.domain.constant.SearchConstraints; import com.decathlon.idp_core.domain.constant.ValidationMessages; import com.decathlon.idp_core.domain.exception.entity.EntityAlreadyExistsException; import com.decathlon.idp_core.domain.exception.entity.EntityDeletionBlockedException; @@ -88,6 +89,17 @@ class EntityServiceTest { @InjectMocks private EntityService entityService; + @BeforeEach + void returnValidatedEntitiesByDefault() { + lenient().when( + entityValidationService.validateForCreation(any(Entity.class), any(EntityTemplate.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + lenient() + .when( + entityValidationService.validateForUpdate(any(Entity.class), any(EntityTemplate.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + } + @Test @DisplayName("Should return entities page by template identifier") void shouldReturnEntitiesByTemplateIdentifier() { @@ -169,6 +181,27 @@ void shouldCreateEntityWhenValidationsPass() { verifyNoInteractions(entityTemplateValidationService); } + @Test + @DisplayName("Should persist the entity returned by creation validation") + void shouldPersistNormalizedEntityOnCreate() { + var entity = new Entity(UUID.randomUUID(), "web-service", "Catalog API", "catalog-api", + List.of(), List.of(relation("database", "placeholder", "missing-database"))); + var template = templateWithRelations("web-service", + relationDefinition("database", "database-service", false, false)); + var normalized = new Entity(entity.id(), entity.templateIdentifier(), entity.name(), + entity.identifier(), entity.properties(), List.of()); + + when(entityTemplateService.getEntityTemplateByIdentifier("web-service")).thenReturn(template); + when(entityValidationService.validateForCreation(any(Entity.class), eq(template))) + .thenReturn(normalized); + when(entityRepository.save(normalized)).thenReturn(normalized); + + var result = entityService.createEntity(entity); + + assertSame(normalized, result); + verify(entityRepository).save(normalized); + } + @Test @DisplayName("Should not save when entity already exists") void shouldNotSaveWhenEntityAlreadyExists() { @@ -231,6 +264,31 @@ void shouldUpdateEntityWhenValidationsPass() { inOrder.verify(entityRepository).save(expectedSaved); } + @Test + @DisplayName("Should persist normalized relations when updating an entity") + void shouldPersistNormalizedEntityOnUpdate() { + var existing = new Entity(UUID.randomUUID(), "web-service", "Catalog API", "catalog-api", + List.of(), List.of(relation("database", "database-service", "database-service-1"))); + var payload = new Entity(null, "web-service", "Catalog API", "catalog-api", List.of(), + List.of(relation("database", "placeholder", "missing-database"))); + var template = templateWithRelations("web-service", + relationDefinition("database", "database-service", false, false)); + var normalized = new Entity(existing.id(), "web-service", "Catalog API", "catalog-api", + List.of(), List.of()); + + when(entityTemplateService.getEntityTemplateByIdentifier("web-service")).thenReturn(template); + when(entityRepository.findByTemplateIdentifierAndIdentifier("web-service", "catalog-api")) + .thenReturn(Optional.of(existing)); + when(entityValidationService.validateForUpdate(any(Entity.class), eq(template))) + .thenReturn(normalized); + when(entityRepository.save(normalized)).thenReturn(normalized); + + var result = entityService.updateEntity("web-service", "catalog-api", payload); + + assertSame(normalized, result); + verify(entityRepository).save(normalized); + } + @Test @DisplayName("Should throw when updating non-existing entity") void shouldThrowWhenUpdatingNonExistingEntity() { @@ -450,7 +508,7 @@ private SearchFilterNode emptyFilter() { private void assertSearchThrows(PaginationCriteria paginationCriteria) { var filter = emptyFilter(); assertThrows(InvalidSearchQueryException.class, - () -> entityService.searchEntities(filter, null, paginationCriteria)); + () -> entityService.searchEntities(filter, null, paginationCriteria, 500)); } private Property property(String name, String value) { @@ -497,7 +555,8 @@ void shouldSearchEntitiesWithValidParameters() { when(entityRepository.search(filter, "api", new PaginationCriteria(0, 20, null))) .thenReturn(paginatedResult); - var result = entityService.searchEntities(filter, "api", new PaginationCriteria(0, 20, null)); + var result = entityService.searchEntities(filter, "api", new PaginationCriteria(0, 20, null), + 500); assertEquals(paginatedResult, result); verify(searchFilterValidationService).validate(filter, "api"); @@ -514,45 +573,27 @@ void shouldSearchEntitiesWithValidSort() { .thenReturn(paginatedResult); var result = entityService.searchEntities(filter, null, - new PaginationCriteria(0, 10, "identifier:asc")); + new PaginationCriteria(0, 10, "identifier,asc"), 500); assertEquals(paginatedResult, result); } - @Test - @DisplayName("Should reject page size exceeding maximum") - void shouldRejectPageSizeExceedingMaximum() { - assertSearchThrows(new PaginationCriteria(0, SearchConstraints.MAX_PAGE_SIZE + 1, null)); - } - - @Test - @DisplayName("Should reject negative page index") - void shouldRejectNegativePageIndex() { - assertSearchThrows(new PaginationCriteria(-1, 20, null)); - } - - @Test - @DisplayName("Should reject non-positive page size") - void shouldRejectNonPositivePageSize() { - assertSearchThrows(new PaginationCriteria(0, 0, null)); - } - @Test @DisplayName("Should reject invalid sort field") void shouldRejectInvalidSortField() { - assertSearchThrows(new PaginationCriteria(0, 20, "badField:asc")); + assertSearchThrows(new PaginationCriteria(0, 20, "badField,asc")); } @Test @DisplayName("Should reject invalid sort direction") void shouldRejectInvalidSortDirection() { - assertSearchThrows(new PaginationCriteria(0, 20, "identifier:zzz")); + assertSearchThrows(new PaginationCriteria(0, 20, "identifier,zzz")); } @Test @DisplayName("Should reject extra sort expression segments") void shouldRejectExtraSortSegments() { - assertSearchThrows(new PaginationCriteria(0, 20, "identifier:asc:extra")); + assertSearchThrows(new PaginationCriteria(0, 20, "identifier,asc,extra")); } // --------------------------------------------------------------------------- @@ -1048,6 +1089,31 @@ void shouldPatchEntityWhenValidationsPass() { verify(entityRepository).save(any(Entity.class)); } + @Test + @DisplayName("Should persist normalized relations when patching an entity") + void shouldPersistNormalizedEntityOnPatch() { + var existing = new Entity(UUID.randomUUID(), "web-service", "Catalog API", "catalog-api", + List.of(), List.of(relation("database", "database-service", "database-service-1"))); + var patchData = new EntityPatch(null, null, + List.of(relation("database", "placeholder", "missing-database"))); + var template = templateWithRelations("web-service", + relationDefinition("database", "database-service", false, false)); + var normalized = new Entity(existing.id(), existing.templateIdentifier(), existing.name(), + existing.identifier(), existing.properties(), List.of()); + + when(entityTemplateService.getEntityTemplateByIdentifier("web-service")).thenReturn(template); + when(entityRepository.findByTemplateIdentifierAndIdentifier("web-service", "catalog-api")) + .thenReturn(Optional.of(existing)); + when(entityValidationService.validateForUpdate(any(Entity.class), eq(template))) + .thenReturn(normalized); + when(entityRepository.save(normalized)).thenReturn(normalized); + + var result = entityService.patchEntity("web-service", "catalog-api", patchData); + + assertSame(normalized, result); + verify(entityRepository).save(normalized); + } + @Test @DisplayName("Should return existing entity without saving when patch contains no actual changes") void shouldReturnExistingEntityWhenPatchDoesNotChangeContent() { diff --git a/src/test/java/com/decathlon/idp_core/domain/service/entity/EntityValidationServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/entity/EntityValidationServiceTest.java index 6b3c2bad..c7ecde22 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/entity/EntityValidationServiceTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/entity/EntityValidationServiceTest.java @@ -22,6 +22,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import com.decathlon.idp_core.domain.exception.entity.EntityAlreadyExistsException; @@ -53,6 +54,10 @@ class EntityValidationServiceTest { void setUp() { entityValidationService = new EntityValidationService(entityRepository, propertyValidationService, relationValidationService); + Mockito + .lenient().when(relationValidationService + .validateAndNormalizeRelationsAgainstTemplate(any(), any(), any())) + .thenAnswer(invocation -> invocation.getArgument(1)); } @Nested @@ -121,10 +126,33 @@ void shouldValidateSuccessfullyWhenNoViolations() { eq(template.propertiesDefinitions()), eq(Map.of("version", property)), any(Violations.class)); - verify(relationValidationService).validateRelationsAgainstTemplate(eq(template), + verify(relationValidationService).validateAndNormalizeRelationsAgainstTemplate(eq(template), eq(entity.relations()), any(Violations.class)); } + @Test + @DisplayName("Should return the entity with normalized relations") + void shouldReturnEntityWithNormalizedRelations() { + var template = buildTemplate(); + var relation = new Relation(UUID.randomUUID(), "owned-by", "team", + List.of("team-a", "missing-team")); + var resolvedRelation = new Relation(relation.id(), relation.name(), + relation.targetTemplateIdentifier(), List.of("team-a")); + var entity = buildEntity("web-service", "catalog-api", "Catalog API", List.of(), + List.of(relation)); + + when(entityRepository.findByTemplateIdentifierAndIdentifier(any(), any())) + .thenReturn(Optional.empty()); + when(relationValidationService.validateAndNormalizeRelationsAgainstTemplate(eq(template), + eq(entity.relations()), any(Violations.class))).thenReturn(List.of(resolvedRelation)); + + var validatedEntity = entityValidationService.validateForCreation(entity, template); + + assertEquals(List.of(resolvedRelation), validatedEntity.relations()); + assertEquals(entity.properties(), validatedEntity.properties()); + assertEquals(entity.identifier(), validatedEntity.identifier()); + } + @Test @DisplayName("Should throw EntityValidationException when delegated validations populate the Violations aggregate") void shouldThrowEntityValidationExceptionWhenViolationsExist() { @@ -148,8 +176,8 @@ void shouldThrowEntityValidationExceptionWhenViolationsExist() { verify(propertyValidationService).validatePropertiesAgainstTemplate(eq(template), any(), any(), any()); - verify(relationValidationService).validateRelationsAgainstTemplate(eq(template), any(), - any()); + verify(relationValidationService).validateAndNormalizeRelationsAgainstTemplate(eq(template), + any(), any()); } } @@ -183,7 +211,7 @@ void shouldHandleEntityWithNullRelations() { assertDoesNotThrow(() -> entityValidationService.validateForCreation(entity, template)); // Entity's compact constructor converts null to empty list - verify(relationValidationService).validateRelationsAgainstTemplate(eq(template), + verify(relationValidationService).validateAndNormalizeRelationsAgainstTemplate(eq(template), eq(List.of()), any(Violations.class)); } @@ -260,7 +288,7 @@ void shouldValidateWithoutUniquenessCheck() { verify(propertyValidationService).validatePropertiesAgainstTemplate(eq(template), eq(template.propertiesDefinitions()), eq(Map.of("version", property)), any(Violations.class)); - verify(relationValidationService).validateRelationsAgainstTemplate(eq(template), + verify(relationValidationService).validateAndNormalizeRelationsAgainstTemplate(eq(template), eq(entity.relations()), any(Violations.class)); } @@ -308,7 +336,7 @@ void shouldHandleUpdateWithNullPropertiesAndRelations() { // Entity's compact constructor converts null to empty lists verify(propertyValidationService).validatePropertiesAgainstTemplate(eq(template), eq(template.propertiesDefinitions()), eq(Map.of()), any(Violations.class)); - verify(relationValidationService).validateRelationsAgainstTemplate(eq(template), + verify(relationValidationService).validateAndNormalizeRelationsAgainstTemplate(eq(template), eq(List.of()), any(Violations.class)); } } diff --git a/src/test/java/com/decathlon/idp_core/domain/service/entity_graph/EntityGraphServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/entity_graph/EntityGraphServiceTest.java index cdd3f32d..d9be2a6c 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/entity_graph/EntityGraphServiceTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/entity_graph/EntityGraphServiceTest.java @@ -5,6 +5,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -24,6 +26,10 @@ import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import com.decathlon.idp_core.domain.exception.entity.EntityNotFoundException; import com.decathlon.idp_core.domain.model.entity.Entity; @@ -34,8 +40,10 @@ import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphNode; import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphQueryOptions; import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphTraversalMode; +import com.decathlon.idp_core.domain.model.search.PaginationCriteria; import com.decathlon.idp_core.domain.port.EntityGraphRepositoryPort; import com.decathlon.idp_core.domain.port.EntityRepositoryPort; +import com.decathlon.idp_core.domain.service.entity.EntityService; import com.decathlon.idp_core.domain.service.entity_template.EntityTemplateValidationService; @ExtendWith(MockitoExtension.class) @@ -48,6 +56,9 @@ class EntityGraphServiceTest { @Mock private EntityGraphRepositoryPort entityGraphRepositoryPort; + @Mock + private EntityService entityService; + @Mock private EntityTemplateValidationService entityTemplateValidationService; @@ -74,6 +85,24 @@ private Relation relation(String name, String targetTemplateIdentifier, String.. private static final String TEMPLATE = "web-service"; + @Nested + @DisplayName("Paginated Entity Sorting") + class PaginatedEntitySorting { + + @Test + @DisplayName("Should apply the requested sort to the entity page") + void shouldApplyRequestedSort() { + when(entityService.getEntitiesByTemplateIdentifier(any(Pageable.class), eq(TEMPLATE), + isNull())).thenReturn(Page.empty()); + + entityGraphService.getEntityGraphPageByTemplate( + new PaginationCriteria(0, 10, "identifier,desc"), TEMPLATE, null, 1, 100); + + verify(entityService).getEntitiesByTemplateIdentifier( + PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "identifier")), TEMPLATE, null); + } + } + private void stubRootEntity(Entity entity) { when(entityRepositoryPort.findSummariesByCompositeKeys( List.of(new EntityCompositeKey(entity.templateIdentifier(), entity.identifier())))) diff --git a/src/test/java/com/decathlon/idp_core/domain/service/principal/PrincipalExtractorTest.java b/src/test/java/com/decathlon/idp_core/domain/service/principal/PrincipalExtractorTest.java index 461ded56..36e6b40a 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/principal/PrincipalExtractorTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/principal/PrincipalExtractorTest.java @@ -1,6 +1,7 @@ package com.decathlon.idp_core.domain.service.principal; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -26,7 +27,8 @@ import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; import com.decathlon.idp_core.domain.model.principal.PrincipalKind; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.AuthenticationProperties; -import com.decathlon.idp_core.infrastructure.adapters.api.configuration.AuthenticationProperties.ServiceAccountDetection; +import com.decathlon.idp_core.infrastructure.adapters.api.configuration.PrincipalExtractionProperties; +import com.decathlon.idp_core.infrastructure.adapters.api.exception.MissingPrincipalIdentifierException; import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractionStrategy; import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; import com.decathlon.idp_core.infrastructure.adapters.api.principal.strategies.JwtPrincipalExtractionStrategy; @@ -68,99 +70,11 @@ void shouldUseApplicableStrategyWhenSupported() { principalExtractor = new PrincipalExtractor(List.of(supportingStrategy)); Authentication authentication = mock(Authentication.class); - // When: Extract principal info PrincipalInfo principalInfo = principalExtractor.extractPrincipalInfo(authentication); - // Then: The strategy was used to extract the principal assertThat(principalInfo).isEqualTo(expectedPrincipal); } - @Test - @DisplayName("Should fallback when no strategy supports authentication") - void shouldFallbackWhenNoStrategySupportsAuthentication() { - // Given: No strategy supports the authentication type - PrincipalExtractionStrategy unsupportingStrategy = mock(PrincipalExtractionStrategy.class); - when(unsupportingStrategy.supports(any())).thenReturn(false); - - principalExtractor = new PrincipalExtractor(List.of(unsupportingStrategy)); - Authentication authentication = new UsernamePasswordAuthenticationToken("testuser", - "password"); - - // When: Extract principal info from unsupported authentication - PrincipalInfo principalInfo = principalExtractor.extractPrincipalInfo(authentication); - - // Then: Fallback principal is created - assertThat(principalInfo.identifier()).isEqualTo("testuser"); - assertThat(principalInfo.kind()).isEqualTo(PrincipalKind.HUMAN); - assertThat(principalInfo.name()).isEqualTo("testuser"); - assertThat(principalInfo.attributes()).isEmpty(); - assertThat(principalInfo.groups()).isEmpty(); - } - - @Test - @DisplayName("Should use first supporting strategy from multiple strategies") - void shouldUseFirstSupportingStrategyFromList() { - // Given: Multiple strategies, first one supports the authentication - PrincipalInfo expectedPrincipal = new PrincipalInfo("first-strategy", PrincipalKind.HUMAN, - "First Strategy", Map.of(), List.of()); - - PrincipalExtractionStrategy firstStrategy = mock(PrincipalExtractionStrategy.class); - when(firstStrategy.supports(any())).thenReturn(true); - when(firstStrategy.extract(any())).thenReturn(expectedPrincipal); - - PrincipalExtractionStrategy secondStrategy = mock(PrincipalExtractionStrategy.class); - - principalExtractor = new PrincipalExtractor(List.of(firstStrategy, secondStrategy)); - Authentication authentication = mock(Authentication.class); - - // When: Extract principal info - PrincipalInfo principalInfo = principalExtractor.extractPrincipalInfo(authentication); - - // Then: First strategy's principal is returned - assertThat(principalInfo).isEqualTo(expectedPrincipal); - } - - @Test - @DisplayName("Should use second strategy when first doesn't support") - void shouldUseSecondStrategyWhenFirstDoesntSupport() { - // Given: Multiple strategies, first doesn't support but second does - PrincipalInfo expectedPrincipal = new PrincipalInfo("second-strategy", PrincipalKind.HUMAN, - "Second Strategy", Map.of(), List.of()); - - PrincipalExtractionStrategy firstStrategy = mock(PrincipalExtractionStrategy.class); - when(firstStrategy.supports(any())).thenReturn(false); - - PrincipalExtractionStrategy secondStrategy = mock(PrincipalExtractionStrategy.class); - when(secondStrategy.supports(any())).thenReturn(true); - when(secondStrategy.extract(any())).thenReturn(expectedPrincipal); - - principalExtractor = new PrincipalExtractor(List.of(firstStrategy, secondStrategy)); - Authentication authentication = mock(Authentication.class); - - // When: Extract principal info - PrincipalInfo principalInfo = principalExtractor.extractPrincipalInfo(authentication); - - // Then: Second strategy's principal is returned - assertThat(principalInfo).isEqualTo(expectedPrincipal); - } - - @Test - @DisplayName("Should fallback when null authentication") - void shouldFallbackWhenAuthenticationIsNull() { - // Given: Extractor with no strategies - principalExtractor = new PrincipalExtractor(List.of()); - - // When: Extract principal info with null authentication - PrincipalInfo principalInfo = principalExtractor.extractPrincipalInfo(null); - - // Then: Fallback principal with UNKNOWN is created - assertThat(principalInfo.identifier()).isEqualTo("UNKNOWN"); - assertThat(principalInfo.name()).isEqualTo("UNKNOWN"); - assertThat(principalInfo.kind()).isEqualTo(PrincipalKind.HUMAN); - assertThat(principalInfo.attributes()).isEmpty(); - assertThat(principalInfo.groups()).isEmpty(); - } - @Test @DisplayName("Should fallback with empty strategies list") void shouldFallbackWithEmptyStrategiesList() { @@ -184,6 +98,7 @@ class JwtPrincipalExtractionStrategyTests { private AuthenticationProperties authProperties; private JwtPrincipalExtractionStrategy jwtStrategy; + private PrincipalExtractionProperties extractionProperties; @BeforeEach void setUp() { @@ -199,10 +114,11 @@ void setUp() { claimMappings.put("grant_type", "grant_type"); claimMappings.put("gty", "gty"); - authProperties = new AuthenticationProperties(claimMappings, new ServiceAccountDetection(true, - "legacy", "token_type", "m2m", List.of("grant_type", "service_name", "client_id")), - List.of()); - jwtStrategy = new JwtPrincipalExtractionStrategy(authProperties); + authProperties = new AuthenticationProperties(claimMappings, List.of()); + extractionProperties = new PrincipalExtractionProperties( + List.of("name", "preferred_username"), new PrincipalExtractionProperties.Human("sub"), + new PrincipalExtractionProperties.Machine("client_id", "")); + jwtStrategy = new JwtPrincipalExtractionStrategy(authProperties, extractionProperties); } @Test @@ -246,13 +162,62 @@ void shouldExtractHumanFromJwtWithAllClaims() { PrincipalInfo principal = jwtStrategy.extract(auth); // Then: Principal is extracted correctly - assertThat(principal.identifier()).isEqualTo("john.doe"); + assertThat(principal.identifier()).isEqualTo("user-123"); assertThat(principal.name()).isEqualTo("John Doe"); assertThat(principal.kind()).isEqualTo(PrincipalKind.HUMAN); assertThat(principal.attributes()).containsEntry("email", "john@example.com"); assertThat(principal.groups()).containsExactly("admin", "users"); } + @Test + @DisplayName("Should use the configured claim as the human principal identifier") + void shouldUseConfiguredIdentifierClaimForHumanPrincipal() { + PrincipalExtractionProperties uuidProperties = new PrincipalExtractionProperties( + List.of("uuid"), new PrincipalExtractionProperties.Human("uuid"), + new PrincipalExtractionProperties.Machine("client_id", "")); + JwtPrincipalExtractionStrategy strategy = new JwtPrincipalExtractionStrategy(authProperties, + uuidProperties); + var jwtToken = mock(org.springframework.security.oauth2.jwt.Jwt.class); + when(jwtToken.getSubject()).thenReturn("stable-subject"); + when(jwtToken.getClaims()) + .thenReturn(Map.of("uuid", "user-uuid", "preferred_username", "recycled-login")); + + PrincipalInfo principal = strategy.extract(new JwtAuthenticationToken(jwtToken)); + + assertThat(principal.identifier()).isEqualTo("user-uuid"); + assertThat(principal.name()).isEqualTo("recycled-login"); + assertThat(principal.kind()).isEqualTo(PrincipalKind.HUMAN); + } + + @Test + @DisplayName("Should treat a blank human indicator as absent") + void shouldTreatBlankHumanIndicatorAsAbsent() { + Map claims = Map.of("uuid", " ", "client_id", "service-123"); + var jwtToken = mock(org.springframework.security.oauth2.jwt.Jwt.class); + when(jwtToken.getClaims()).thenReturn(claims); + + PrincipalExtractionProperties properties = new PrincipalExtractionProperties(List.of("uuid"), + new PrincipalExtractionProperties.Human("uuid"), + new PrincipalExtractionProperties.Machine("client_id", "machine:")); + PrincipalInfo principal = new JwtPrincipalExtractionStrategy(authProperties, properties) + .extract(new JwtAuthenticationToken(jwtToken)); + + assertThat(principal.kind()).isEqualTo(PrincipalKind.SERVICE_ACCOUNT); + assertThat(principal.identifier()).isEqualTo("machine:service-123"); + } + + @Test + @DisplayName("Should reject machine tokens without the configured machine identifier") + void shouldRejectMachineWithoutConfiguredIdentifier() { + var jwtToken = mock(org.springframework.security.oauth2.jwt.Jwt.class); + when(jwtToken.getClaims()).thenReturn(Map.of("token_type", "m2m")); + var authentication = new JwtAuthenticationToken(jwtToken); + + assertThatThrownBy(() -> jwtStrategy.extract(authentication)) + .isInstanceOf(MissingPrincipalIdentifierException.class) + .hasMessageContaining("client_id"); + } + @Test @DisplayName("Should fall back to subject when preferred_username missing") void shouldFallbackToSubjectWhenPreferredUsernameMissing() { @@ -358,9 +323,9 @@ void shouldFilterNonStringValuesFromGroups() { } @Test - @DisplayName("Should detect service account with legacy mode - grant_type client_credentials") - void shouldDetectServiceAccountLegacyGrantType() { - // Given: JWT with grant_type=client_credentials (legacy mode enabled) + @DisplayName("Should classify by human indicator rather than grant_type") + void shouldUseHumanIndicatorInsteadOfGrantType() { + // Given: JWT with a configured human indicator and a grant_type claim Map claims = new HashMap<>(); claims.put("client_id", "my-service"); claims.put("name", "My Service"); @@ -375,16 +340,16 @@ void shouldDetectServiceAccountLegacyGrantType() { // When: Extract principal PrincipalInfo principal = jwtStrategy.extract(auth); - // Then: Detected as service account - assertThat(principal.kind()).isEqualTo(PrincipalKind.SERVICE_ACCOUNT); + // Then: The configured human indicator determines the principal kind. + assertThat(principal.kind()).isEqualTo(PrincipalKind.HUMAN); assertThat(principal.identifier()).isEqualTo("my-service"); assertThat(principal.name()).isEqualTo("My Service"); } @Test - @DisplayName("Should detect service account with gty claim") - void shouldDetectServiceAccountWithGtyClaim() { - // Given: JWT with gty=client_credentials + @DisplayName("Should not detect service account from gty alone") + void shouldNotDetectServiceAccountFromGtyAlone() { + // Given: JWT with gty=client_credentials but no definitive claim Map claims = new HashMap<>(); claims.put("client_id", "my-service"); claims.put("gty", "client_credentials"); @@ -398,20 +363,20 @@ void shouldDetectServiceAccountWithGtyClaim() { // When: Extract principal PrincipalInfo principal = jwtStrategy.extract(auth); - // Then: Detected as service account + // Then: Grant-type claims do not affect the indicator-based classification. assertThat(principal.kind()).isEqualTo(PrincipalKind.SERVICE_ACCOUNT); } @Test - @DisplayName("Should detect service account with service_name claim") - void shouldDetectServiceAccountWithServiceNameClaim() { - // Given: JWT with service_name claim + @DisplayName("Should classify a token without human indicators as a service account") + void shouldTreatServiceNameWithoutDefinitiveClaimAsHuman() { + // Given: JWT with a machine ID and no configured human indicator Map claims = new HashMap<>(); claims.put("service_name", "my-service"); claims.put("client_id", "my-service"); var jwtToken = mock(org.springframework.security.oauth2.jwt.Jwt.class); - when(jwtToken.getSubject()).thenReturn("my-service"); + when(jwtToken.getSubject()).thenReturn("user-123"); when(jwtToken.getClaims()).thenReturn(claims); var auth = new JwtAuthenticationToken(jwtToken); @@ -419,14 +384,15 @@ void shouldDetectServiceAccountWithServiceNameClaim() { // When: Extract principal PrincipalInfo principal = jwtStrategy.extract(auth); - // Then: Detected as service account + // Then: Uses the configured machine ID assertThat(principal.kind()).isEqualTo(PrincipalKind.SERVICE_ACCOUNT); + assertThat(principal.identifier()).isEqualTo("my-service"); } @Test - @DisplayName("Should detect service account when sub equals client_id") - void shouldDetectServiceAccountWhenSubEqualsClientId() { - // Given: JWT where sub equals client_id + @DisplayName("Should classify a token with only client_id as a machine") + void shouldNotDetectServiceAccountWhenSubEqualsClientIdAlone() { + // Given: JWT where sub equals client_id but no definitive claim Map claims = new HashMap<>(); claims.put("client_id", "my-service"); @@ -439,16 +405,16 @@ void shouldDetectServiceAccountWhenSubEqualsClientId() { // When: Extract principal PrincipalInfo principal = jwtStrategy.extract(auth); - // Then: Detected as service account + // Then: Human classification requires a configured indicator claim assertThat(principal.kind()).isEqualTo(PrincipalKind.SERVICE_ACCOUNT); } @Test - @DisplayName("Should extract service account with client_id and fallback to azp") + @DisplayName("Should extract a machine ID from the configured client_id claim") void shouldExtractServiceAccountWithClientIdFallbackToAzp() { - // Given: JWT with azp instead of client_id + // Given: JWT with a client_id claim Map claims = new HashMap<>(); - claims.put("azp", "authorized-party"); + claims.put("client_id", "authorized-party"); claims.put("grant_type", "client_credentials"); var jwtToken = mock(org.springframework.security.oauth2.jwt.Jwt.class); @@ -460,8 +426,9 @@ void shouldExtractServiceAccountWithClientIdFallbackToAzp() { // When: Extract principal PrincipalInfo principal = jwtStrategy.extract(auth); - // Then: Uses azp as client_id + // Then: Uses client_id as the machine principal ID assertThat(principal.kind()).isEqualTo(PrincipalKind.SERVICE_ACCOUNT); + assertThat(principal.identifier()).isEqualTo("authorized-party"); assertThat(principal.attributes()).containsEntry("client_id", "authorized-party"); } @@ -479,11 +446,18 @@ void shouldExtractServiceAccountWithServiceNameFallbackToName() { when(jwtToken.getClaims()).thenReturn(claims); var auth = new JwtAuthenticationToken(jwtToken); + PrincipalExtractionProperties machineProperties = new PrincipalExtractionProperties( + List.of("uuid"), new PrincipalExtractionProperties.Human("uuid"), + new PrincipalExtractionProperties.Machine("client_id", "machine:")); + JwtPrincipalExtractionStrategy machineStrategy = new JwtPrincipalExtractionStrategy( + authProperties, machineProperties); // When: Extract principal - PrincipalInfo principal = jwtStrategy.extract(auth); + PrincipalInfo principal = machineStrategy.extract(auth); // Then: Uses name for service account + assertThat(principal.kind()).isEqualTo(PrincipalKind.SERVICE_ACCOUNT); + assertThat(principal.identifier()).isEqualTo("machine:my-service"); assertThat(principal.name()).isEqualTo("My Service Name"); } @@ -531,93 +505,6 @@ void shouldExtractServiceAccountGroups() { assertThat(principal.groups()).containsExactly("service-admins", "integrations"); } - @Test - @DisplayName("Should disable service account detection when disabled in config") - void shouldDisableServiceAccountDetectionWhenDisabled() { - // Given: Service account detection disabled - AuthenticationProperties disabledConfig = new AuthenticationProperties( - authProperties.userClaimMappings(), - new ServiceAccountDetection(false, "legacy", "token_type", "m2m", - List.of("grant_type", "service_name")), - authProperties.jitProvisioningExcludedPaths()); - JwtPrincipalExtractionStrategy strategyDisabled = new JwtPrincipalExtractionStrategy( - disabledConfig); - - Map claims = new HashMap<>(); - claims.put("client_id", "my-service"); - claims.put("grant_type", "client_credentials"); - - var jwtToken = mock(org.springframework.security.oauth2.jwt.Jwt.class); - when(jwtToken.getSubject()).thenReturn("my-service"); - when(jwtToken.getClaims()).thenReturn(claims); - - var auth = new JwtAuthenticationToken(jwtToken); - - // When: Extract principal - PrincipalInfo principal = strategyDisabled.extract(auth); - - // Then: Treated as human even with M2M indicators - assertThat(principal.kind()).isEqualTo(PrincipalKind.HUMAN); - } - - @Test - @DisplayName("Should use strict mode for service account detection") - void shouldUseStrictModeForServiceAccountDetection() { - // Given: Strict mode configuration - AuthenticationProperties strictConfig = new AuthenticationProperties( - authProperties.userClaimMappings(), - new ServiceAccountDetection(true, "strict", "token_type", "m2m", - List.of("grant_type", "service_name")), - authProperties.jitProvisioningExcludedPaths()); - JwtPrincipalExtractionStrategy strategyStrict = new JwtPrincipalExtractionStrategy( - strictConfig); - - Map claims = new HashMap<>(); - claims.put("token_type", "m2m"); - claims.put("client_id", "my-service"); - - var jwtToken = mock(org.springframework.security.oauth2.jwt.Jwt.class); - when(jwtToken.getSubject()).thenReturn("my-service"); - when(jwtToken.getClaims()).thenReturn(claims); - - var auth = new JwtAuthenticationToken(jwtToken); - - // When: Extract principal - PrincipalInfo principal = strategyStrict.extract(auth); - - // Then: Detected with strict mode - assertThat(principal.kind()).isEqualTo(PrincipalKind.SERVICE_ACCOUNT); - } - - @Test - @DisplayName("Should not detect service account in strict mode with wrong claim value") - void shouldNotDetectServiceAccountInStrictModeWithWrongValue() { - // Given: Strict mode with wrong claim value - AuthenticationProperties strictConfig = new AuthenticationProperties( - authProperties.userClaimMappings(), - new ServiceAccountDetection(true, "strict", "token_type", "m2m", - List.of("grant_type", "service_name")), - authProperties.jitProvisioningExcludedPaths()); - JwtPrincipalExtractionStrategy strategyStrict = new JwtPrincipalExtractionStrategy( - strictConfig); - - Map claims = new HashMap<>(); - claims.put("token_type", "human"); // Wrong value - claims.put("client_id", "my-service"); - claims.put("grant_type", "client_credentials"); // Would match in legacy mode - - var jwtToken = mock(org.springframework.security.oauth2.jwt.Jwt.class); - when(jwtToken.getSubject()).thenReturn("my-service"); - when(jwtToken.getClaims()).thenReturn(claims); - - var auth = new JwtAuthenticationToken(jwtToken); - - // When: Extract principal - PrincipalInfo principal = strategyStrict.extract(auth); - - // Then: Not detected as service account (strict mode doesn't check grant_type) - assertThat(principal.kind()).isEqualTo(PrincipalKind.HUMAN); - } } @Nested @@ -641,9 +528,7 @@ void setUp() { claimMappings.put("grant_type", "grant_type"); claimMappings.put("gty", "gty"); - authProperties = new AuthenticationProperties(claimMappings, new ServiceAccountDetection(true, - "legacy", "token_type", "m2m", List.of("grant_type", "service_name", "client_id")), - List.of()); + authProperties = new AuthenticationProperties(claimMappings, List.of()); oauth2Strategy = new OAuth2UserPrincipalExtractionStrategy(authProperties); } @@ -721,41 +606,37 @@ void shouldExtractOAuth2UserWithAllAttributes() { } @Test - @DisplayName("Should fall back to name when sub not present in OAuth2User") - void shouldFallbackToNameWhenSubNotPresent() { - // Given: OAuth2User without sub claim + @DisplayName("Should require a nonblank framework principal name for OAuth2User") + void shouldRequireNonblankPrincipalName() { Map attributes = new HashMap<>(); - attributes.put("name", "John Doe"); + attributes.put("sub", " "); - OAuth2User oauth2User = new DefaultOAuth2User(List.of(), attributes, "name"); + OAuth2User oauth2User = new DefaultOAuth2User(List.of(), attributes, "sub"); Authentication auth = mock(Authentication.class); when(auth.getPrincipal()).thenReturn(oauth2User); - // When: Extract principal - PrincipalInfo principal = oauth2Strategy.extract(auth); - - // Then: Falls back to name (which is the OAuth2User.getName()) - assertThat(principal.identifier()).isNotBlank(); + assertThatThrownBy(() -> oauth2Strategy.extract(auth)) + .isInstanceOf(MissingPrincipalIdentifierException.class) + .hasMessageContaining("principal identifier claim 'name' is missing or blank"); } @Test - @DisplayName("Should prefer configured preferred username for OAuth2User identifier") - void shouldPreferConfiguredPreferredUsernameForOAuth2UserIdentifier() { - // Given: OAuth2User exposing a provider-specific login + @DisplayName("Should use the configured OAuth2 name attribute for identity") + void shouldUseConfiguredOAuth2NameAttribute() { Map attributes = new HashMap<>(); - attributes.put("sub", "user-123"); + attributes.put("id", "user-123"); attributes.put("preferred_username", "john.doe"); attributes.put("name", "John Doe"); - OAuth2User oauth2User = new DefaultOAuth2User(List.of(), attributes, "sub"); + OAuth2User oauth2User = new DefaultOAuth2User(List.of(), attributes, "id"); Authentication auth = mock(Authentication.class); when(auth.getPrincipal()).thenReturn(oauth2User); // When: Extract principal PrincipalInfo principal = oauth2Strategy.extract(auth); - // Then: Identifier uses the human-friendly login - assertThat(principal.identifier()).isEqualTo("john.doe"); + // Then: Spring's configured user-name attribute supplies the identifier + assertThat(principal.identifier()).isEqualTo("user-123"); assertThat(principal.name()).isEqualTo("John Doe"); } @@ -801,12 +682,8 @@ void shouldSkipEmailWhenNotPresent() { void shouldSupportGithubStyleOAuth2AttributesForJitProvisioning() { // Given: GitHub returns id/login and may omit the display name Map githubClaimMappings = new HashMap<>(authProperties.userClaimMappings()); - githubClaimMappings.put("sub", "id"); githubClaimMappings.put("preferred_username", "login"); - authProperties = new AuthenticationProperties(githubClaimMappings, - new ServiceAccountDetection(true, "legacy", "token_type", "m2m", - List.of("grant_type", "service_name", "client_id")), - List.of()); + authProperties = new AuthenticationProperties(githubClaimMappings, List.of()); oauth2Strategy = new OAuth2UserPrincipalExtractionStrategy(authProperties); Map attributes = new HashMap<>(); @@ -820,8 +697,8 @@ void shouldSupportGithubStyleOAuth2AttributesForJitProvisioning() { // When: Extract principal PrincipalInfo principal = oauth2Strategy.extract(auth); - // Then: JIT provisioning gets a stable identifier and usable display name - assertThat(principal.identifier()).isEqualTo("octocat"); + // Then: JIT provisioning uses the provider's stable principal name + assertThat(principal.identifier()).isEqualTo("424242"); assertThat(principal.name()).isEqualTo("octocat"); assertThat(principal.kind()).isEqualTo(PrincipalKind.HUMAN); } @@ -878,8 +755,26 @@ void shouldExtractOidcUserWithPreferredUsername() { // When: Extract principal PrincipalInfo principal = oauth2Strategy.extract(auth); - // Then: Uses preferred_username as identifier - assertThat(principal.identifier()).isEqualTo("john.doe"); + // Then: The OIDC subject is the configured identifier and the username is only + // a display value + assertThat(principal.identifier()).isEqualTo("user-123"); + assertThat(principal.name()).isEqualTo("John Doe"); + } + + @Test + @DisplayName("Should always use the standard subject for an OIDC principal") + void shouldUseOidcSubjectAsIdentifier() { + var idToken = mock(OidcIdToken.class); + when(idToken.getClaims()) + .thenReturn(Map.of("sub", "subject-123", "uuid", "person-uuid", "name", "John Doe")); + + var oidcUser = new DefaultOidcUser(List.of(), idToken); + Authentication auth = mock(Authentication.class); + when(auth.getPrincipal()).thenReturn(oidcUser); + + PrincipalInfo principal = oauth2Strategy.extract(auth); + + assertThat(principal.identifier()).isEqualTo("subject-123"); assertThat(principal.name()).isEqualTo("John Doe"); } diff --git a/src/test/java/com/decathlon/idp_core/domain/service/principal/PrincipalProvisioningServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/principal/PrincipalProvisioningServiceTest.java index 093378ed..f32338bf 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/principal/PrincipalProvisioningServiceTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/principal/PrincipalProvisioningServiceTest.java @@ -115,6 +115,44 @@ void shouldCreateServiceAccountPrincipal() { "github-connector", "github"); } + @Test + void shouldProvisionPrincipalWithAdminDisabledRegardlessOfAttributes() { + PrincipalInfo principalInfo = new PrincipalInfo("alice", PrincipalKind.HUMAN, "Alice Dupont", + Map.of("is_admin", "true", "kind", "SERVICE_ACCOUNT"), List.of()); + when(entityRepository.findByTemplateIdentifierAndIdentifier("principal", "alice")) + .thenReturn(Optional.empty()); + when(entityRepository.save(any(Entity.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + provisioningService.provisionPrincipal(principalInfo); + + ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(Entity.class); + verify(entityRepository).save(entityCaptor.capture()); + List properties = entityCaptor.getValue().properties(); + assertThat(properties).filteredOn(property -> property.name().equals("is_admin")) + .extracting(Property::value).containsExactly("false"); + assertThat(properties).filteredOn(property -> property.name().equals("kind")) + .extracting(Property::value).containsExactly("HUMAN"); + } + + @Test + void shouldProvisionGlobalAdministratorWithAdminEnabled() { + PrincipalInfo principalInfo = new PrincipalInfo("global-admin", PrincipalKind.HUMAN, + "Global Admin", Map.of("is_admin", "false"), List.of()); + when(entityRepository.findByTemplateIdentifierAndIdentifier("principal", "global-admin")) + .thenReturn(Optional.empty()); + when(entityRepository.save(any(Entity.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + provisioningService.provisionGlobalAdministrator(principalInfo); + + ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(Entity.class); + verify(entityRepository).save(entityCaptor.capture()); + assertThat(entityCaptor.getValue().properties()) + .filteredOn(property -> property.name().equals("is_admin")).extracting(Property::value) + .containsExactly("true"); + } + @Test void shouldHandlePrincipalWithNoGroups() { // Given: Principal without group membership @@ -195,7 +233,7 @@ void shouldRetrievePrincipalByIdentifier() { .thenReturn(Optional.of(principal)); // When: Retrieve principal - Optional result = provisioningService.getPrincipal("alice"); + Optional result = provisioningService.findPrincipal("alice"); // Then: Principal returned assertThat(result).isPresent(); @@ -209,9 +247,21 @@ void shouldReturnEmptyWhenPrincipalNotFound() { .thenReturn(Optional.empty()); // When: Retrieve non-existent principal - Optional result = provisioningService.getPrincipal("unknown"); + Optional result = provisioningService.findPrincipal("unknown"); // Then: Empty optional returned assertThat(result).isEmpty(); } + + @Test + void shouldNotLinkPrincipalWhenStoredKindDiffersFromAuthenticatedKind() { + PrincipalInfo human = new PrincipalInfo("alice", PrincipalKind.HUMAN, "Alice", Map.of(), + List.of()); + Entity serviceAccount = new Entity(UUID.randomUUID(), "principal", "Alice", "alice", + List.of(new Property(null, "kind", "SERVICE_ACCOUNT")), List.of()); + when(entityRepository.findByTemplateIdentifierAndIdentifier("principal", "alice")) + .thenReturn(Optional.of(serviceAccount)); + + assertThat(provisioningService.findPrincipalWithSameKind(human)).isEmpty(); + } } diff --git a/src/test/java/com/decathlon/idp_core/domain/service/relation/RelationValidationServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/relation/RelationValidationServiceTest.java index 61e332bd..06b16d0c 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/relation/RelationValidationServiceTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/relation/RelationValidationServiceTest.java @@ -1,10 +1,13 @@ package com.decathlon.idp_core.domain.service.relation; +import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_NAME_ALREADY_EXISTS; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_NOT_DEFINED_IN_TEMPLATE; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_REQUIRED_MISSING; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_TARGET_ENTITY_NOT_FOUND; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_TARGET_TEMPLATE_MISMATCH; import static com.decathlon.idp_core.domain.constant.ValidationMessages.RELATION_TOO_MANY_TARGETS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -16,11 +19,13 @@ import java.util.List; import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -28,6 +33,7 @@ import com.decathlon.idp_core.domain.model.entity.Relation; import com.decathlon.idp_core.domain.model.entity_template.EntityTemplate; import com.decathlon.idp_core.domain.model.entity_template.RelationDefinition; +import com.decathlon.idp_core.domain.model.enums.RelationTargetValidationMode; import com.decathlon.idp_core.domain.port.EntityRepositoryPort; import com.decathlon.idp_core.domain.service.entity.Violations; @@ -38,9 +44,17 @@ class RelationValidationServiceTest { @Mock private EntityRepositoryPort entityRepository; - @InjectMocks private RelationValidationService service; + private RelationValidationService tolerantService; + + @BeforeEach + void setUp() { + service = new RelationValidationService(entityRepository, RelationTargetValidationMode.STRICT); + tolerantService = new RelationValidationService(entityRepository, + RelationTargetValidationMode.TOLERANT); + } + private void mockExistingEntities(String... identifiers) { var summaries = Arrays.stream(identifiers) .map(identifier -> new EntitySummary(UUID.randomUUID(), identifier, "Name", "template")) @@ -93,6 +107,46 @@ private EntitySummary entitySummary(String identifier, String templateIdentifier return new EntitySummary(UUID.randomUUID(), identifier, "Name", templateIdentifier); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @DisplayName("Should reject duplicate relation names in strict validation and dry-run") + void shouldRejectDuplicateRelationNames(boolean dryRun) { + var template = template("system-template", List.of(definition("depends-on", false, true))); + var relations = List.of(relation("depends-on", List.of()), relation("depends-on", List.of())); + var violations = new Violations(); + + if (dryRun) { + service.validateRelationsAgainstTemplateForDryRun(template, relations, violations); + } else { + service.validateAndNormalizeRelationsAgainstTemplate(template, relations, violations); + } + + assertEquals(List.of(RELATION_NAME_ALREADY_EXISTS.formatted("depends-on")), + violations.asList()); + verifyNoInteractions(entityRepository); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @DisplayName("Should reject duplicate names even when tolerant normalization omits one entry") + void shouldRejectDuplicateRelationNamesBeforeOptionalTargetOmission(boolean missingFirst) { + when(entityRepository.findByIdentifierIn(List.of("missing-team"))).thenReturn(List.of()); + when(entityRepository.findByIdentifierIn(List.of("team-a", "team-b"))) + .thenReturn(List.of(entitySummary("team-a", "team"), entitySummary("team-b", "team"))); + var template = template("system-template", + List.of(definition("owned-by", "team", false, false))); + var missing = relation("owned-by", "team", List.of("missing-team")); + var resolved = relation("owned-by", "team", List.of("team-a", "team-b")); + var relations = missingFirst ? List.of(missing, resolved) : List.of(resolved, missing); + var violations = new Violations(); + + var normalized = tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, + relations, violations); + + assertEquals(List.of(resolved), normalized); + assertTrue(violations.asList().contains(RELATION_NAME_ALREADY_EXISTS.formatted("owned-by"))); + } + @Nested @DisplayName("Relation Existence Checks") class ExistenceTests { @@ -149,6 +203,130 @@ void shouldSkipTargetEntityExistenceValidationDuringDryRun() { verifyNoInteractions(entityRepository); verifyNoInteractions(violations); } + + @Test + @DisplayName("Should reject unresolved optional targets in strict mode") + void shouldRejectUnresolvedOptionalTargetsInStrictMode() { + when(entityRepository.findByIdentifierIn(any())).thenReturn(List.of()); + var definition = definition("depends-on", "service", false, true); + var template = template("system-template", List.of(definition)); + var relation = relation("depends-on", "service", List.of("missing-service")); + var violations = mock(Violations.class); + + service.validateAndNormalizeRelationsAgainstTemplate(template, List.of(relation), violations); + + verify(violations).add(RELATION_TARGET_ENTITY_NOT_FOUND, "depends-on", "missing-service"); + } + + @Test + @DisplayName("Should omit unresolved targets from optional relations") + void shouldOmitUnresolvedOptionalTargets() { + when(entityRepository.findByIdentifierIn(any())).thenReturn(List.of()); + var definition = definition("depends-on", "service", false, true); + var template = template("system-template", List.of(definition)); + var relation = relation("depends-on", "service", List.of("missing-service")); + var violations = mock(Violations.class); + + var normalized = tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, + List.of(relation), violations); + + assertEquals(List.of(), normalized); + verifyNoInteractions(violations); + } + + @Test + @DisplayName("Should preserve existing targets and omit unresolved targets") + void shouldPreserveResolvedOptionalTargets() { + when(entityRepository.findByIdentifierIn(any())) + .thenReturn(List.of(entitySummary("service-a", "service"))); + var definition = definition("depends-on", "service", false, true); + var template = template("system-template", List.of(definition)); + var relation = relation("depends-on", "service", List.of("service-a", "missing-service")); + var violations = mock(Violations.class); + + var normalized = tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, + List.of(relation), violations); + + assertEquals(List.of("service-a"), normalized.getFirst().targetEntityIdentifiers()); + verifyNoInteractions(violations); + } + + @Test + @DisplayName("Should omit unresolved optional targets before checking single-target cardinality") + void shouldCheckCardinalityAfterOmittingUnresolvedOptionalTargets() { + when(entityRepository.findByIdentifierIn(any())) + .thenReturn(List.of(entitySummary("team-a", "team"))); + var definition = definition("owned-by", "team", false, false); + var template = template("system-template", List.of(definition)); + var relation = relation("owned-by", "team", List.of("team-a", "missing-team")); + var violations = mock(Violations.class); + + var normalized = tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, + List.of(relation), violations); + + assertEquals(List.of("team-a"), normalized.getFirst().targetEntityIdentifiers()); + verifyNoInteractions(violations); + } + + @Test + @DisplayName("Should enforce single-target cardinality in tolerant mode") + void shouldEnforceCardinalityInTolerantMode() { + when(entityRepository.findByIdentifierIn(any())) + .thenReturn(List.of(entitySummary("team-a", "team"), entitySummary("team-b", "team"))); + var definition = definition("owned-by", "team", false, false); + var template = template("system-template", List.of(definition)); + var relation = relation("owned-by", "team", List.of("team-a", "team-b")); + var violations = mock(Violations.class); + + tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, List.of(relation), + violations); + + verify(violations).add(RELATION_TOO_MANY_TARGETS, "owned-by", "system-template"); + verifyNoMoreInteractions(violations); + } + + @Test + @DisplayName("Should report unresolved targets for required relations") + void shouldRejectUnresolvedRequiredTargets() { + when(entityRepository.findByIdentifierIn(any())).thenReturn(List.of()); + var definition = definition("owned-by", "team", true, false); + var template = template("system-template", List.of(definition)); + var relation = relation("owned-by", "team", List.of("missing-team")); + var violations = mock(Violations.class); + + tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, List.of(relation), + violations); + + verify(violations).add(RELATION_TARGET_ENTITY_NOT_FOUND, "owned-by", "missing-team"); + } + + @Test + @DisplayName("Should reject a required relation that has no targets") + void shouldRejectMissingRequiredRelation() { + var definition = definition("owned-by", "team", true, false); + var template = template("system-template", List.of(definition)); + var violations = mock(Violations.class); + + tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, List.of(), violations); + + verify(violations).add(RELATION_REQUIRED_MISSING, "owned-by", "system-template"); + } + + @Test + @DisplayName("Should reject unresolved targets in a partially resolved required relation") + void shouldRejectPartiallyResolvedRequiredTargets() { + when(entityRepository.findByIdentifierIn(any())) + .thenReturn(List.of(entitySummary("team-a", "team"))); + var definition = definition("owned-by", "team", true, true); + var template = template("system-template", List.of(definition)); + var relation = relation("owned-by", "team", List.of("team-a", "missing-team")); + var violations = mock(Violations.class); + + tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, List.of(relation), + violations); + + verify(violations).add(RELATION_TARGET_ENTITY_NOT_FOUND, "owned-by", "missing-team"); + } } @Nested @@ -272,6 +450,24 @@ void shouldReportMismatchWhenTargetEntityUsesDifferentTemplate() { verifyNoMoreInteractions(violations); } + @Test + @DisplayName("Should still report template mismatch for resolved optional targets") + void shouldRejectOptionalTargetWithIncompatibleTemplate() { + when(entityRepository.findByIdentifierIn(any())) + .thenReturn(List.of(entitySummary("team-a", "group"))); + var definition = definition("owned-by", "team", false, false); + var template = template("system-template", List.of(definition)); + var relation = relation("owned-by", "team", List.of("team-a")); + var violations = mock(Violations.class); + + tolerantService.validateAndNormalizeRelationsAgainstTemplate(template, List.of(relation), + violations); + + verify(violations).add(RELATION_TARGET_TEMPLATE_MISMATCH, "owned-by", "team", "team-a", + "group"); + verifyNoMoreInteractions(violations); + } + @Test @DisplayName("Should ignore existing entities that are not targeted by the relation") void shouldIgnoreExistingEntitiesThatAreNotTargetedByRelation() { @@ -344,6 +540,22 @@ void shouldIgnoreBlankTargetIdentifiersWhenValidatingTargetTemplates() { @DisplayName("Relation Cardinality Checks") class CardinalityTests { + @Test + @DisplayName("Should enforce single-target cardinality in strict mode") + void shouldEnforceCardinalityInStrictMode() { + when(entityRepository.findByIdentifierIn(any())) + .thenReturn(List.of(entitySummary("team-a", "team"), entitySummary("team-b", "team"))); + var definition = definition("owned-by", "team", false, false); + var template = template("system-template", List.of(definition)); + var relation = relation("owned-by", "team", List.of("team-a", "team-b")); + var violations = mock(Violations.class); + + service.validateAndNormalizeRelationsAgainstTemplate(template, List.of(relation), violations); + + verify(violations).add(RELATION_TOO_MANY_TARGETS, "owned-by", "system-template"); + verifyNoMoreInteractions(violations); + } + @Test @DisplayName("Should report violation when a non-toMany relation has multiple valid targets") void shouldReportViolationForMultipleTargetsOnSingleRelation() { diff --git a/src/test/java/com/decathlon/idp_core/domain/service/search/SortParameterParserTest.java b/src/test/java/com/decathlon/idp_core/domain/service/search/SortParameterParserTest.java new file mode 100644 index 00000000..1c24bf18 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/domain/service/search/SortParameterParserTest.java @@ -0,0 +1,65 @@ +package com.decathlon.idp_core.domain.service.search; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.decathlon.idp_core.domain.exception.search.InvalidSearchQueryException; +import com.decathlon.idp_core.domain.model.search.SortCriteria; +import com.decathlon.idp_core.domain.model.search.SortCriteria.Direction; + +@DisplayName("SortParameterParser Tests") +class SortParameterParserTest { + + @Test + @DisplayName("Should parse comma-delimited sort expression") + void shouldParseCommaDelimitedExpression() { + assertThat(SortParameterParser.parse("identifier,desc")) + .contains(new SortCriteria("identifier", Direction.DESC)); + } + + @Test + @DisplayName("Should reject colon-delimited sort expressions") + void shouldRejectColonDelimitedExpressions() { + assertThatThrownBy(() -> SortParameterParser.parse("name:asc")) + .isInstanceOf(InvalidSearchQueryException.class) + .hasMessageContaining("Invalid sort expression"); + assertThatThrownBy(() -> SortParameterParser.parse("name:desc")) + .isInstanceOf(InvalidSearchQueryException.class) + .hasMessageContaining("Invalid sort expression"); + } + + @Test + @DisplayName("Should default direction to ascending") + void shouldDefaultDirectionToAscending() { + assertThat(SortParameterParser.parse("templateIdentifier")) + .contains(new SortCriteria("templateIdentifier", Direction.ASC)); + } + + @Test + @DisplayName("Should return empty when sort is not provided") + void shouldReturnEmptyForMissingSort() { + assertThat(SortParameterParser.parse(null)).isEmpty(); + assertThat(SortParameterParser.parse(" ")).isEmpty(); + } + + @Test + @DisplayName("Should reject unsupported sort field") + void shouldRejectUnsupportedField() { + assertThatThrownBy(() -> SortParameterParser.parse("badField,asc")) + .isInstanceOf(InvalidSearchQueryException.class).hasMessageContaining("badField"); + } + + @Test + @DisplayName("Should reject invalid direction and malformed expressions") + void shouldRejectInvalidExpressions() { + assertThatThrownBy(() -> SortParameterParser.parse("identifier:sideways")) + .isInstanceOf(InvalidSearchQueryException.class); + assertThatThrownBy(() -> SortParameterParser.parse("identifier,asc:desc")) + .isInstanceOf(InvalidSearchQueryException.class); + assertThatThrownBy(() -> SortParameterParser.parse("identifier,")) + .isInstanceOf(InvalidSearchQueryException.class); + } +} diff --git a/src/test/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorServiceTest.java index 7376ad73..c7d781ca 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorServiceTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorServiceTest.java @@ -109,8 +109,9 @@ void shouldValidateAndSave() { void shouldNotSaveWhenValidationFails() { WebhookConnector toCreate = buildWebhookConnector(null, "github-dora", "GitHub DORA", "desc", true); + WebhookConnector normalizedConnector = toCreate.withEnabled(false); doThrow(new RuntimeException("validation error")).when(webhookConnectorValidationService) - .validateWebhookConnectorForCreation(toCreate); + .validateWebhookConnectorForCreation(normalizedConnector); assertThatThrownBy(() -> service.createWebhookConnector(toCreate)) .hasMessageContaining("validation error"); @@ -135,6 +136,8 @@ void shouldDisableConnectorWhenMappingsAreEmpty() { // Even though toCreate had enabled=true, it should be saved with enabled=false assertThat(saved.enabled()).isFalse(); assertThat(saved.mappings()).isEmpty(); + verify(webhookConnectorValidationService) + .validateWebhookConnectorForCreation(argThat(connector -> !connector.enabled())); } @Test @@ -284,6 +287,8 @@ void shouldDisableConnectorWhenUpdatingWithEmptyMappings() { // Should be forced to false because mappings are empty assertThat(saved.enabled()).isFalse(); assertThat(saved.mappings()).isEmpty(); + verify(webhookConnectorValidationService) + .validateWebhookConnectorForUpdate(argThat(connector -> !connector.enabled())); } @Test diff --git a/src/test/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorValidationServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorValidationServiceTest.java index d109597f..57cefe2f 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorValidationServiceTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/webhook/WebhookConnectorValidationServiceTest.java @@ -63,7 +63,8 @@ void shouldValidateAllChecksForCreation() { var order = inOrder(webhookConnectorRepositoryPort, webhookSecurityValidationService); order.verify(webhookConnectorRepositoryPort).existsByIdentifier("github-dora"); - order.verify(webhookSecurityValidationService).validateForCreation(connector.security()); + order.verify(webhookSecurityValidationService).validateForCreation(connector.security(), + connector.enabled()); } @Test @@ -76,7 +77,19 @@ void shouldThrowWhenIdentifierAlreadyExists() { .isInstanceOf(WebhookConnectorAlreadyExistException.class) .hasMessageContaining("github-dora"); - verify(webhookSecurityValidationService, never()).validateForCreation(any()); + verify(webhookSecurityValidationService, never()).validateForCreation(any(), anyBoolean()); + } + + @Test + @DisplayName("Should pass the disabled state to security validation on creation") + void shouldPassDisabledStateToSecurityValidationOnCreation() { + WebhookConnector connector = buildWebhookConnector("github-dora", "GitHub DORA") + .withEnabled(false); + when(webhookConnectorRepositoryPort.existsByIdentifier("github-dora")).thenReturn(false); + + service.validateWebhookConnectorForCreation(connector); + + verify(webhookSecurityValidationService).validateForCreation(connector.security(), false); } } @@ -94,7 +107,8 @@ void shouldValidateMappingsWhenPresent() { verify(webhookConnectorMappingValidationService) .validateMappings(connectorToUpdate.mappings()); - verify(webhookSecurityValidationService).validateForCreation(connectorToUpdate.security()); + verify(webhookSecurityValidationService).validateForCreation(connectorToUpdate.security(), + connectorToUpdate.enabled()); } @Test @@ -119,7 +133,20 @@ void shouldSkipMappingValidationWhenNoMappings() { service.validateWebhookConnectorForUpdate(connectorToUpdate); verify(webhookConnectorMappingValidationService, never()).validateMappings(any()); - verify(webhookSecurityValidationService).validateForCreation(connectorToUpdate.security()); + verify(webhookSecurityValidationService).validateForCreation(connectorToUpdate.security(), + connectorToUpdate.enabled()); + } + + @Test + @DisplayName("Should pass the disabled state to security validation on update") + void shouldPassDisabledStateToSecurityValidationOnUpdate() { + WebhookConnector connectorToUpdate = buildWebhookConnector("github-dora", "Title") + .withEnabled(false); + + service.validateWebhookConnectorForUpdate(connectorToUpdate); + + verify(webhookSecurityValidationService).validateForCreation(connectorToUpdate.security(), + false); } @Test diff --git a/src/test/java/com/decathlon/idp_core/domain/service/webhook/security/WebhookSecurityValidationServiceTest.java b/src/test/java/com/decathlon/idp_core/domain/service/webhook/security/WebhookSecurityValidationServiceTest.java index c916884b..b2a5780f 100644 --- a/src/test/java/com/decathlon/idp_core/domain/service/webhook/security/WebhookSecurityValidationServiceTest.java +++ b/src/test/java/com/decathlon/idp_core/domain/service/webhook/security/WebhookSecurityValidationServiceTest.java @@ -2,6 +2,7 @@ import static com.decathlon.idp_core.domain.model.enums.WebhookSecurityType.HMAC_SHA256; import static com.decathlon.idp_core.domain.model.enums.WebhookSecurityType.JWT_BEARER; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.lenient; @@ -21,6 +22,7 @@ import com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException; import com.decathlon.idp_core.domain.model.enums.WebhookSecurityType; import com.decathlon.idp_core.domain.model.inbound_connectors.webhook.WebhookSecurity; +import com.decathlon.idp_core.domain.model.inbound_connectors.webhook.WebhookSecurityValidationPolicy; import com.decathlon.idp_core.domain.port.WebhookSecurityStrategy; @DisplayName("WebhookSecurityValidationService Tests") @@ -35,7 +37,8 @@ class WebhookSecurityValidationServiceTest { @BeforeEach void setUp() { lenient().when(hmacCreationValidator.supports(HMAC_SHA256)).thenReturn(true); - service = new WebhookSecurityValidationService(List.of(hmacCreationValidator)); + service = new WebhookSecurityValidationService(List.of(hmacCreationValidator), + new WebhookSecurityValidationPolicy(true)); } @Nested @@ -45,7 +48,7 @@ class NullBlankGuards { @Test @DisplayName("Should throw when security is null") void shouldThrowWhenSecurityIsNull() { - assertThatThrownBy(() -> service.validateForCreation(null)) + assertThatThrownBy(() -> service.validateForCreation(null, true)) .isInstanceOf(WebhookSecurityConfigurationException.class) .hasMessageContaining("mandatory"); } @@ -78,7 +81,7 @@ void shouldDelegateToHmacValidator() { var config = Map.of("header_name", "X-Hub-Signature-256", "secret_alias", "MY_SECRET"); var security = new WebhookSecurity(HMAC_SHA256, config); - assertThatCode(() -> service.validateForCreation(security)).doesNotThrowAnyException(); + assertThatCode(() -> service.validateForCreation(security, true)).doesNotThrowAnyException(); verify(hmacCreationValidator).validateConfiguration(config); } @@ -93,7 +96,16 @@ class NoneTypeValidation { void shouldPassForNoneTypeWithEmptyConfig() { var security = new WebhookSecurity(WebhookSecurityType.NONE, Map.of()); - assertThatCode(() -> service.validateForCreation(security)).doesNotThrowAnyException(); + assertThatCode(() -> service.validateForCreation(security, true)).doesNotThrowAnyException(); + } + + @Test + @DisplayName("Should normalize a null config of a NONE type to an empty map and pass") + void shouldNormalizeNullConfigForNoneType() { + WebhookSecurity security = new WebhookSecurity(WebhookSecurityType.NONE, null); + + assertThat(security.config()).isNotNull().isEmpty(); + assertThatCode(() -> service.validateForCreation(security, true)).doesNotThrowAnyException(); } @Test @@ -101,10 +113,56 @@ void shouldPassForNoneTypeWithEmptyConfig() { void shouldThrowForNoneTypeWithNonEmptyConfig() { var security = new WebhookSecurity(WebhookSecurityType.NONE, Map.of("header_name", "X-Test")); - assertThatThrownBy(() -> service.validateForCreation(security)) + assertThatThrownBy(() -> service.validateForCreation(security, true)) .isInstanceOf(WebhookSecurityConfigurationException.class) .hasMessageContaining("must be empty when type is NONE"); } + + @Test + @DisplayName("Should allow disabled connectors with NONE when the allow-none flag is disabled") + void shouldAllowDisabledConnectorWithNoneWhenDisabled() { + var disabled = new WebhookSecurityValidationService(List.of(hmacCreationValidator), + new WebhookSecurityValidationPolicy(false)); + var security = new WebhookSecurity(WebhookSecurityType.NONE, Map.of()); + + assertThatCode(() -> disabled.validateForCreation(security, false)) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("Should reject enabled connectors with NONE when the allow-none flag is disabled") + void shouldRejectEnabledConnectorWithNoneWhenDisabled() { + var disabled = new WebhookSecurityValidationService(List.of(hmacCreationValidator), + new WebhookSecurityValidationPolicy(false)); + var security = new WebhookSecurity(WebhookSecurityType.NONE, Map.of()); + + assertThatThrownBy(() -> disabled.validateForCreation(security, true)) + .isInstanceOf(WebhookSecurityConfigurationException.class) + .hasMessageContaining("IDP_WEBHOOK_SECURITY_ALLOW_NONE"); + } + + @Test + @DisplayName("Should allow disabled connectors with normalized null NONE config") + void shouldAllowDisabledConnectorWithNullNoneConfig() { + var disabled = new WebhookSecurityValidationService(List.of(hmacCreationValidator), + new WebhookSecurityValidationPolicy(false)); + var security = new WebhookSecurity(WebhookSecurityType.NONE, null); + + assertThatCode(() -> disabled.validateForCreation(security, false)) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("Should still validate other security types when the flag is disabled") + void shouldAllowHmacWhenNoneDisabled() { + var disabled = new WebhookSecurityValidationService(List.of(hmacCreationValidator), + new WebhookSecurityValidationPolicy(false)); + var config = Map.of("header_name", "X-Hub-Signature-256", "secret_alias", "MY_SECRET"); + + assertThatCode( + () -> disabled.validateForCreation(new WebhookSecurity(HMAC_SHA256, config), true)) + .doesNotThrowAnyException(); + } } @Nested @@ -118,7 +176,7 @@ void shouldThrowForUnregisteredType() { var security = new WebhookSecurity(JWT_BEARER, Map.of("jwks_uri", "https://example.com/.well-known/jwks")); - assertThatThrownBy(() -> service.validateForCreation(security)) + assertThatThrownBy(() -> service.validateForCreation(security, true)) .isInstanceOf(WebhookSecurityConfigurationException.class) .hasMessageContaining("No validator registered"); } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizationRequestFactoryTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizationRequestFactoryTest.java new file mode 100644 index 00000000..9c312d64 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/AuthorizationRequestFactoryTest.java @@ -0,0 +1,96 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.auth; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; +import com.decathlon.idp_core.domain.model.principal.PrincipalKind; + +class AuthorizationRequestFactoryTest { + + private final AuthorizationRequestFactory factory = new AuthorizationRequestFactory( + TestHandlerMappings.controllers()); + private final PrincipalInfo principal = new PrincipalInfo("subject-123", PrincipalKind.HUMAN, + "User", Map.of(), List.of()); + + @Test + void shouldMapPostSearchToRead() { + var authorizationRequest = create("POST", "/api/v1/entities/search"); + + assertThat(authorizationRequest.action()).isEqualTo(AuthorizationAction.READ); + assertThat(authorizationRequest.resource().type()).isEqualTo("entity_search"); + } + + @Test + void shouldMapDynamicMappingDryRunToRead() { + var authorizationRequest = create("POST", "/api/v1/entity_dynamic_mappings/dry-run"); + + assertThat(authorizationRequest.action()).isEqualTo(AuthorizationAction.READ); + assertThat(authorizationRequest.resource().type()).isEqualTo("entity_dynamic_mapping_dry_run"); + } + + @Test + void shouldMapWebhookConfigurationCreationSeparately() { + var authorizationRequest = create("POST", "/api/v1/inbound_webhooks"); + + assertThat(authorizationRequest.action()).isEqualTo(AuthorizationAction.CREATE); + assertThat(authorizationRequest.resource().type()) + .isEqualTo(AuthorizationResource.INBOUND_WEBHOOK_CONFIGURATION); + } + + @Test + void shouldMapCatalogEntityPathContext() { + var authorizationRequest = create("DELETE", "/api/v1/entities/principal/user-123"); + + assertThat(authorizationRequest.action()).isEqualTo(AuthorizationAction.DELETE); + assertThat(authorizationRequest.resource().type()).isEqualTo("entity"); + assertThat(authorizationRequest.resource().identifier()).contains("user-123"); + assertThat(authorizationRequest.resource().parentIdentifier()).contains("principal"); + } + + @Test + void shouldMapAuditPathVariablesByName() { + var authorizationRequest = create("GET", "/api/v1/audit/entities/principal/user-123"); + + assertThat(authorizationRequest.resource().type()).isEqualTo("audit"); + assertThat(authorizationRequest.resource().identifier()).contains("user-123"); + assertThat(authorizationRequest.resource().parentIdentifier()).contains("principal"); + } + + @Test + void shouldMapTemplateIdentifier() { + var authorizationRequest = create("PUT", "/api/v1/entity-templates/service"); + + assertThat(authorizationRequest.action()).isEqualTo(AuthorizationAction.UPDATE); + assertThat(authorizationRequest.resource().type()).isEqualTo("entity_template"); + assertThat(authorizationRequest.resource().identifier()).contains("service"); + } + + @Test + void shouldUseUnknownResourceWhenNoHandlerMatches() { + var authorizationRequest = create("GET", "/actuator/health"); + + assertThat(authorizationRequest.action()).isEqualTo(AuthorizationAction.READ); + assertThat(authorizationRequest.resource().type()).isEqualTo("unknown"); + } + + @Test + void shouldRejectUnknownHttpMethods() { + var authorizationRequest = create("TRACE", "/api/v1/entities"); + + assertThat(authorizationRequest.action()).isEqualTo(AuthorizationAction.UNSUPPORTED); + } + + private com.decathlon.idp_core.domain.model.authorization.AuthorizationRequest create( + String method, String path) { + return factory.create(new MockHttpServletRequest(method, path), principal, Optional.empty()); + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilterTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilterTest.java new file mode 100644 index 00000000..95d71c2e --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilterTest.java @@ -0,0 +1,222 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.auth; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +import com.decathlon.idp_core.domain.exception.authorization.PrincipalNotAuthorizedException; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationMode; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationRequest; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; +import com.decathlon.idp_core.domain.model.entity.Entity; +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; +import com.decathlon.idp_core.domain.model.principal.PrincipalKind; +import com.decathlon.idp_core.domain.service.authorization.GlobalAuthorizationService; +import com.decathlon.idp_core.domain.service.principal.PrincipalProvisioningService; +import com.decathlon.idp_core.infrastructure.adapters.api.exception.MissingPrincipalIdentifierException; +import com.decathlon.idp_core.infrastructure.adapters.api.handler.ApiErrorResponseWriter; +import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; +import com.fasterxml.jackson.databind.ObjectMapper; + +class GlobalAuthorizationFilterTest { + + private final PrincipalExtractor principalExtractor = mock(PrincipalExtractor.class); + private final PrincipalProvisioningService provisioningService = mock( + PrincipalProvisioningService.class); + private final GlobalAuthorizationService authorizationService = mock( + GlobalAuthorizationService.class); + private final PrincipalInfo principal = new PrincipalInfo("platform-user", PrincipalKind.HUMAN, + "Platform User", Map.of(), List.of()); + private final AuthorizationRequestFactory requestFactory = new AuthorizationRequestFactory( + TestHandlerMappings.controllers()); + private final ApiErrorResponseWriter errorResponseWriter = new ApiErrorResponseWriter( + new ObjectMapper()); + private GlobalAuthorizationFilter filter; + private Authentication authentication; + + @BeforeEach + void setUp() { + var policy = new AuthorizationPolicy(AuthorizationMode.GLOBAL, Set.of(), Optional.empty()); + filter = new GlobalAuthorizationFilter(principalExtractor, provisioningService, + authorizationService, policy, requestFactory, errorResponseWriter); + authentication = mock(Authentication.class); + when(authentication.isAuthenticated()).thenReturn(true); + SecurityContextHolder.getContext().setAuthentication(authentication); + when(principalExtractor.extractPrincipalInfo(authentication)).thenReturn(principal); + when(provisioningService.findPrincipalWithSameKind(principal)).thenReturn(Optional.empty()); + } + + @AfterEach + void clearSecurityContext() { + SecurityContextHolder.clearContext(); + } + + @ParameterizedTest + @MethodSource("readMethods") + void shouldMarkReadMethodsAsReadAndContinue(String method) throws ServletException, IOException { + var request = new MockHttpServletRequest("GET", "/api/v1/entities"); + request.setMethod(method); + var response = new MockHttpServletResponse(); + FilterChain chain = (req, res) -> { + }; + + filter.doFilter(request, response, chain); + + var requestCaptor = org.mockito.ArgumentCaptor.forClass(AuthorizationRequest.class); + verify(authorizationService).authorize(requestCaptor.capture(), any(AuthorizationPolicy.class)); + assertThat(requestCaptor.getValue().action()).isEqualTo(AuthorizationAction.READ); + assertThat(response.getStatus()).isEqualTo(200); + } + + @Test + void shouldClassifyPostEntitySearchAsRead() throws ServletException, IOException { + var request = new MockHttpServletRequest("POST", "/api/v1/entities/search"); + var response = new MockHttpServletResponse(); + + filter.doFilter(request, response, (req, res) -> { + }); + + var requestCaptor = org.mockito.ArgumentCaptor.forClass(AuthorizationRequest.class); + verify(authorizationService).authorize(requestCaptor.capture(), any(AuthorizationPolicy.class)); + assertThat(requestCaptor.getValue().action()).isEqualTo(AuthorizationAction.READ); + } + + @Test + void shouldClassifyWebhookCreationAsPlatformAdminOnlyResource() + throws ServletException, IOException { + var request = new MockHttpServletRequest("POST", "/api/v1/inbound_webhooks"); + var response = new MockHttpServletResponse(); + + filter.doFilter(request, response, (req, res) -> { + }); + + var requestCaptor = org.mockito.ArgumentCaptor.forClass(AuthorizationRequest.class); + verify(authorizationService).authorize(requestCaptor.capture(), any(AuthorizationPolicy.class)); + assertThat(requestCaptor.getValue().action()).isEqualTo(AuthorizationAction.CREATE); + assertThat(requestCaptor.getValue().resource().type()) + .isEqualTo(AuthorizationResource.INBOUND_WEBHOOK_CONFIGURATION); + } + + @Test + void shouldReusePrincipalResolvedByJitProvisioning() throws ServletException, IOException { + Entity principalEntity = new Entity(null, "principal", "Platform User", "platform-user", + List.of(), List.of()); + var request = new MockHttpServletRequest("GET", "/api/v1/entities"); + request.setAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE, + new ProvisionedPrincipalContext(principal, Optional.of(principalEntity))); + + filter.doFilter(request, new MockHttpServletResponse(), (req, res) -> { + }); + + verify(principalExtractor, never()).extractPrincipalInfo(any()); + verify(provisioningService, never()).findPrincipalWithSameKind(any()); + var requestCaptor = org.mockito.ArgumentCaptor.forClass(AuthorizationRequest.class); + verify(authorizationService).authorize(requestCaptor.capture(), any(AuthorizationPolicy.class)); + assertThat(requestCaptor.getValue().principalEntity()).contains(principalEntity); + } + + @Test + void shouldReturnForbiddenAndStopChainWhenAuthorizationIsDenied() + throws ServletException, IOException { + var request = new MockHttpServletRequest("POST", "/api/v1/entities"); + var response = new MockHttpServletResponse(); + AtomicInteger downstreamMutations = new AtomicInteger(); + FilterChain chain = (req, res) -> downstreamMutations.incrementAndGet(); + doThrow(new PrincipalNotAuthorizedException("platform-user")).when(authorizationService) + .authorize(any(AuthorizationRequest.class), any(AuthorizationPolicy.class)); + + filter.doFilter(request, response, chain); + + assertThat(response.getStatus()).isEqualTo(403); + assertThat(response.getContentType()).startsWith("application/problem+json"); + assertThat(response.getContentAsString()).contains("\"type\":\"about:blank\"", + "\"title\":\"Forbidden\"", "\"status\":403", + "\"detail\":\"Principal is not authorized to perform this operation\"", + "\"instance\":\"/api/v1/entities\"", "\"error\":\"FORBIDDEN\"", + "\"error_description\":\"Principal is not authorized to perform this operation\"", + "\"timestamp\":"); + assertThat(downstreamMutations).hasValue(0); + } + + @Test + void shouldRejectMissingPrincipalIdentifierAsUnauthorized() throws ServletException, IOException { + var request = new MockHttpServletRequest("GET", "/api/v1/entities"); + var response = new MockHttpServletResponse(); + FilterChain chain = mock(FilterChain.class); + when(principalExtractor.extractPrincipalInfo(authentication)) + .thenThrow(new MissingPrincipalIdentifierException("id")); + + filter.doFilter(request, response, chain); + + assertThat(response.getStatus()).isEqualTo(401); + assertThat(response.getContentType()).startsWith("application/problem+json"); + assertThat(response.getContentAsString()).contains("\"type\":\"about:blank\"", + "\"title\":\"Unauthorized\"", "\"status\":401", + "\"detail\":\"Required principal identifier claim 'id' is missing or blank\"", + "\"instance\":\"/api/v1/entities\"", "\"error\":\"UNAUTHORIZED\"", + "\"error_description\":\"Required principal identifier claim 'id' is missing or blank\"", + "\"timestamp\":"); + verify(chain, never()).doFilter(any(), any()); + verify(authorizationService, never()).authorize(any(), any()); + } + + @Test + void shouldTreatNonUppercaseReadMethodsAsWrites() throws ServletException, IOException { + var request = new MockHttpServletRequest("POST", "/api/v1/entities"); + request.setMethod("get"); + var response = new MockHttpServletResponse(); + FilterChain chain = mock(FilterChain.class); + doThrow(new PrincipalNotAuthorizedException("platform-user")).when(authorizationService) + .authorize(any(AuthorizationRequest.class), any(AuthorizationPolicy.class)); + + filter.doFilter(request, response, chain); + + assertThat(response.getStatus()).isEqualTo(403); + verify(chain, never()).doFilter(any(), any()); + } + + @Test + void shouldFailClosedWhenPrincipalLookupFails() throws ServletException, IOException { + var request = new MockHttpServletRequest("POST", "/api/v1/entities"); + var response = new MockHttpServletResponse(); + FilterChain chain = mock(FilterChain.class); + when(provisioningService.findPrincipalWithSameKind(principal)) + .thenThrow(new IllegalStateException("catalog unavailable")); + + assertThatThrownBy(() -> filter.doFilter(request, response, chain)) + .isInstanceOf(IllegalStateException.class); + verify(chain, never()).doFilter(any(), any()); + } + + private static Stream readMethods() { + return Stream.of("GET", "HEAD", "OPTIONS"); + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/JitProvisioningFilterTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/JitProvisioningFilterTest.java index 4229ee21..9f0635aa 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/JitProvisioningFilterTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/JitProvisioningFilterTest.java @@ -10,6 +10,8 @@ import java.io.IOException; import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -21,19 +23,29 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationMode; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.domain.model.entity.Entity; import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; import com.decathlon.idp_core.domain.model.principal.PrincipalKind; import com.decathlon.idp_core.domain.service.principal.PrincipalProvisioningService; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.AuthenticationProperties; +import com.decathlon.idp_core.infrastructure.adapters.api.configuration.PrincipalProvisioningMode; +import com.decathlon.idp_core.infrastructure.adapters.api.configuration.PrincipalProvisioningProperties; +import com.decathlon.idp_core.infrastructure.adapters.api.exception.MissingPrincipalIdentifierException; +import com.decathlon.idp_core.infrastructure.adapters.api.handler.ApiErrorResponseWriter; import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; @ExtendWith(MockitoExtension.class) @@ -48,6 +60,15 @@ class JitProvisioningFilterTest { @Mock private AuthenticationProperties authProperties; + @Mock + private PrincipalProvisioningProperties provisioningProperties; + + @Mock + private AuthorizationPolicy authorizationPolicy; + + @Mock + private ApiErrorResponseWriter errorResponseWriter; + @Mock private HttpServletRequest request; @@ -82,6 +103,13 @@ void doFilterInternal_whenAuthenticatedUser_provisionsPrincipalAndContinuesChain when(principalInfo.identifier()).thenReturn("user-123"); when(principalInfo.kind()).thenReturn(PrincipalKind.valueOf("HUMAN")); when(principalExtractor.extractPrincipalInfo(auth)).thenReturn(principalInfo); + when(provisioningProperties.mode()).thenReturn(PrincipalProvisioningMode.JIT); + Entity principalEntity = new Entity(null, "principal", "User", "user-123", + List.of(new com.decathlon.idp_core.domain.model.entity.Property(null, "kind", "HUMAN")), + List.of()); + when(provisioningService.provisionPrincipal(principalInfo)).thenReturn(principalEntity); + when(provisioningService.findPrincipalWithSameKind(principalInfo)) + .thenReturn(Optional.of(principalEntity)); // Act jitProvisioningFilter.doFilterInternal(request, response, filterChain); @@ -89,9 +117,144 @@ void doFilterInternal_whenAuthenticatedUser_provisionsPrincipalAndContinuesChain // Assert verify(principalExtractor).extractPrincipalInfo(auth); verify(provisioningService).provisionPrincipal(principalInfo); + verify(request).setAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE, + new ProvisionedPrincipalContext(principalInfo, Optional.of(principalEntity))); + verify(filterChain).doFilter(request, response); + } + + @Test + void doFilterInternal_inLinkOnlyMode_linksExistingPrincipalWithoutProvisioning() + throws ServletException, IOException { + Authentication auth = mock(Authentication.class); + when(auth.isAuthenticated()).thenReturn(true); + SecurityContextHolder.getContext().setAuthentication(auth); + PrincipalInfo principalInfo = new PrincipalInfo("user-123", PrincipalKind.HUMAN, "User", + java.util.Map.of(), List.of()); + Entity principalEntity = new Entity(null, "principal", "User", "user-123", + List.of(new com.decathlon.idp_core.domain.model.entity.Property(null, "kind", "HUMAN")), + List.of()); + when(provisioningProperties.mode()).thenReturn(PrincipalProvisioningMode.LINK_ONLY); + when(principalExtractor.extractPrincipalInfo(auth)).thenReturn(principalInfo); + when(provisioningService.findPrincipalWithSameKind(principalInfo)) + .thenReturn(Optional.of(principalEntity)); + + jitProvisioningFilter.doFilterInternal(request, response, filterChain); + + verify(provisioningService, never()).provisionPrincipal(any()); + verify(request).setAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE, + new ProvisionedPrincipalContext(principalInfo, Optional.of(principalEntity))); verify(filterChain).doFilter(request, response); } + @Test + void doFilterInternal_inLinkOnlyMode_rejectsMissingIdentity() + throws ServletException, IOException { + Authentication auth = mock(Authentication.class); + when(auth.isAuthenticated()).thenReturn(true); + SecurityContextHolder.getContext().setAuthentication(auth); + PrincipalInfo principalInfo = new PrincipalInfo("unregistered", PrincipalKind.HUMAN, "User", + java.util.Map.of(), List.of()); + when(provisioningProperties.mode()).thenReturn(PrincipalProvisioningMode.LINK_ONLY); + when(principalExtractor.extractPrincipalInfo(auth)).thenReturn(principalInfo); + + jitProvisioningFilter.doFilterInternal(request, response, filterChain); + + verify(provisioningService, never()).provisionPrincipal(any()); + verify(errorResponseWriter).write(request, response, HttpStatus.UNAUTHORIZED, + "No linked principal matches the authenticated identity"); + verify(filterChain, never()).doFilter(any(), any()); + } + + @Test + void doFilterInternal_inLinkOnlyMode_provisionsAndAllowsUnlinkedGlobalPrincipal() + throws ServletException, IOException { + Authentication auth = mock(Authentication.class); + when(auth.isAuthenticated()).thenReturn(true); + SecurityContextHolder.getContext().setAuthentication(auth); + PrincipalInfo principalInfo = new PrincipalInfo("global-user", PrincipalKind.HUMAN, "User", + java.util.Map.of(), List.of()); + when(provisioningProperties.mode()).thenReturn(PrincipalProvisioningMode.LINK_ONLY); + when(authorizationPolicy.mode()).thenReturn(AuthorizationMode.GLOBAL); + when(authorizationPolicy.globalPrincipalIdentifiers()) + .thenReturn(java.util.Set.of("global-user")); + when(principalExtractor.extractPrincipalInfo(auth)).thenReturn(principalInfo); + when(provisioningService.findPrincipalWithSameKind(principalInfo)).thenReturn(Optional.empty()); + Entity principalEntity = new Entity(null, "principal", "User", "global-user", + List.of(new com.decathlon.idp_core.domain.model.entity.Property(null, "kind", "HUMAN")), + List.of()); + when(provisioningService.provisionGlobalAdministrator(principalInfo)) + .thenReturn(principalEntity); + + jitProvisioningFilter.doFilterInternal(request, response, filterChain); + + verify(provisioningService).provisionGlobalAdministrator(principalInfo); + verify(request).setAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE, + new ProvisionedPrincipalContext(principalInfo, Optional.of(principalEntity))); + verify(filterChain).doFilter(request, response); + verify(errorResponseWriter, never()).write(any(), any(), any(), any()); + } + + @ParameterizedTest(name = "{0} {1} wrongKind={2}") + @MethodSource("principalLinkScenarios") + void doFilterInternal_appliesProvisioningModeForBothActorKinds(PrincipalProvisioningMode mode, + PrincipalKind kind, boolean existingWrongKind) throws ServletException, IOException { + Authentication auth = mock(Authentication.class); + when(auth.isAuthenticated()).thenReturn(true); + SecurityContextHolder.getContext().setAuthentication(auth); + PrincipalInfo principalInfo = new PrincipalInfo("linked-identity", kind, "Actor", + java.util.Map.of(), List.of()); + when(provisioningProperties.mode()).thenReturn(mode); + when(principalExtractor.extractPrincipalInfo(auth)).thenReturn(principalInfo); + + boolean shouldContinue = mode == PrincipalProvisioningMode.JIT && !existingWrongKind; + if (mode == PrincipalProvisioningMode.LINK_ONLY) { + when(provisioningService.findPrincipalWithSameKind(principalInfo)) + .thenReturn(Optional.empty()); + } else if (existingWrongKind) { + String storedKind = kind == PrincipalKind.HUMAN ? "SERVICE_ACCOUNT" : "HUMAN"; + Entity wrongKindPrincipal = new Entity(null, "principal", "Actor", "linked-identity", + List.of( + new com.decathlon.idp_core.domain.model.entity.Property(null, "kind", storedKind)), + List.of()); + when(provisioningService.provisionPrincipal(principalInfo)).thenReturn(wrongKindPrincipal); + when(provisioningService.findPrincipalWithSameKind(principalInfo)) + .thenReturn(Optional.empty()); + } else { + Entity matchingPrincipal = new Entity(null, "principal", "Actor", "linked-identity", + List.of( + new com.decathlon.idp_core.domain.model.entity.Property(null, "kind", kind.name())), + List.of()); + when(provisioningService.provisionPrincipal(principalInfo)).thenReturn(matchingPrincipal); + when(provisioningService.findPrincipalWithSameKind(principalInfo)) + .thenReturn(Optional.of(matchingPrincipal)); + } + + jitProvisioningFilter.doFilterInternal(request, response, filterChain); + + if (shouldContinue) { + verify(filterChain).doFilter(request, response); + verify(errorResponseWriter, never()).write(any(), any(), any(), any()); + } else { + verify(errorResponseWriter).write(request, response, HttpStatus.UNAUTHORIZED, + "No linked principal matches the authenticated identity"); + verify(filterChain, never()).doFilter(any(), any()); + } + if (mode == PrincipalProvisioningMode.LINK_ONLY) { + verify(provisioningService, never()).provisionPrincipal(any()); + } + } + + private static Stream principalLinkScenarios() { + Stream.Builder scenarios = Stream.builder(); + for (PrincipalKind kind : PrincipalKind.values()) { + for (PrincipalProvisioningMode mode : PrincipalProvisioningMode.values()) { + scenarios.add(Arguments.of(mode, kind, false)); + scenarios.add(Arguments.of(mode, kind, true)); + } + } + return scenarios.build(); + } + @Test void doFilterInternal_whenAuthenticationIsNull_skipsProvisioningAndContinuesChain() throws ServletException, IOException { @@ -141,7 +304,7 @@ void doFilterInternal_whenAnonymousAuthentication_skipsProvisioningAndContinuesC } @Test - void doFilterInternal_whenProvisioningThrowsException_failsOpenAndContinuesChain() + void doFilterInternal_whenProvisioningThrowsException_failsClosed() throws ServletException, IOException { // Arrange Authentication auth = mock(Authentication.class); @@ -156,7 +319,64 @@ void doFilterInternal_whenProvisioningThrowsException_failsOpenAndContinuesChain // Act & Assert (Should not throw exception) jitProvisioningFilter.doFilterInternal(request, response, filterChain); - verify(filterChain).doFilter(request, response); + verify(errorResponseWriter).write(request, response, HttpStatus.SERVICE_UNAVAILABLE, + "Unable to verify your access at this time. Please try again later."); + verify(filterChain, never()).doFilter(any(), any()); + } + + @Test + void doFilterInternal_inLinkOnlyMode_whenPrincipalLookupThrowsException_failsClosed() + throws ServletException, IOException { + Authentication auth = mock(Authentication.class); + when(auth.isAuthenticated()).thenReturn(true); + SecurityContextHolder.getContext().setAuthentication(auth); + PrincipalInfo principalInfo = new PrincipalInfo("unlinked", PrincipalKind.HUMAN, "User", + java.util.Map.of(), List.of()); + when(provisioningProperties.mode()).thenReturn(PrincipalProvisioningMode.LINK_ONLY); + when(principalExtractor.extractPrincipalInfo(auth)).thenReturn(principalInfo); + when(provisioningService.findPrincipalWithSameKind(principalInfo)) + .thenThrow(new RuntimeException("Catalog service unavailable")); + + jitProvisioningFilter.doFilterInternal(request, response, filterChain); + + verify(errorResponseWriter).write(request, response, HttpStatus.SERVICE_UNAVAILABLE, + "Unable to verify your access at this time. Please try again later."); + verify(filterChain, never()).doFilter(any(), any()); + } + + @Test + void doFilterInternal_whenIdentifierClaimIsMissing_rejectsAuthentication() + throws ServletException, IOException { + Authentication auth = mock(Authentication.class); + when(auth.isAuthenticated()).thenReturn(true); + SecurityContextHolder.getContext().setAuthentication(auth); + when(principalExtractor.extractPrincipalInfo(auth)) + .thenThrow(new MissingPrincipalIdentifierException("id")); + + jitProvisioningFilter.doFilterInternal(request, response, filterChain); + + verify(errorResponseWriter).write(request, response, HttpStatus.UNAUTHORIZED, + "Required principal identifier claim 'id' is missing or blank"); + verify(filterChain, never()).doFilter(any(), any()); + verify(provisioningService, never()).provisionPrincipal(any()); + } + + @Test + void doFilterInternal_whenOtherPrincipalExtractionFailureOccurs_propagatesIt() + throws ServletException, IOException { + Authentication auth = mock(Authentication.class); + when(auth.isAuthenticated()).thenReturn(true); + SecurityContextHolder.getContext().setAuthentication(auth); + when(principalExtractor.extractPrincipalInfo(auth)) + .thenThrow(new IllegalStateException("Unexpected extraction failure")); + + org.assertj.core.api.Assertions + .assertThatThrownBy( + () -> jitProvisioningFilter.doFilterInternal(request, response, filterChain)) + .isInstanceOf(IllegalStateException.class).hasMessage("Unexpected extraction failure"); + + verify(errorResponseWriter, never()).write(any(), any(), any(), any()); + verify(filterChain, never()).doFilter(any(), any()); } @ParameterizedTest diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/TestHandlerMappings.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/TestHandlerMappings.java new file mode 100644 index 00000000..eae787d3 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/TestHandlerMappings.java @@ -0,0 +1,40 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.auth; + +import static org.mockito.Mockito.mock; + +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import com.decathlon.idp_core.infrastructure.adapters.api.controller.AuditController; +import com.decathlon.idp_core.infrastructure.adapters.api.controller.EntityController; +import com.decathlon.idp_core.infrastructure.adapters.api.controller.EntityDynamicMappingController; +import com.decathlon.idp_core.infrastructure.adapters.api.controller.EntityTemplateController; +import com.decathlon.idp_core.infrastructure.adapters.api.controller.InboundWebhookConfigurationController; + +/// Builds a real MVC handler mapping over mocked controllers to test route-based authorization. +final class TestHandlerMappings { + + private TestHandlerMappings() { + } + + static RequestMappingHandlerMapping controllers() { + var context = new GenericApplicationContext(); + context.registerBean("entityController", EntityController.class, + () -> mock(EntityController.class)); + context.registerBean("auditController", AuditController.class, + () -> mock(AuditController.class)); + context.registerBean("entityTemplateController", EntityTemplateController.class, + () -> mock(EntityTemplateController.class)); + context.registerBean("entityDynamicMappingController", EntityDynamicMappingController.class, + () -> mock(EntityDynamicMappingController.class)); + context.registerBean("inboundWebhookConfigurationController", + InboundWebhookConfigurationController.class, + () -> mock(InboundWebhookConfigurationController.class)); + context.refresh(); + + var mapping = new RequestMappingHandlerMapping(); + mapping.setApplicationContext(context); + mapping.afterPropertiesSet(); + return mapping; + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UnifiedUserProviderTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UnifiedUserProviderTest.java index 7bb2ce18..533f5b26 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UnifiedUserProviderTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/UnifiedUserProviderTest.java @@ -2,8 +2,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,19 +16,21 @@ import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.oauth2.core.oidc.user.OidcUser; -import org.springframework.security.oauth2.core.user.OAuth2User; -import org.springframework.security.oauth2.jwt.Jwt; -import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; + +import com.decathlon.idp_core.domain.model.principal.PrincipalInfo; +import com.decathlon.idp_core.domain.model.principal.PrincipalKind; +import com.decathlon.idp_core.infrastructure.adapters.api.principal.PrincipalExtractor; class UnifiedUserProviderTest { private UnifiedUserProvider unifiedUserProvider; private SecurityContext securityContext; + private PrincipalExtractor principalExtractor; @BeforeEach void setUp() { - unifiedUserProvider = new UnifiedUserProvider(); + principalExtractor = mock(PrincipalExtractor.class); + unifiedUserProvider = new UnifiedUserProvider(principalExtractor); securityContext = mock(SecurityContext.class); SecurityContextHolder.setContext(securityContext); } @@ -63,84 +69,15 @@ void shouldReturnUnknownWhenAnonymousUser() { } @Test - void shouldReturnSubjectWhenJwtAuthentication() { - JwtAuthenticationToken jwtAuth = mock(JwtAuthenticationToken.class); - Jwt jwt = mock(Jwt.class); - - when(jwtAuth.isAuthenticated()).thenReturn(true); - when(jwtAuth.getToken()).thenReturn(jwt); - when(jwt.getSubject()).thenReturn("jwt-user-id"); - when(securityContext.getAuthentication()).thenReturn(jwtAuth); - - assertThat(unifiedUserProvider.getAuthId()).isEqualTo("jwt-user-id"); - } - - @Test - void shouldReturnSubjectWhenOidcUser() { + void shouldReturnIdentifierExtractedForAuthenticatedPrincipal() { Authentication auth = mock(Authentication.class); - OidcUser oidcUser = mock(OidcUser.class); when(auth.isAuthenticated()).thenReturn(true); - when(auth.getPrincipal()).thenReturn(oidcUser); - when(oidcUser.getSubject()).thenReturn("oidc-user-id"); when(securityContext.getAuthentication()).thenReturn(auth); + when(principalExtractor.extractPrincipalInfo(auth)).thenReturn(principal("stable-id")); - assertThat(unifiedUserProvider.getAuthId()).isEqualTo("oidc-user-id"); - } - - @Test - void shouldReturnSubAttributeWhenOAuth2User() { - Authentication auth = mock(Authentication.class); - OAuth2User oauth2User = mock(OAuth2User.class); - - when(auth.isAuthenticated()).thenReturn(true); - when(auth.getPrincipal()).thenReturn(oauth2User); - when(oauth2User.getAttribute("sub")).thenReturn("oauth2-sub-id"); - when(securityContext.getAuthentication()).thenReturn(auth); - - assertThat(unifiedUserProvider.getAuthId()).isEqualTo("oauth2-sub-id"); - } - - @Test - void shouldReturnIdAttributeWhenOAuth2UserHasNoSub() { - Authentication auth = mock(Authentication.class); - OAuth2User oauth2User = mock(OAuth2User.class); - - when(auth.isAuthenticated()).thenReturn(true); - when(auth.getPrincipal()).thenReturn(oauth2User); - when(oauth2User.getAttribute("sub")).thenReturn(null); - when(oauth2User.getAttribute("id")).thenReturn("oauth2-id-attribute"); - when(securityContext.getAuthentication()).thenReturn(auth); - - assertThat(unifiedUserProvider.getAuthId()).isEqualTo("oauth2-id-attribute"); - } - - @Test - void shouldReturnFallbackNameWhenOAuth2UserHasNoSubOrId() { - Authentication auth = mock(Authentication.class); - OAuth2User oauth2User = mock(OAuth2User.class); - - when(auth.isAuthenticated()).thenReturn(true); - when(auth.getName()).thenReturn("fallback-oauth2-name"); - when(auth.getPrincipal()).thenReturn(oauth2User); - when(oauth2User.getAttribute("sub")).thenReturn(null); - when(oauth2User.getAttribute("id")).thenReturn(null); - when(securityContext.getAuthentication()).thenReturn(auth); - - assertThat(unifiedUserProvider.getAuthId()).isEqualTo("fallback-oauth2-name"); - } - - @Test - void shouldReturnNameForBasicOrOtherAuthentication() { - Authentication auth = mock(Authentication.class); - - when(auth.isAuthenticated()).thenReturn(true); - when(auth.getName()).thenReturn("basic-auth-user"); - when(auth.getPrincipal()).thenReturn("Standard String Principal"); // N'est ni OAuth2User ni - // OidcUser - when(securityContext.getAuthentication()).thenReturn(auth); - - assertThat(unifiedUserProvider.getAuthId()).isEqualTo("basic-auth-user"); + assertThat(unifiedUserProvider.getAuthId()).isEqualTo("stable-id"); + verify(principalExtractor).extractPrincipalInfo(auth); } @Test @@ -153,4 +90,8 @@ void shouldReturnNameWhenGetNameIsCalled() { assertThat(unifiedUserProvider.getName()).isEqualTo("expected-user-name"); } + + private PrincipalInfo principal(String identifier) { + return new PrincipalInfo(identifier, PrincipalKind.HUMAN, identifier, Map.of(), List.of()); + } } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthenticationPropertiesTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthenticationPropertiesTest.java new file mode 100644 index 00000000..bd1cc925 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthenticationPropertiesTest.java @@ -0,0 +1,30 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class AuthenticationPropertiesTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(TestConfiguration.class); + + @Test + void shouldBindAuthenticationProperties() { + contextRunner + .withPropertyValues("app.security.authentication.user-claim-mappings.name=display_name", + "app.security.authentication.jit-provisioning-excluded-paths[0]=/health") + .run(context -> { + assertThat(context).hasNotFailed(); + AuthenticationProperties properties = context.getBean(AuthenticationProperties.class); + assertThat(properties.userClaimMappings()).containsEntry("name", "display_name"); + assertThat(properties.jitProvisioningExcludedPaths()).containsExactly("/health"); + }); + } + + @EnableConfigurationProperties(AuthenticationProperties.class) + static class TestConfiguration { + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationConfigurationTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationConfigurationTest.java new file mode 100644 index 00000000..8038d05d --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/AuthorizationConfigurationTest.java @@ -0,0 +1,49 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.boot.web.servlet.FilterRegistrationBean; + +import com.decathlon.idp_core.domain.model.authorization.AuthorizationMode; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationPolicy; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.GlobalAuthorizationFilter; + +class AuthorizationConfigurationTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(AuthorizationConfiguration.class) + .withBean(GlobalAuthorizationFilter.class, () -> mock(GlobalAuthorizationFilter.class)); + + @Test + void shouldBridgeConfiguredAuthorizationPropertiesIntoDomainPolicy() { + contextRunner.withPropertyValues("app.security.authorization.mode=GLOBAL", + "app.security.authorization.global-principal-identifiers=super-admin, platform-admin", + "app.security.authorization.required-principal-property=eligible").run(context -> { + assertThat(context).hasSingleBean(AuthorizationProperties.class) + .hasSingleBean(AuthorizationPolicy.class); + assertThat(context.getBean(AuthorizationPolicy.class).mode()) + .isEqualTo(AuthorizationMode.GLOBAL); + assertThat(context.getBean(AuthorizationPolicy.class).globalPrincipalIdentifiers()) + .containsExactlyInAnyOrder("super-admin", "platform-admin"); + assertThat(context.getBean(AuthorizationPolicy.class).requiredPrincipalProperty()) + .contains("eligible"); + assertThat( + context.getBean("globalAuthorizationFilterRegistration", FilterRegistrationBean.class) + .isEnabled()).isFalse(); + }); + } + + @Test + void shouldDefaultAuthorizationSettingsWhenNotConfigured() { + contextRunner.withPropertyValues("app.security.authorization.required-principal-property=") + .run(context -> { + assertThat(context.getBean(AuthorizationPolicy.class).mode()) + .isEqualTo(AuthorizationMode.GLOBAL); + assertThat(context.getBean(AuthorizationPolicy.class).requiredPrincipalProperty()) + .isEmpty(); + }); + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/JwtConfigurationTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/JwtConfigurationTest.java new file mode 100644 index 00000000..ffaced46 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/JwtConfigurationTest.java @@ -0,0 +1,73 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; +import org.springframework.security.oauth2.jwt.Jwt; + +@DisplayName("JwtConfigurationTest") +class JwtConfigurationTest { + + private static final String JWKS = "https://idp.example.com/jwks.json"; + private static final String ISSUER = "https://idp.example.com/"; + + @Test + void shouldAcceptAnyIssuerAndAudienceWhenNothingIsConfigured() { + var validator = new JwtConfiguration(JWKS, "", "").jwtValidator(); + + assertThat( + validator.validate(jwt("https://other.example.com/", List.of("other-app"))).hasErrors()) + .isFalse(); + } + + @Test + void shouldRejectExpiredTokenEvenWhenNothingIsConfigured() { + var validator = new JwtConfiguration(JWKS, null, null).jwtValidator(); + Jwt expired = Jwt.withTokenValue("t").header("alg", "RS256").issuer(ISSUER) + .issuedAt(Instant.now().minusSeconds(7200)).expiresAt(Instant.now().minusSeconds(3600)) + .build(); + + assertThat(validator.validate(expired).hasErrors()).isTrue(); + } + + @Test + void shouldRejectTokenFromAnotherIssuerWhenIssuerIsConfigured() { + var validator = new JwtConfiguration(JWKS, ISSUER, "").jwtValidator(); + + assertThat(validator.validate(jwt(ISSUER, List.of("any"))).hasErrors()).isFalse(); + assertThat(validator.validate(jwt("https://other.example.com/", List.of("any"))).hasErrors()) + .isTrue(); + } + + @Test + void shouldRejectTokenForAnotherAudienceWhenAudiencesAreConfigured() { + var validator = new JwtConfiguration(JWKS, "", " idp-core , idp-core-cli ").jwtValidator(); + + assertThat(validator.validate(jwt(ISSUER, List.of("idp-core-cli"))).hasErrors()).isFalse(); + assertThat(validator.validate(jwt(ISSUER, List.of("x", "idp-core"))).hasErrors()).isFalse(); + assertThat(validator.validate(jwt(ISSUER, List.of("other-app"))).hasErrors()).isTrue(); + } + + @Test + void shouldRejectTokenWithoutAudienceWhenAudiencesAreConfigured() { + var validator = new JwtConfiguration(JWKS, "", "idp-core").jwtValidator(); + + OAuth2TokenValidatorResult result = validator.validate(jwt(ISSUER, null)); + + assertThat(result.hasErrors()).isTrue(); + } + + private static Jwt jwt(String issuer, List audience) { + Jwt.Builder builder = Jwt.withTokenValue("t").header("alg", "RS256").issuer(issuer) + .issuedAt(Instant.now().minusSeconds(60)).expiresAt(Instant.now().plusSeconds(3600)); + if (audience != null) { + builder.audience(audience); + } + return builder.build(); + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalExtractionPropertiesTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalExtractionPropertiesTest.java new file mode 100644 index 00000000..b7d79402 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/PrincipalExtractionPropertiesTest.java @@ -0,0 +1,49 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class PrincipalExtractionPropertiesTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(TestConfiguration.class); + + @Test + void shouldBindHumanAndMachineExtractionSettings() { + contextRunner + .withPropertyValues( + "app.security.authentication.principal-extraction.human-indicator-claims[0]=uuid", + "app.security.authentication.principal-extraction.human.id-claim=uuid", + "app.security.authentication.principal-extraction.machine.id-claim=client_id", + "app.security.authentication.principal-extraction.machine.id-prefix=machine:") + .run(context -> { + assertThat(context).hasNotFailed(); + PrincipalExtractionProperties properties = context + .getBean(PrincipalExtractionProperties.class); + assertThat(properties.humanIndicatorClaims()).containsExactly("uuid"); + assertThat(properties.human().idClaim()).isEqualTo("uuid"); + assertThat(properties.machine().idClaim()).isEqualTo("client_id"); + assertThat(properties.machine().idPrefix()).isEqualTo("machine:"); + }); + } + + @Test + void shouldUseDefaultsForMissingConfiguration() { + contextRunner.run(context -> { + assertThat(context).hasNotFailed(); + PrincipalExtractionProperties properties = context + .getBean(PrincipalExtractionProperties.class); + assertThat(properties.humanIndicatorClaims()).isEmpty(); + assertThat(properties.human().idClaim()).isEqualTo("sub"); + assertThat(properties.machine().idClaim()).isEqualTo("client_id"); + assertThat(properties.machine().idPrefix()).isEmpty(); + }); + } + + @EnableConfigurationProperties(PrincipalExtractionProperties.class) + static class TestConfiguration { + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationConfigurationTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationConfigurationTest.java new file mode 100644 index 00000000..aa7fc663 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/RelationValidationConfigurationTest.java @@ -0,0 +1,47 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.env.SystemEnvironmentPropertySource; + +import com.decathlon.idp_core.domain.model.enums.RelationTargetValidationMode; + +class RelationValidationConfigurationTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(RelationValidationConfiguration.class); + + @Test + void shouldDefaultToStrictMode() { + contextRunner.run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(RelationValidationProperties.class).targetValidationMode()) + .isEqualTo(RelationTargetValidationMode.STRICT); + assertThat(context.getBean(RelationTargetValidationMode.class)) + .isEqualTo(RelationTargetValidationMode.STRICT); + }); + } + + @Test + void shouldBindTolerantModeFromEnvironmentVariable() { + contextRunner + .withInitializer(context -> context.getEnvironment().getPropertySources() + .addFirst(new SystemEnvironmentPropertySource("testEnvironment", + Map.of("APP_RELATIONS_TARGET_VALIDATION_MODE", "TOLERANT")))) + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(RelationTargetValidationMode.class)) + .isEqualTo(RelationTargetValidationMode.TOLERANT); + }); + } + + @Test + void shouldRejectUnsupportedMode() { + contextRunner.withPropertyValues("app.relations.target-validation-mode=LENIENT") + .run(context -> assertThat(context).hasFailed()); + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityRolePropertiesTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityRolePropertiesTest.java deleted file mode 100644 index bd781146..00000000 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SecurityRolePropertiesTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.decathlon.idp_core.infrastructure.adapters.api.configuration; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/// Unit tests for SecurityRoleProperties verifying correct handling of baseline role configuration. -/// when a real role managing should be put in place, this test must fail -class SecurityRolePropertiesTest { - - @Test - void shouldKeepValidRole() { - SecurityRoleProperties props = new SecurityRoleProperties("ROLE_EDITOR"); - assertEquals("ROLE_EDITOR", props.baselineRole()); - } - - @Test - void shouldDefaultToStarWhenNull() { - SecurityRoleProperties props = new SecurityRoleProperties(null); - assertEquals("*", props.baselineRole()); - } - - @Test - void shouldDefaultToStarWhenEmpty() { - SecurityRoleProperties props = new SecurityRoleProperties(""); - assertEquals("*", props.baselineRole()); - } - - @Test - void shouldDefaultToStarWhenBlank() { - SecurityRoleProperties props = new SecurityRoleProperties(" "); - assertEquals("*", props.baselineRole()); - } -} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerConfigurationTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerConfigurationTest.java new file mode 100644 index 00000000..17c7e220 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/SwaggerConfigurationTest.java @@ -0,0 +1,163 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.LinkedHashMap; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springdoc.core.customizers.GlobalOpenApiCustomizer; +import org.springframework.data.domain.PageRequest; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.media.ObjectSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import io.swagger.v3.oas.models.security.SecurityScheme; + +class SwaggerConfigurationTest { + + private final SwaggerConfiguration configuration = new SwaggerConfiguration( + "https://identity.example/token", "https://idp.example", true); + + @Test + void shouldExposeProblemDetailCustomizerForGroupedDocuments() { + assertInstanceOf(GlobalOpenApiCustomizer.class, configuration.problemDetailSchemaCustomizer()); + } + + @Test + void shouldDocumentProblemDetailExtensionsAtRootAndPreserveStandardFields() { + Schema schema = new ObjectSchema().addProperty("detail", new StringSchema()) + .addProperty("instance", new StringSchema().format("uri")) + .addProperty("properties", new ObjectSchema()); + OpenAPI openApi = new OpenAPI() + .components(new Components().addSchemas("ProblemDetail", schema)); + + configuration.problemDetailSchemaCustomizer().customise(openApi); + + assertFalse(schema.getProperties().containsKey("properties")); + assertEquals("string", schema.getProperties().get("detail").getType()); + assertEquals("uri", schema.getProperties().get("instance").getFormat()); + assertEquals("string", schema.getProperties().get("error").getType()); + assertEquals("string", schema.getProperties().get("error_description").getType()); + assertEquals("string", schema.getProperties().get("timestamp").getType()); + assertEquals("date-time", schema.getProperties().get("timestamp").getFormat()); + assertEquals(5, schema.getProperties().size()); + } + + @Test + void shouldAddExtensionsWhenProblemDetailHasNoProperties() { + Schema schema = new ObjectSchema(); + OpenAPI openApi = new OpenAPI() + .components(new Components().addSchemas("ProblemDetail", schema)); + + configuration.problemDetailSchemaCustomizer().customise(openApi); + + assertEquals(3, schema.getProperties().size()); + assertTrue(schema.getProperties().keySet() + .containsAll(List.of("error", "error_description", "timestamp"))); + } + + @Test + void shouldLeaveDocumentWithoutComponentsUnchanged() { + OpenAPI openApi = new OpenAPI(); + + configuration.problemDetailSchemaCustomizer().customise(openApi); + + assertNull(openApi.getComponents()); + } + + @Test + void shouldLeaveComponentsWithoutSchemasUnchanged() { + OpenAPI openApi = new OpenAPI().components(new Components()); + + configuration.problemDetailSchemaCustomizer().customise(openApi); + + assertNull(openApi.getComponents().getSchemas()); + } + + @Test + void shouldLeaveOtherSchemasUnchangedWhenProblemDetailIsAbsent() { + Schema schema = new ObjectSchema().addProperty("name", new StringSchema()); + OpenAPI openApi = new OpenAPI().components(new Components().addSchemas("Entity", schema)); + + configuration.problemDetailSchemaCustomizer().customise(openApi); + + assertEquals(1, openApi.getComponents().getSchemas().size()); + assertSame(schema, openApi.getComponents().getSchemas().get("Entity")); + assertEquals(1, schema.getProperties().size()); + } + + @Test + void shouldHandleEmptySchemas() { + OpenAPI openApi = new OpenAPI().components(new Components().schemas(new LinkedHashMap<>())); + + configuration.problemDetailSchemaCustomizer().customise(openApi); + + assertTrue(openApi.getComponents().getSchemas().isEmpty()); + } + + @Test + void shouldKeepCustomizationIdempotent() { + Schema schema = new ObjectSchema(); + OpenAPI openApi = new OpenAPI() + .components(new Components().addSchemas("ProblemDetail", schema)); + + configuration.problemDetailSchemaCustomizer().customise(openApi); + configuration.problemDetailSchemaCustomizer().customise(openApi); + + assertEquals(3, schema.getProperties().size()); + assertEquals("date-time", schema.getProperties().get("timestamp").getFormat()); + } + + @Test + void shouldConfigureApiMetadataAndBothAuthenticationSchemes() { + OpenAPI openApi = configuration.openAPI(); + + assertEquals("Idp core API", openApi.getInfo().getTitle()); + assertEquals("v1", openApi.getInfo().getVersion()); + assertEquals("https://idp.example", openApi.getServers().getFirst().getUrl()); + var schemes = openApi.getComponents().getSecuritySchemes(); + assertEquals(SecurityScheme.Type.OAUTH2, schemes.get("clientId").getType()); + assertEquals("https://identity.example/token", + schemes.get("clientId").getFlows().getClientCredentials().getTokenUrl()); + assertEquals(SecurityScheme.Type.HTTP, schemes.get("bearer").getType()); + assertEquals("bearer", schemes.get("bearer").getScheme()); + assertEquals("JWT", schemes.get("bearer").getBearerFormat()); + assertEquals(2, openApi.getSecurity().size()); + assertTrue(openApi.getSecurity().get(0).containsKey("clientId")); + assertTrue(openApi.getSecurity().get(1).containsKey("bearer")); + } + + @Test + void shouldOmitSecurityWhenAuthenticationIsDisabled() { + OpenAPI openApi = new SwaggerConfiguration(" ", "http://localhost:8080", false).openAPI(); + + assertNull(openApi.getComponents()); + assertNull(openApi.getSecurity()); + } + + @Test + void shouldConfigureInternalApiGroup() { + var group = configuration.allApis(); + + assertEquals("internal", group.getGroup()); + assertEquals(List.of("/**"), group.getPathsToMatch()); + } + + @Test + void shouldConstructPaginatedResponseModels() { + var pageable = PageRequest.of(0, 20); + var pages = List.of(new SwaggerConfiguration.TemplatePageResponse(List.of(), pageable, 0), + new SwaggerConfiguration.EntityPageResponse(List.of(), pageable, 0), + new SwaggerConfiguration.WebhookConnectorPageResponse(List.of(), pageable, 0), + new SwaggerConfiguration.EntityDynamicMappingPageResponse(List.of(), pageable, 0)); + + for (var page : pages) { + assertTrue(page.getContent().isEmpty()); + assertEquals(pageable, page.getPageable()); + assertEquals(0, page.getTotalElements()); + } + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/FallbackDenyAllFilterChainConfigTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/FallbackDenyAllFilterChainConfigTest.java new file mode 100644 index 00000000..08164b76 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/FallbackDenyAllFilterChainConfigTest.java @@ -0,0 +1,62 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.configuration.security.chains; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.DefaultSecurityFilterChain; +import org.springframework.security.web.SecurityFilterChain; + +@DisplayName("FallbackDenyAllFilterChainConfigTest") +@ExtendWith(MockitoExtension.class) +class FallbackDenyAllFilterChainConfigTest { + + @Mock + DefaultSecurityFilterChain securityFilterChain; + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(FallbackDenyAllFilterChainConfig.class)) + .withBean(HttpSecurity.class, this::httpSecurity); + + @Test + void shouldCreateDenyAllChainWhenNoAuthenticationPropertyIsSet() { + contextRunner + .run(context -> assertThat(context).hasSingleBean(FallbackDenyAllFilterChainConfig.class) + .hasSingleBean(SecurityFilterChain.class)); + } + + @Test + void shouldCreateDenyAllChainWhenEveryModeIsExplicitlyDisabled() { + contextRunner + .withPropertyValues("app.security.authentication.jwt.enabled=false", + "app.security.authentication.oauth2-login.enabled=false", + "app.security.authentication.api-key.enabled=false", + "app.security.authentication.mock.enabled=false") + .run(context -> assertThat(context).hasSingleBean(FallbackDenyAllFilterChainConfig.class) + .hasSingleBean(SecurityFilterChain.class)); + } + + @ParameterizedTest + @ValueSource(strings = {"jwt", "oauth2-login", "api-key", "mock"}) + void shouldNotCreateDenyAllChainWhenOneModeIsEnabled(String mode) { + contextRunner.withPropertyValues("app.security.authentication." + mode + ".enabled=true") + .run(context -> assertThat(context).doesNotHaveBean(FallbackDenyAllFilterChainConfig.class) + .doesNotHaveBean(SecurityFilterChain.class)); + } + + private HttpSecurity httpSecurity() { + HttpSecurity http = mock(HttpSecurity.class, org.mockito.Answers.RETURNS_DEEP_STUBS); + when(http.build()).thenReturn(securityFilterChain); + return http; + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/JwtFilterChainConfigTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/JwtFilterChainConfigTest.java index acc3a441..53b321d7 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/JwtFilterChainConfigTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/JwtFilterChainConfigTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.jupiter.api.DisplayName; @@ -16,6 +17,7 @@ import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.SecurityFilterChain; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.GlobalAuthorizationFilter; import com.decathlon.idp_core.infrastructure.adapters.api.auth.JitProvisioningFilter; @DisplayName("JwtFilterChainConfigTest") @@ -28,6 +30,7 @@ class JwtFilterChainConfigTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JwtFilterChainConfig.class)) .withBean(JitProvisioningFilter.class, () -> mock(JitProvisioningFilter.class)) + .withBean(GlobalAuthorizationFilter.class, () -> mock(GlobalAuthorizationFilter.class)) .withBean(JwtAuthenticationConverter.class, JwtAuthenticationConverter::new) .withBean(HttpSecurity.class, () -> httpSecurity()); @@ -45,9 +48,28 @@ void shouldNotCreateJwtFilterChainWhenDisabled() { .doesNotHaveBean(SecurityFilterChain.class)); } + @Test + void shouldRegisterGlobalAuthorizationAfterJitProvisioning() { + var jitFilter = mock(JitProvisioningFilter.class); + var authorizationFilter = mock(GlobalAuthorizationFilter.class); + var configuration = new JwtFilterChainConfig(jitFilter, authorizationFilter, + new JwtAuthenticationConverter()); + HttpSecurity http = httpSecurity(); + + configuration.jwtSecurityFilterChain(http); + + verify(http).addFilterAfter(authorizationFilter, JitProvisioningFilter.class); + } + private HttpSecurity httpSecurity() { HttpSecurity http = mock(HttpSecurity.class, org.mockito.Answers.RETURNS_DEEP_STUBS); when(http.build()).thenReturn(securityFilterChain); + when(http.authorizeHttpRequests(org.mockito.ArgumentMatchers.any())).thenReturn(http); + when(http.cors(org.mockito.ArgumentMatchers.any())).thenReturn(http); + when(http.oauth2ResourceServer(org.mockito.ArgumentMatchers.any())).thenReturn(http); + when( + http.addFilterAfter(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .thenReturn(http); return http; } } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/MockFilterChainConfigTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/MockFilterChainConfigTest.java index 2cb912c3..a877727e 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/MockFilterChainConfigTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/MockFilterChainConfigTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; @@ -32,6 +33,7 @@ import org.springframework.security.web.SecurityFilterChain; import com.decathlon.idp_core.domain.exception.mock.MockSecurityConfigurationException; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.GlobalAuthorizationFilter; import com.decathlon.idp_core.infrastructure.adapters.api.auth.JitProvisioningFilter; /// Unit tests for MockFilterChainConfig and MockJwtAuthenticationFilter. @@ -78,11 +80,17 @@ void shouldInjectMockJwtAuthenticationAndClearAfterwards() throws ServletExcepti private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MockFilterChainConfig.class)) .withBean(JitProvisioningFilter.class, () -> mock(JitProvisioningFilter.class)) + .withBean(GlobalAuthorizationFilter.class, () -> mock(GlobalAuthorizationFilter.class)) .withBean(HttpSecurity.class, this::httpSecurity); private HttpSecurity httpSecurity() { HttpSecurity http = mock(HttpSecurity.class, org.mockito.Answers.RETURNS_DEEP_STUBS); when(http.build()).thenReturn(securityFilterChain); + when(http.sessionManagement(any())).thenReturn(http); + when(http.cors(any())).thenReturn(http); + when(http.authorizeHttpRequests(any())).thenReturn(http); + when(http.addFilterBefore(any(), any())).thenReturn(http); + when(http.addFilterAfter(any(), any())).thenReturn(http); return http; } @@ -113,7 +121,8 @@ void shouldNotLoadConfigurationWhenPropertyIsMissing() { void shouldThrowMockFilterChainConfigExceptionWhenHttpConfigFails() { // Given JitProvisioningFilter jitProvisioningFilterMock = mock(JitProvisioningFilter.class); - MockFilterChainConfig configuration = new MockFilterChainConfig(jitProvisioningFilterMock); + MockFilterChainConfig configuration = new MockFilterChainConfig(jitProvisioningFilterMock, + mock(GlobalAuthorizationFilter.class)); HttpSecurity httpSecurityMock = mock(HttpSecurity.class); RuntimeException simulatedError = new RuntimeException("Internal simulated Error"); when(httpSecurityMock.sessionManagement(any())).thenThrow(simulatedError); @@ -128,6 +137,18 @@ void shouldThrowMockFilterChainConfigExceptionWhenHttpConfigFails() { @DisplayName("JWT Token Creation Tests") class JwtTokenCreationTests { + @Test + void shouldRegisterGlobalAuthorizationAfterJitProvisioning() { + var jitFilter = mock(JitProvisioningFilter.class); + var authorizationFilter = mock(GlobalAuthorizationFilter.class); + var configuration = new MockFilterChainConfig(jitFilter, authorizationFilter); + HttpSecurity http = httpSecurity(); + + configuration.mockSecurityFilterChain(http); + + verify(http).addFilterAfter(authorizationFilter, JitProvisioningFilter.class); + } + @Test @DisplayName("Should create mock JWT with correct subject") void shouldCreateMockJwtWithCorrectSubject() throws ServletException, IOException { diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/OAuth2LoginFilterChainConfigTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/OAuth2LoginFilterChainConfigTest.java index b5b5639a..38239a53 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/OAuth2LoginFilterChainConfigTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/OAuth2LoginFilterChainConfigTest.java @@ -1,7 +1,9 @@ package com.decathlon.idp_core.infrastructure.adapters.api.configuration.security.chains; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.jupiter.api.DisplayName; @@ -16,6 +18,7 @@ import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.SecurityFilterChain; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.GlobalAuthorizationFilter; import com.decathlon.idp_core.infrastructure.adapters.api.auth.JitProvisioningFilter; @DisplayName("OAuth2LoginFilterChainConfigTest") @@ -28,6 +31,7 @@ class OAuth2LoginFilterChainConfigTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(OAuth2LoginFilterChainConfig.class)) .withBean(JitProvisioningFilter.class, () -> mock(JitProvisioningFilter.class)) + .withBean(GlobalAuthorizationFilter.class, () -> mock(GlobalAuthorizationFilter.class)) .withBean(ClientRegistrationRepository.class, () -> mock(ClientRegistrationRepository.class)) .withBean(HttpSecurity.class, this::httpSecurity); @@ -50,15 +54,34 @@ void shouldNotCreateOauth2LoginFilterChainWithoutClientRegistration() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(OAuth2LoginFilterChainConfig.class)) .withBean(JitProvisioningFilter.class, () -> mock(JitProvisioningFilter.class)) + .withBean(GlobalAuthorizationFilter.class, () -> mock(GlobalAuthorizationFilter.class)) .withBean(HttpSecurity.class, this::httpSecurity) .withPropertyValues("app.security.authentication.oauth2-login.enabled=true") .run(context -> assertThat(context).doesNotHaveBean(OAuth2LoginFilterChainConfig.class) .doesNotHaveBean(SecurityFilterChain.class)); } + @Test + void shouldApplyGlobalAuthorizationAfterJitProvisioning() { + var jitFilter = mock(JitProvisioningFilter.class); + var authorizationFilter = mock(GlobalAuthorizationFilter.class); + var configuration = new OAuth2LoginFilterChainConfig(jitFilter, authorizationFilter); + HttpSecurity http = httpSecurity(); + + configuration.oauth2LoginSecurityFilterChain(http); + + verify(http).addFilterAfter(authorizationFilter, JitProvisioningFilter.class); + } + private HttpSecurity httpSecurity() { HttpSecurity http = mock(HttpSecurity.class, org.mockito.Answers.RETURNS_DEEP_STUBS); when(http.build()).thenReturn(securityFilterChain); + when(http.sessionManagement(any())).thenReturn(http); + when(http.cors(any())).thenReturn(http); + when(http.csrf(any())).thenReturn(http); + when(http.authorizeHttpRequests(any())).thenReturn(http); + when(http.oauth2Login(any())).thenReturn(http); + when(http.addFilterAfter(any(), any())).thenReturn(http); return http; } } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/PublicFilterChainConfigTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/PublicFilterChainConfigTest.java index 1ab65fa5..d3a4ffd6 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/PublicFilterChainConfigTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/configuration/security/chains/PublicFilterChainConfigTest.java @@ -19,7 +19,6 @@ import org.springframework.security.web.SecurityFilterChain; import com.decathlon.idp_core.infrastructure.adapters.api.configuration.AuthenticationProperties; -import com.decathlon.idp_core.infrastructure.adapters.api.configuration.AuthenticationProperties.ServiceAccountDetection; @DisplayName("PublicFilterChainConfigTest") @ExtendWith(MockitoExtension.class) @@ -41,9 +40,7 @@ void shouldCreatePublicFilterChain() { } private AuthenticationProperties authenticationProperties(List excludedPaths) { - return new AuthenticationProperties(Map.of(), - new ServiceAccountDetection(false, "legacy", "token_type", "m2m", List.of()), - excludedPaths); + return new AuthenticationProperties(Map.of(), excludedPaths); } private HttpSecurity httpSecurity() { diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditControllerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditControllerTest.java index db0c9c8c..22f6eb8a 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditControllerTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditControllerTest.java @@ -13,23 +13,24 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MockMvc; import com.decathlon.idp_core.AbstractIntegrationTest; @DisplayName("Audit Controller Integration Tests") +@Sql(scripts = { + "/db/test/R__6_insert_principal_user_for_test.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) class AuditControllerTest extends AbstractIntegrationTest { private static final String AUDIT_JSON_FILES_TEST_PATH = "integration_test/json/audit/v1/"; - - @Autowired - private MockMvc mockMvc; - private static final String AUDIT_BASE_PATH = "/api/v1/audit/entities"; private static final String ENTITY_BASE_PATH = "/api/v1/entities"; + @Autowired + private MockMvc mockMvc; @Test - @WithMockUser + @WithMockUser(username = "test-admin") @DisplayName("Should return audit history for existing entity") void getAuditHistory_shouldReturnAuditNotFound_whenEntityExistsBeforeAudit() throws Exception { String templateIdentifier = "web-service"; @@ -41,7 +42,7 @@ void getAuditHistory_shouldReturnAuditNotFound_whenEntityExistsBeforeAudit() thr } @Test - @WithMockUser + @WithMockUser(username = "test-admin") @DisplayName("Should return 404 when entity does not exist") void getAuditHistory_shouldReturn404_whenEntityDoesNotExist() throws Exception { String templateIdentifier = "non-existing-template"; @@ -62,7 +63,7 @@ void getAuditHistory_shouldReturn401_withoutAuthentication() throws Exception { } @Test - @WithMockUser(username = "test-user") + @WithMockUser(username = "test-admin") @DisplayName("Should track complete lifecycle (Create, Update, Delete) in audit history") void auditHistory_shouldTrackFullLifecycle() throws Exception { String templateIdentifier = "web-audited"; @@ -79,16 +80,16 @@ void auditHistory_shouldTrackFullLifecycle() throws Exception { // Latest action (DELETED) .andExpect(jsonPath("$[0].revision_type").value("DELETED")) - .andExpect(jsonPath("$[0].modified_by").value("test-user")) + .andExpect(jsonPath("$[0].modified_by").value("test-admin")) // Middle action (UPDATED) .andExpect(jsonPath("$[1].revision_type").value("UPDATED")) - .andExpect(jsonPath("$[1].modified_by").value("test-user")) + .andExpect(jsonPath("$[1].modified_by").value("test-admin")) .andExpect(jsonPath("$[1].snapshot.name").value("Audit Test Entity Updated")) // First action (CREATED) .andExpect(jsonPath("$[2].revision_type").value("CREATED")) - .andExpect(jsonPath("$[2].modified_by").value("test-user")) + .andExpect(jsonPath("$[2].modified_by").value("test-admin")) .andExpect(jsonPath("$[2].snapshot.name").value("Audit Test Entity")); } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityControllerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityControllerTest.java index 0ec4a066..c990ec24 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityControllerTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityControllerTest.java @@ -1,9 +1,11 @@ package com.decathlon.idp_core.infrastructure.adapters.api.controller; +import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -24,16 +26,19 @@ import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.decathlon.idp_core.AbstractIntegrationTest; import com.decathlon.idp_core.domain.constant.SearchConstraints; +import com.decathlon.idp_core.domain.constant.ValidationMessages; /// Integration tests for the EntityController REST API endpoints. These tests /// verify the behavior of entity retrieval endpoints, including pagination, /// authentication, and lookup by template identifier and entity identifier. +@TestPropertySource(properties = "app.relations.target-validation-mode=TOLERANT") public class EntityControllerTest extends AbstractIntegrationTest { private static final String TEMPLATE_IDENTIFIER = "web-service"; @@ -70,12 +75,90 @@ void getEntities_paginated_200() throws Exception { .andExpect(jsonPath("$.content[0].template_identifier").value(TEMPLATE_IDENTIFIER)); } + @Test + @DisplayName("Should accept size at the minimum bound of 1") + @WithMockUser + void getEntities_sizeMinimum_200() throws Exception { + mockMvc + .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER).param("page", "0") + .param("size", "1").accept(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.page.size").value(1)); + } + + @Test + @DisplayName("Should accept size at the maximum bound of 500") + @WithMockUser + void getEntities_sizeMaximum_200() throws Exception { + mockMvc + .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER).param("page", "0") + .param("size", "500").accept(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.page.size").value(500)); + } + + @Test + @DisplayName("Should return 400 when size is zero") + @WithMockUser + void getEntities_sizeZero_400() throws Exception { + mockMvc.perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) + .param("page", "0").param("size", "0").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("Should return 400 when size exceeds 500") + @WithMockUser + void getEntities_sizeAboveMaximum_400() throws Exception { + mockMvc.perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) + .param("page", "0").param("size", "501").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("Should return 400 when page is negative") + @WithMockUser + void getEntities_negativePage_400() throws Exception { + mockMvc + .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) + .param("page", "-1").param("size", "10").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("Should return 400 when size is not a number") + @WithMockUser + void getEntities_nonNumericSize_400() throws Exception { + mockMvc + .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER).param("page", "0") + .param("size", "abc").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andExpect( + jsonPath("$.error_description").value(ValidationMessages.PAGE_SIZE_NOT_INTEGER)); + } + + @Test + @DisplayName("Should return 400 when page is not an integer") + @WithMockUser + void getEntities_nonIntegerPage_400() throws Exception { + mockMvc + .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) + .param("page", "1.5").param("size", "10").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andExpect( + jsonPath("$.error_description").value(ValidationMessages.PAGE_INDEX_NOT_INTEGER)); + } + @Test @DisplayName("Should return 404 when template does not exist") @WithMockUser void getEntities_paginated_404_when_non_existent_template() throws Exception { - mockMvc.perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, "non-existent-template-identifier") - .accept(APPLICATION_JSON)).andExpect(status().isNotFound()); + mockMvc + .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, "non-existent-template-identifier") + .accept(APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andExpect(content().contentType(APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.status").value(404)) + .andExpect(jsonPath("$.title").value("Not Found")) + .andExpect(jsonPath("$.error").value("NOT_FOUND")) + .andExpect(jsonPath("$.error_description").exists()) + .andExpect(jsonPath("$.timestamp").exists()); } @Test @@ -100,9 +183,9 @@ void getTemplates_paginated_401_without_user_token() throws Exception { void getEntities_paginated_200_custom() throws Exception { mockMvc - .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, "monitoring-service") - .param("page", "1").param("size", "5").param("sort", "template_identifier,asc") - .accept(APPLICATION_JSON)) + .perform( + get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, "monitoring-service").param("page", "1") + .param("size", "5").param("sort", "identifier,asc").accept(APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JSON)) .andExpect(jsonPath("$.content.length()").value(1)) .andExpect(jsonPath("$.content[0].name").value("Monitoring Service 6")) @@ -112,10 +195,38 @@ void getEntities_paginated_200_custom() throws Exception { .andExpect(jsonPath("$.page.number").value(1)); } + @Test + @DisplayName("Should return entities in the requested descending order") + @WithMockUser + void getEntities_sortDescending_200() throws Exception { + mockMvc + .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) + .param("sort", "identifier,desc").accept(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content[*].identifier").value(contains("web-api-2", "web-api-1", + "graph-svc-d", "graph-svc-c", "graph-svc-b", "graph-svc-a"))); + } + + @ParameterizedTest + @CsvSource(value = { + "badField,asc;Invalid sort field 'badField'. Supported fields: identifier, name, templateIdentifier", + "identifier,sideways;Invalid sort expression 'identifier,sideways'. Expected format: field[,asc|desc] or field alone", + "name:asc;Invalid sort expression 'name:asc'. Expected format: field[,asc|desc] or field alone", + "name:desc;Invalid sort expression 'name:desc'. Expected format: field[,asc|desc] or field alone"}, delimiter = ';') + @DisplayName("Should return 400 when sort field or direction is invalid") + @WithMockUser + void getEntities_invalidSort_400(String sort, String errorDescription) throws Exception { + mockMvc + .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) + .param("sort", sort).accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error_description").value(errorDescription)); + } + @Test @DisplayName("Should return paginated entities with default pagination") @WithMockUser - void getEntities_invalid_pagination_200() throws Exception { + void getEntities_defaultPagination_200() throws Exception { mockMvc .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) .accept(APPLICATION_JSON)) @@ -199,8 +310,14 @@ void getEntities_400_malformedQuery() throws Exception { mockMvc .perform(get(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) .param("q", "noOperator").accept(APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error_description") - .value("Invalid query format, expected field:operator:value")); + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.status").value(400)) + .andExpect(jsonPath("$.title").value("Bad Request")) + .andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(jsonPath("$.error_description") + .value("Invalid query format, expected field:operator:value")) + .andExpect(jsonPath("$.timestamp").exists()); } @Test @@ -398,10 +515,24 @@ void getEntity_relationsDepth_1() throws Exception { .andExpect(status().isOk()).andExpect(jsonPath("$.identifier").value("graph-svc-a")) .andExpect(jsonPath("$.relations.uses", hasSize(1))) .andExpect(jsonPath("$.relations.uses[0].identifier").value("graph-svc-b")) + .andExpect(jsonPath("$.relations.uses[0].properties").doesNotExist()) .andExpect(jsonPath("$.relations.monitors", hasSize(1))) .andExpect(jsonPath("$.relations.monitors[0].identifier").value("graph-svc-b")); } + @Test + @DisplayName("Should include relation properties when include_relations_properties=true") + @WithMockUser + void getEntity_includeRelationsProperties() throws Exception { + mockMvc + .perform(get(ENTITIES_BY_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER, "graph-svc-a") + .param("include_relations_properties", "true").accept(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.relations.uses[0].identifier").value("graph-svc-b")) + .andExpect(jsonPath("$.relations.uses[0].properties.tier").value("silver")) + .andExpect(jsonPath("$.relations.uses[0].properties.version").value("2.0.0")); + } + @Test @DisplayName("Should return flattened depth-2 relations (a -> b -> c) when relations_depth=2") @WithMockUser @@ -558,17 +689,51 @@ void postEntity_400_when_property_not_defined_in_template() throws Exception { @Test @WithMockUser() - @DisplayName("Should return 400 when relation target entity does not exist") - void postEntity_400_when_relation_target_entity_does_not_exist() throws Exception { + @DisplayName("Should omit unresolved targets from optional relations") + void postEntity_201_omitsUnresolvedOptionalRelationTargets() throws Exception { + String entityIdentifier = "web-service-missing-relation-target-" + + java.util.UUID.randomUUID(); + String payload = getJsonTestFileContent( + ENTITY_JSON_FILES_TEST_PATH + "postEntity_optional_missing_relation_target.json") + .replace("web-service-missing-relation-target", entityIdentifier); + + try { + mockMvc + .perform(MockMvcRequestBuilders + .post(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) + .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) + .content(payload)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.identifier").value(entityIdentifier)) + .andExpect(jsonPath("$.properties.applicationName").value("catalog-api")) + .andExpect(jsonPath("$.relations.database").doesNotExist()); + } finally { + mockMvc.perform(delete(ENTITIES_BY_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER, entityIdentifier) + .accept(APPLICATION_JSON).with(csrf())).andExpect(status().isNoContent()); + } + } + + @Test + @WithMockUser + @DisplayName("Should reject an unresolved target on a required relation") + void postEntity_400_when_required_relation_target_is_unresolved() throws Exception { mockMvc - .perform( - MockMvcRequestBuilders.post(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) - .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) - .content(getJsonTestFileContent(ENTITY_JSON_FILES_TEST_PATH - + "postEntity_400_relation_target_entity_does_not_exist.json"))) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .perform(post(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, "support") + .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(""" + { + "name": "Support Entity", + "identifier": "support-missing-required-team", + "relations": [ + { + "name": "required_team", + "target_entity_identifiers": ["missing-team"] + } + ] + } + """)) + .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error_description").value(org.hamcrest.Matchers.containsString( - "Relation 'database': target entity 'missing-database' does not exist"))); + "Relation 'required_team': target entity 'missing-team' does not exist"))); } } @@ -665,8 +830,9 @@ void putEntity_400_when_property_rules_not_respected() throws Exception { @Test @WithMockUser - @DisplayName("Should return 400 when update contains a property not defined in template and a missing relation target") - void putEntity_400_when_property_not_defined_and_relation_target_missing() throws Exception { + @DisplayName("Should ignore unresolved optional relation targets while rejecting invalid properties") + void putEntity_400_when_property_not_defined_and_optional_relation_target_missing() + throws Exception { mockMvc .perform(put(ENTITIES_BY_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER, ENTITY_IDENTIFIER) .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) @@ -676,8 +842,8 @@ void putEntity_400_when_property_not_defined_and_relation_target_missing() throw .andExpect(jsonPath("$.error_description").value(org.hamcrest.Matchers.allOf( org.hamcrest.Matchers .containsString("Property 'status' is not defined in template 'web-service'"), - org.hamcrest.Matchers.containsString( - "Relation 'database': target entity 'missing-database' does not exist")))); + org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString( + "Relation 'database': target entity 'missing-database' does not exist"))))); } @Test @@ -763,6 +929,61 @@ void patchEntity_200_updates_relations() throws Exception { } } + @Test + @WithMockUser + @DisplayName("Should omit unresolved optional targets when patching relations") + void patchEntity_200_omitsUnresolvedOptionalRelationTargets() throws Exception { + String entityIdentifier = "relation-patch-" + java.util.UUID.randomUUID(); + String createPayload = """ + { + "name": "Relation Patch Entity", + "identifier": "%s", + "properties": { + "applicationName": "catalog-api", + "ownerEmail": "owner@example.com", + "environment": "DEV", + "version": "1.2.3", + "teamName": "platform-team", + "baseUrl": "https://catalog.example.com", + "port": "8080", + "protocol": "HTTP", + "programmingLanguage": "JAVA" + }, + "relations": [ + { + "name": "database", + "target_entity_identifiers": ["database-service-1"] + } + ] + } + """.formatted(entityIdentifier); + + try { + mockMvc.perform(post(ENTITIES_BY_TEMPLATE_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER) + .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) + .content(createPayload)).andExpect(status().isCreated()); + + mockMvc + .perform(patch(ENTITIES_BY_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER, entityIdentifier) + .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(""" + { + "relations": [ + { + "name": "database", + "target_entity_identifiers": ["missing-database"] + } + ] + } + """)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.properties.applicationName").value("catalog-api")) + .andExpect(jsonPath("$.relations.database").doesNotExist()); + } finally { + mockMvc.perform(delete(ENTITIES_BY_IDENTIFIER_PATH, TEMPLATE_IDENTIFIER, entityIdentifier) + .accept(APPLICATION_JSON).with(csrf())).andExpect(status().isNoContent()); + } + } + @Test @WithMockUser @DisplayName("Should return 404 when patching a non-existent entity") @@ -1023,7 +1244,7 @@ void search_200_byTemplateAndProperty() throws Exception { { "field": "property.programmingLanguage", "operation": "EQ", "value": "JAVA" } ] }, - "page": 0, "size": 20, "sort": "identifier:asc" + "page": 0, "size": 20, "sort": "identifier,asc" } """)).andExpect(status().isOk()).andReturn(); JSONAssert.assertEquals( @@ -1046,7 +1267,7 @@ void search_200_orTemplates() throws Exception { { "field": "template", "operation": "EQ", "value": "batch-job" } ] }, - "page": 0, "size": 20, "sort": "identifier:asc" + "page": 0, "size": 20, "sort": "identifier,asc" } """)).andExpect(status().isOk()).andReturn(); JSONAssert.assertEquals( @@ -1349,7 +1570,7 @@ void search_200_withSort() throws Exception { }, "page": 0, "size": 6, - "sort": "name:desc" + "sort": "name,desc" } """)) .andExpect(status().isOk()).andExpect(jsonPath("$.content.length()").value(6)) @@ -1564,9 +1785,8 @@ void search_200_numericGt_onNumberProperty() throws Exception { } """)) .andExpect(status().isOk()).andExpect(jsonPath("$.page.total_elements").value(3)) - .andExpect(jsonPath("$.content[0].identifier").value("web-api-1")) - .andExpect(jsonPath("$.content[1].identifier").value("web-service-valid-1")) - .andExpect(jsonPath("$.content[2].identifier").value("web-api-2")); + .andExpect(jsonPath("$.content[*].identifier") + .value(containsInAnyOrder("web-api-1", "web-api-2", "web-service-valid-1"))); } @Test @@ -1600,7 +1820,7 @@ void search_200_numericLte_onNumberProperty_allMatch() throws Exception { void search_200_noPageOrSize_usesDefaults() throws Exception { // Omitting page and size must not cause a 400 JSON parse error (primitive int // vs null). - // The record defaults should kick in: page=0, size=20. + // The controller defaults should kick in: page=0, size=20. mockMvc .perform(MockMvcRequestBuilders.post(SEARCH_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(""" @@ -1626,8 +1846,8 @@ void search_400_pageSizeTooLarge() throws Exception { .accept(APPLICATION_JSON).with(csrf()).content(""" { "page": 0, "size": 501 } """)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error_description") - .value("Page size must not exceed %d".formatted(SearchConstraints.MAX_PAGE_SIZE))); + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error_description").value( + "Page size must not exceed %d".formatted(SearchConstraints.DEFAULT_MAX_PAGE_SIZE))); } @Test @@ -1637,12 +1857,26 @@ void search_400_invalidSortField() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(SEARCH_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(""" - { "page": 0, "size": 20, "sort": "badField:asc" } + { "page": 0, "size": 20, "sort": "badField,asc" } """)) .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error_description").value( "Invalid sort field 'badField'. Supported fields: identifier, name, templateIdentifier")); } + @ParameterizedTest + @CsvSource({"name:asc", "name:desc"}) + @WithMockUser + @DisplayName("Should return 400 for colon-delimited sort") + void search_400_colonDelimitedSort(String sort) throws Exception { + mockMvc + .perform(MockMvcRequestBuilders.post(SEARCH_PATH).contentType(APPLICATION_JSON) + .accept(APPLICATION_JSON).with(csrf()).content(""" + { "page": 0, "size": 20, "sort": "%s" } + """.formatted(sort))) + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error_description") + .value(ValidationMessages.SEARCH_INVALID_SORT_FORMAT.formatted(sort))); + } + @Test @WithMockUser @DisplayName("Should return entities that have a relation with an exact name match") @@ -1670,7 +1904,7 @@ void search_200_byRelationNameContains() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(""" { "filter": { "field": "relation", "operation": "CONTAINS", "value": "database" }, - "page": 0, "size": 20, "sort": "identifier:asc" + "page": 0, "size": 20, "sort": "identifier,asc" } """)).andExpect(status().isOk()).andReturn(); JSONAssert.assertEquals( diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingControllerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingControllerTest.java index c2c18cf7..6e9cb7de 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingControllerTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingControllerTest.java @@ -1,14 +1,25 @@ package com.decathlon.idp_core.infrastructure.adapters.api.controller; -import static com.decathlon.idp_core.domain.constant.ValidationMessages.*; +import static com.decathlon.idp_core.domain.constant.ValidationMessages.ENTITY_DYNAMIC_MAPPING_TEMPLATE_IDENTIFIER_MANDATORY; import static org.hamcrest.Matchers.containsString; import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -import org.junit.jupiter.api.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.ClassOrderer; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestClassOrder; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MockMvc; @@ -24,16 +35,15 @@ /// for all CRUD operations on entity dynamic mappings. @DisplayName("EntityDynamicMappingController Integration Tests") @TestClassOrder(ClassOrderer.OrderAnnotation.class) -@Sql(scripts = {"/db/test/R__1_Insert_test_data.sql", - "/db/test/R__4_insert_webhook_test_data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +@Sql(scripts = {"/db/test/R__1_Insert_test_data.sql", "/db/test/R__4_insert_webhook_test_data.sql", + "/db/test/R__6_insert_principal_user_for_test.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Slf4j class EntityDynamicMappingControllerTest extends AbstractIntegrationTest { + private static final String MAPPING_PATH = "/api/v1/entity_dynamic_mappings"; @Autowired private MockMvc mockMvc; - private static final String MAPPING_PATH = "/api/v1/entity_dynamic_mappings"; - /// Builds a valid entity dynamic mapping creation payload. private String buildCreatePayload(String mappingIdentifier) { return buildCreatePayload(mappingIdentifier, "UPDATE_ENTITY"); @@ -137,6 +147,35 @@ void getMappings_200_with_custom_pagination() throws Exception { .andExpect(jsonPath("$.page.size").value(5)) .andExpect(jsonPath("$.page.number").value(0)); } + + @Test + @WithMockUser + @DisplayName("Should return 400 when page size exceeds 500") + void getMappings_400_size_above_500() throws Exception { + mockMvc + .perform( + get(MAPPING_PATH).param("page", "0").param("size", "501").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser + @DisplayName("Should return 400 when page size is zero") + void getMappings_400_size_zero() throws Exception { + mockMvc + .perform(get(MAPPING_PATH).param("page", "0").param("size", "0").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser + @DisplayName("Should return 400 when page size is not an integer") + void getMappings_400_size_not_integer() throws Exception { + mockMvc + .perform( + get(MAPPING_PATH).param("page", "0").param("size", "abc").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } } @Nested @@ -144,6 +183,35 @@ void getMappings_200_with_custom_pagination() throws Exception { @Order(2) class PostMappingTests { + @Test + @DisplayName("Should forbid service accounts from creating principal-targeting mappings") + void postPrincipalTargetMapping_forbiddenForServiceAccount() throws Exception { + String serviceIdentifier = "mapping-service-" + java.util.UUID.randomUUID(); + String payload = """ + { + "identifier": "protected-principal-mapping", + "entity_template_identifier": "principal", + "filter": ".action == \\"pushed\\"", + "action": "UPDATE_ENTITY", + "name": "Protected principal mapping", + "entity": { + "identifier": ".user.id", + "name": ".user.name", + "properties": {"is_admin": "true"}, + "relations": [] + } + } + """; + + mockMvc + .perform(MockMvcRequestBuilders.post(MAPPING_PATH) + .with(jwt().jwt(token -> token.claim("sub", serviceIdentifier) + .claim("client_id", serviceIdentifier).claim("token_type", "m2m"))) + .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) + .andExpect(status().isForbidden()).andExpect(jsonPath("$.error").value("FORBIDDEN")) + .andExpect(jsonPath("$.error_description").exists()); + } + @Test @DisplayName("Should return 401 without authentication") void postMapping_401_without_user_token() throws Exception { @@ -191,7 +259,7 @@ void postMapping_409_identifier_already_exists() throws Exception { .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()) .content(buildCreatePayload("microservice-mapping"))) - .andExpect(status().isConflict()).andExpect(jsonPath("$.error").value("CONFLICT")) + .andExpect(status().isConflict()).andExpect(problemDetailResponse(HttpStatus.CONFLICT)) .andExpect(jsonPath("$.error_description").value(containsString("microservice-mapping"))); } @@ -223,7 +291,8 @@ void postMapping_400_identifier_missing() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) .andExpect(jsonPath("$.error_description").value(containsString("mapping identifier"))); } @@ -250,7 +319,8 @@ void postMapping_400_template_missing() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) .andExpect(jsonPath("$.error_description") .value(containsString("Entity Template Identifier is mandatory"))); } @@ -279,7 +349,7 @@ void postMapping_404_template_not_found() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isNotFound()).andExpect(jsonPath("$.error").value("NOT_FOUND")) + .andExpect(status().isNotFound()).andExpect(problemDetailResponse(HttpStatus.NOT_FOUND)) .andExpect(jsonPath("$.error_description") .value(containsString("non-existent-entityTemplateIdentifier"))); } @@ -311,13 +381,13 @@ void postMapping_400_missing_required_properties() throws Exception { .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) .andExpect(status().isUnprocessableContent()) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")) + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)) .andExpect(jsonPath("$.error_description").value(containsString("missing required"))); } @Test @WithMockUser - @DisplayName("Should return 400 with explicit message when target_entity_identifiers is a plain string instead of an array") + @DisplayName("Should return a native 400 problem detail when target_entity_identifiers is a string instead of an array") void postMapping_400_target_entity_identifiers_is_string() throws Exception { var payload = """ { @@ -344,10 +414,15 @@ void postMapping_400_target_entity_identifiers_is_string() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) - .andExpect( - jsonPath("$.error_description").value(containsString("target_entity_identifiers"))) - .andExpect(jsonPath("$.error_description").value(containsString("expected"))); + .andExpect(status().isBadRequest()) + .andExpect(content().contentTypeCompatibleWith(APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.status").value(400)) + .andExpect(jsonPath("$.title").value("Bad Request")) + .andExpect(jsonPath("$.detail").value("Failed to read request")) + .andExpect(jsonPath("$.instance").value(MAPPING_PATH)) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) + .andExpect(jsonPath("$.error_description").value("Failed to read request")) + .andExpect(jsonPath("$.timestamp").isNotEmpty()); } @Test @@ -375,7 +450,7 @@ void postMapping_422_entity_properties_null() throws Exception { .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) .andExpect(status().isUnprocessableContent()) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")) + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)) .andExpect(jsonPath("$.error_description").value(containsString("missing required"))); } @@ -447,7 +522,7 @@ void postMapping_422_required_relations_missing() throws Exception { .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) .andExpect(status().isUnprocessableContent()) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")).andExpect( + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)).andExpect( jsonPath("$.error_description").value(containsString("missing required relations"))); } @@ -497,7 +572,7 @@ void postMapping_422_relation_not_defined_for_template_without_relations() throw .perform(MockMvcRequestBuilders.post(MAPPING_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) .andExpect(status().isUnprocessableContent()) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")).andExpect( + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)).andExpect( jsonPath("$.error_description").value(containsString("is not defined in template"))); } } @@ -533,7 +608,7 @@ void getMapping_200() throws Exception { @DisplayName("Should return 404 when mapping does not exist") void getMapping_404_not_found() throws Exception { mockMvc.perform(get(MAPPING_PATH + "/non-existent-mapping").accept(APPLICATION_JSON)) - .andExpect(status().isNotFound()).andExpect(jsonPath("$.error").value("NOT_FOUND")) + .andExpect(status().isNotFound()).andExpect(problemDetailResponse(HttpStatus.NOT_FOUND)) .andExpect(jsonPath("$.error_description").exists()); } @@ -573,7 +648,7 @@ void putMapping_404_not_found() throws Exception { .perform(MockMvcRequestBuilders.put(MAPPING_PATH + "/non-existent-mapping") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(buildUpdatePayload())) - .andExpect(status().isNotFound()).andExpect(jsonPath("$.error").value("NOT_FOUND")) + .andExpect(status().isNotFound()).andExpect(problemDetailResponse(HttpStatus.NOT_FOUND)) .andExpect(jsonPath("$.error_description").exists()); } @@ -623,7 +698,8 @@ void putMapping_400_template_missing() throws Exception { mockMvc .perform(MockMvcRequestBuilders.put(MAPPING_PATH + "/microservice-mapping") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")); + .andExpect(status().isBadRequest()) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)); } } @@ -651,7 +727,7 @@ void deleteMapping_204() throws Exception { .accept(APPLICATION_JSON).with(csrf())).andExpect(status().isNoContent()); mockMvc.perform(get(MAPPING_PATH + "/mapping-to-delete").accept(APPLICATION_JSON)) - .andExpect(status().isNotFound()).andExpect(jsonPath("$.error").value("NOT_FOUND")); + .andExpect(status().isNotFound()).andExpect(problemDetailResponse(HttpStatus.NOT_FOUND)); } @Test @@ -661,7 +737,7 @@ void deleteMapping_404_not_found() throws Exception { mockMvc .perform(MockMvcRequestBuilders.delete(MAPPING_PATH + "/non-existent-mapping") .accept(APPLICATION_JSON).with(csrf())) - .andExpect(status().isNotFound()).andExpect(jsonPath("$.error").value("NOT_FOUND")) + .andExpect(status().isNotFound()).andExpect(problemDetailResponse(HttpStatus.NOT_FOUND)) .andExpect(jsonPath("$.error_description").exists()); } @@ -672,7 +748,7 @@ void deleteMapping_409_in_use() throws Exception { mockMvc .perform(MockMvcRequestBuilders.delete(MAPPING_PATH + "/microservice-mapping") .accept(APPLICATION_JSON).with(csrf())) - .andExpect(status().isConflict()).andExpect(jsonPath("$.error").value("CONFLICT")) + .andExpect(status().isConflict()).andExpect(problemDetailResponse(HttpStatus.CONFLICT)) .andExpect(jsonPath("$.error_description").value(containsString("in use"))); } } @@ -815,11 +891,11 @@ private String buildApimApiDryRunPayload() { "relations": [ { "name": "apim-api-consumed_by-component", - "target_entity_identifiers": [".relations.\\\"apim-api-consumed_by-component\\\""] + "target_entity_identifiers": [".relations.\\"apim-api-consumed_by-component\\""] }, { "name": "apim-api-provided_by-component", - "target_entity_identifiers": [".relations.\\\"apim-api-provided_by-component\\\""] + "target_entity_identifiers": [".relations.\\"apim-api-provided_by-component\\""] } ] } @@ -1136,7 +1212,7 @@ void dryRunMapping_404_template_not_found() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isNotFound()).andExpect(jsonPath("$.error").value("NOT_FOUND")) + .andExpect(status().isNotFound()).andExpect(problemDetailResponse(HttpStatus.NOT_FOUND)) .andExpect( jsonPath("$.error_description").value(containsString("non-existent-template"))); } @@ -1159,7 +1235,8 @@ void dryRunMapping_400_mapping_missing() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) .andExpect(jsonPath("$.error_description") .value(containsString("Entity dynamic Mapping definition is mandatory"))); } @@ -1188,7 +1265,8 @@ void dryRunMapping_400_payload_missing() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) .andExpect(jsonPath("$.error_description").value(containsString("Payload is mandatory"))); } @@ -1224,7 +1302,8 @@ void dryRunMapping_400_payload_blank_string() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) .andExpect(jsonPath("$.error_description").value(containsString("Payload is mandatory"))); } @@ -1272,7 +1351,7 @@ void dryRunMapping_422_required_relations_missing() throws Exception { .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) .andExpect(status().isUnprocessableContent()) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")).andExpect( + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)).andExpect( jsonPath("$.error_description").value(containsString("missing required relations"))); } @@ -1304,7 +1383,8 @@ void dryRunMapping_400_template_identifier_missing() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) .andExpect(jsonPath("$.error_description") .value(containsString(ENTITY_DYNAMIC_MAPPING_TEMPLATE_IDENTIFIER_MANDATORY))); } @@ -1340,7 +1420,8 @@ void dryRunMapping_400_mapping_identifier_missing() throws Exception { mockMvc .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(status().isBadRequest()) + .andExpect(problemDetailResponse(HttpStatus.BAD_REQUEST)) .andExpect(jsonPath("$.error_description").value(containsString("mapping identifier"))); } @@ -1353,17 +1434,17 @@ void dryRunMapping_422_with_expression_evaluation_failed_exception() throws Exce "mapping": { "identifier": "runtime-expression-error-test", "entity_template_identifier": "microservice", - "filter": ".action == \\\"pushed\\\"", + "filter": ".action == \\"pushed\\"", "action": "UPDATE_ENTITY", "name": "runtime expression error test", "description": "test", "entity": { - "identifier": "error(\\\"forced dry-run failure\\\")", + "identifier": "error(\\"forced dry-run failure\\")", "name": ".repository.name", "properties": { "applicationName": ".repository.name", "ownerEmail": ".sender.email", - "environment": "\\\"DEV\\\"", + "environment": "\\"DEV\\"", "version": ".ref", "port": "8080", "programmingLanguage": ".repository.language" @@ -1390,8 +1471,8 @@ void dryRunMapping_422_with_expression_evaluation_failed_exception() throws Exce .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) .andExpect(status().isUnprocessableContent()) - .andExpect(content().contentType(APPLICATION_JSON)) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")) + .andExpect(content().contentType(APPLICATION_PROBLEM_JSON)) + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)) .andExpect(jsonPath("$.error_description") .value(containsString("Expression evaluation failed"))); } @@ -1432,7 +1513,7 @@ void dryRunMapping_400_with_jslt_error() throws Exception { .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) .andExpect(status().isUnprocessableContent()) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")) + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)) .andExpect(jsonPath("$.error_description").value(containsString( "The mapping is missing required properties: [environment, ownerEmail, port, programmingLanguage, version]"))); } @@ -1446,7 +1527,7 @@ void dryRunMapping_422_when_owner_email_is_not_extracted() throws Exception { "mapping": { "identifier": "github-commits-dry-run", "entity_template_identifier": "microservice", - "filter": ".action == \\\"pushed\\\"", + "filter": ".action == \\"pushed\\"", "action": "UPDATE_ENTITY", "name": "GitHub multi-commit dry-run", "description": "Generation d'une liste d'entites a partir des commits", @@ -1456,10 +1537,10 @@ void dryRunMapping_422_when_owner_email_is_not_extracted() throws Exception { "properties": { "applicationName": ".repository.name", "ownerEmail": ".email", - "port": "\\\"8080\\\"", + "port": "\\"8080\\"", "programmingLanguage": ".repository.language", - "version": "\\\"1.0.0\\\"", - "environment": "\\\"DEV\\\"" + "version": "\\"1.0.0\\"", + "environment": "\\"DEV\\"" }, "relations": [] } @@ -1483,7 +1564,7 @@ void dryRunMapping_422_when_owner_email_is_not_extracted() throws Exception { .perform(MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) .andExpect(status().isUnprocessableContent()) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")) + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)) .andExpect(jsonPath("$.error_description").value(containsString("ownerEmail"))); } @@ -1677,7 +1758,7 @@ void dryRunMapping_422_relation_not_defined() throws Exception { MockMvcRequestBuilders.post(MAPPING_PATH + "/dry-run").contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(dryRunPayload)) .andExpect(status().isUnprocessableContent()) - .andExpect(jsonPath("$.error").value("UNPROCESSABLE_CONTENT")) + .andExpect(problemDetailResponse(HttpStatus.UNPROCESSABLE_CONTENT)) .andExpect( jsonPath("$.error_description").value(containsString("is not defined in template"))) .andExpect(jsonPath("$.error_description").value(containsString("undefined-api-link"))); diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingDeletionAuthorizationTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingDeletionAuthorizationTest.java new file mode 100644 index 00000000..d28b2be9 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityDynamicMappingDeletionAuthorizationTest.java @@ -0,0 +1,97 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.controller; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import jakarta.servlet.http.HttpServletRequest; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.decathlon.idp_core.domain.exception.authorization.PrincipalNotAuthorizedException; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationResource; +import com.decathlon.idp_core.domain.model.entity_mapping.EntityDynamicMapping; +import com.decathlon.idp_core.domain.model.entity_mapping.MappingAction; +import com.decathlon.idp_core.domain.service.entity_dynamic_mapping.EntityDynamicMappingDryRunService; +import com.decathlon.idp_core.domain.service.entity_dynamic_mapping.EntityDynamicMappingService; +import com.decathlon.idp_core.infrastructure.adapters.api.auth.RequestAuthorizer; +import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity_dynamic_mapping.EntityDynamicMappingDryRunDtoInMapper; +import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity_dynamic_mapping.EntityDynamicMappingDryRunDtoOutMapper; +import com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity_dynamic_mapping.EntityDynamicMappingMapper; + +@ExtendWith(MockitoExtension.class) +class EntityDynamicMappingDeletionAuthorizationTest { + + @Mock + private EntityDynamicMappingMapper dynamicMappingMapper; + + @Mock + private EntityDynamicMappingService dynamicMappingService; + + @Mock + private EntityDynamicMappingDryRunService dynamicMappingDryRunService; + + @Mock + private EntityDynamicMappingDryRunDtoOutMapper entityDynamicMappingDryRunDtoOutMapper; + + @Mock + private EntityDynamicMappingDryRunDtoInMapper entityDynamicMappingDryRunDtoInMapper; + + @Mock + private RequestAuthorizer requestAuthorizer; + + @Mock + private HttpServletRequest request; + + @InjectMocks + private EntityDynamicMappingController controller; + + @Test + void shouldAuthorizeResolvedPrincipalTargetBeforeDeletingMapping() { + when(dynamicMappingService.getEntityDynamicMapping("principal-mapping")).thenReturn( + mapping("principal-mapping", AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER)); + doThrow(new PrincipalNotAuthorizedException("service-account")).when(requestAuthorizer) + .authorize(eq(request), eq(AuthorizationAction.DELETE), any(AuthorizationResource.class)); + + assertThatThrownBy(() -> controller.deleteEntityDynamicMapping("principal-mapping", request)) + .isInstanceOf(PrincipalNotAuthorizedException.class); + + verify(requestAuthorizer).authorize(eq(request), eq(AuthorizationAction.DELETE), + argThat(resource -> resource.type().equals(AuthorizationResource.ENTITY_DYNAMIC_MAPPING) + && resource.identifier().filter("principal-mapping"::equals).isPresent() + && resource.parentIdentifier() + .filter(AuthorizationResource.PRINCIPAL_TEMPLATE_IDENTIFIER::equals).isPresent())); + verify(dynamicMappingService, never()).deleteEntityDynamicMapping(any()); + } + + @Test + void shouldDeleteMappingWithoutPrincipalAuthorizationWhenTargetIsNotPrincipal() { + when(dynamicMappingService.getEntityDynamicMapping("regular-mapping")) + .thenReturn(mapping("regular-mapping", "microservice")); + + controller.deleteEntityDynamicMapping("regular-mapping", request); + + verify(requestAuthorizer, never()).authorize(any(), any(), any()); + verify(dynamicMappingService).deleteEntityDynamicMapping("regular-mapping"); + } + + private EntityDynamicMapping mapping(String identifier, String targetTemplate) { + return new EntityDynamicMapping(UUID.randomUUID(), identifier, targetTemplate, + ".action == 'update'", MappingAction.UPDATE_ENTITY, "Mapping", null, ".entity.id", + ".entity.name", Map.of(), List.of()); + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateControllerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateControllerTest.java index d9833076..7e7d5560 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateControllerTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateControllerTest.java @@ -5,7 +5,9 @@ import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -24,6 +26,7 @@ import org.junit.jupiter.api.TestClassOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -40,15 +43,16 @@ @DisplayName("EntityTemplate Controller Integration Tests") @TestClassOrder(ClassOrderer.OrderAnnotation.class) +@Sql(scripts = { + "/db/test/R__6_insert_principal_user_for_test.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Slf4j class EntityTemplateControllerTest extends AbstractIntegrationTest { + private static final String ENTITY_TEMPLATE_PATH = "/api/v1/entity-templates"; @Autowired private MockMvc mockMvc; - @Autowired private EntityTemplateRepositoryPort entityTemplateRepository; - private static final String ENTITY_TEMPLATE_PATH = "/api/v1/entity-templates"; /// Test suite for the GET /api/v1/entity-templates endpoint, covering paginated /// retrieval of entity templates. @@ -75,6 +79,7 @@ class GetTemplatesPaginatedTests { /// - Default pagination settings are applied (page 0, size 20) /// - Template ordering is consistent (batch-job at index 1) /// - Pagination metadata is correctly populated + /// /// @throws Exception if the MockMvc request fails @Test @DisplayName("Should return paginated templates with default pagination") @@ -94,6 +99,7 @@ void getTemplates_paginated_200() throws Exception { /// Tests that accessing the /api/v1/entity-templates/ endpoint without /// authentication returns a 401 Unauthorized status. + /// /// @throws Exception if an error occurs during the request @Test @DisplayName("Should return 401 without authentication") @@ -102,10 +108,22 @@ void getTemplates_paginated_401_without_user_token() throws Exception { .andExpect(status().isUnauthorized()); } + @Test + @DisplayName("Should return standard 401 when an unmarked token has no machine identifier") + void getTemplates_401_whenMachineIdentifierClaimIsMissing() throws Exception { + mockMvc + .perform(get(ENTITY_TEMPLATE_PATH).with(jwt().jwt(token -> token.claim("sub", " "))) + .accept(APPLICATION_JSON)) + .andExpect(status().isUnauthorized()).andExpect(jsonPath("$.error").value("UNAUTHORIZED")) + .andExpect(jsonPath("$.error_description") + .value(containsString("principal identifier claim 'client_id'"))); + } + /// Tests the GET /api/v1/entity-templates/ endpoint with custom pagination /// parameters. /// This test verifies that: /// - Custom pagination parameters are correctly applied (page=1, size=5, + /// /// @throws Exception if the MockMvc request fails @Test @DisplayName("Should return paginated templates with custom pagination") @@ -124,9 +142,59 @@ void getTemplates_paginated_200_custom() throws Exception { .andExpect(jsonPath("$.page.number").value(1)); } + /// Tests that Pageable endpoints reject `size` values above 500 instead of + /// clamping them. + /// @throws Exception if the MockMvc request fails + @Test + @DisplayName("Should return 400 when page size exceeds 500 on Pageable endpoints") + @WithMockUser + void getTemplates_paginated_400_size_above_500() throws Exception { + + mockMvc.perform(get("/api/v1/entity-templates").param("page", "0").param("size", "501") + .accept(APPLICATION_JSON)).andExpect(status().isBadRequest()); + } + + /// Tests that Pageable endpoints reject `size` values below 1 instead of + /// silently replacing them with a default. + /// @throws Exception if the MockMvc request fails + @Test + @DisplayName("Should return 400 when page size is zero on Pageable endpoints") + @WithMockUser + void getTemplates_paginated_400_size_zero() throws Exception { + + mockMvc.perform(get("/api/v1/entity-templates").param("page", "0").param("size", "0") + .accept(APPLICATION_JSON)).andExpect(status().isBadRequest()); + } + + /// Tests that Pageable endpoints reject non-numeric `size` values. + /// @throws Exception if the MockMvc request fails + @Test + @DisplayName("Should return 400 when page size is not an integer on Pageable endpoints") + @WithMockUser + void getTemplates_paginated_400_size_not_integer() throws Exception { + + mockMvc.perform(get("/api/v1/entity-templates").param("page", "0").param("size", "abc") + .accept(APPLICATION_JSON)).andExpect(status().isBadRequest()); + } + + /// Tests that the maximum allowed page size of 500 is accepted on Pageable + /// endpoints. + /// @throws Exception if the MockMvc request fails + @Test + @DisplayName("Should accept page size of exactly 500 on Pageable endpoints") + @WithMockUser + void getTemplates_paginated_200_size_500() throws Exception { + + mockMvc + .perform(get("/api/v1/entity-templates").param("page", "0").param("size", "500") + .accept(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.page.size").value(500)); + } + /// Tests the GET /api/v1/entity-templates/{identifier} endpoint for /// retrieving a specific template. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @DisplayName("Should return 200 even with invalid pagination parameters") @@ -141,6 +209,7 @@ void getTemplates_paginated_200_invalid_pagination() throws Exception { /// parameter. /// This test verifies that: /// - The endpoint returns HTTP 200 OK status when identifier parameter is + /// /// @throws Exception if the MockMvc request fails @Test @DisplayName("Should return 200 with valid identifier") @@ -162,6 +231,7 @@ class PostTemplateTests { /// Tests the POST /api/v1/entity-templates endpoint for successful template /// creation. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -175,8 +245,32 @@ void postTemplate_201() throws Exception { .andExpect(status().isCreated()).andReturn(); } + @Test + @DisplayName("Should forbid service accounts from creating the protected principal template") + void postPrincipalTemplate_forbiddenForServiceAccount() throws Exception { + String serviceIdentifier = "template-service-" + UUID.randomUUID(); + String payload = """ + { + "identifier": "principal", + "name": "Principal", + "description": "Protected identity template", + "properties_definitions": [], + "relations_definitions": [] + } + """; + + mockMvc + .perform(MockMvcRequestBuilders.post(ENTITY_TEMPLATE_PATH) + .with(jwt().jwt(token -> token.claim("sub", serviceIdentifier) + .claim("client_id", serviceIdentifier).claim("token_type", "m2m"))) + .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) + .andExpect(status().isForbidden()).andExpect(jsonPath("$.error").value("FORBIDDEN")) + .andExpect(jsonPath("$.error_description").exists()); + } + /// Tests the POST /api/v1/entity-templates endpoint without authentication. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @DisplayName("Should create template and return 401") @@ -194,6 +288,7 @@ void postTemplate_401_without_user_token() throws Exception { /// missing. /// This test verifies that: /// - Validation error message matches expected template identifier mandatory + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -209,6 +304,7 @@ void postTemplate_400_identifier_missing() throws Exception { /// blank. /// This test verifies that: /// - Validation error message matches expected template identifier mandatory + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -224,6 +320,7 @@ void postTemplate_400_identifier_blank() throws Exception { /// already exists. /// This test verifies that: /// - Validation error message contains expected template name already exists + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -239,6 +336,7 @@ void postTemplate_409_name_already_exists() throws Exception { /// missing. /// This test verifies that: /// - Validation error message matches expected template identifier mandatory + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -254,6 +352,7 @@ void postTemplate_400_name_missing() throws Exception { /// blank. /// This test verifies that: /// - Validation error message contains expected template name mandatory message + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -269,6 +368,7 @@ void postTemplate_400_name_blank() throws Exception { /// too long. /// This test verifies that: /// - Validation error message matches expected template name too long + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -284,6 +384,7 @@ void postTemplate_400_name_too_long() throws Exception { /// not respect regex pattern. /// This test verifies that: /// - Validation error message matches expected template name pattern + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -299,6 +400,7 @@ void postTemplate_400_name_invalid_pattern() throws Exception { /// empty. /// This test verifies that: /// - Validation error message indicates property definitions are + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -313,6 +415,7 @@ void postTemplate_400_property_name_missing() throws Exception { /// Tests the POST /api/v1/entity-templates endpoint when property name field is /// blank. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -327,6 +430,7 @@ void postTemplate_400_property_name_blank() throws Exception { /// Tests the POST /api/v1/entity-templates endpoint when property description /// field is missing. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -342,6 +446,7 @@ void postTemplate_400_property_description_missing() throws Exception { /// Tests the POST /api/v1/entity-templates endpoint when property description /// field is blank. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -356,6 +461,7 @@ void postTemplate_400_property_description_blank() throws Exception { /// Tests the POST /api/v1/entity-templates endpoint when property type field is /// missing. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -370,6 +476,7 @@ void postTemplate_400_property_type_missing() throws Exception { /// Tests the POST /api/v1/entity-templates endpoint when trying to create a /// template with duplicate identifier. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -382,7 +489,15 @@ void postTemplate_409_identifier_already_exists() throws Exception { .accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent(ENTITY_TEMPLATE_JSON_TEST_PATH + "postEntityTemplate_409_identifier_already_exists.json"))) - .andExpect(status().isConflict()).andExpect(content().contentType(APPLICATION_JSON)) + .andExpect(status().isConflict()) + .andExpect(content().contentType(APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.status").value(409)) + .andExpect(jsonPath("$.title").value("Conflict")) + .andExpect(jsonPath("$.detail").value(TEMPLATE_ALREADY_EXISTS + ":web-service")) + .andExpect(jsonPath("$.error").value("CONFLICT")) + .andExpect( + jsonPath("$.error_description").value(TEMPLATE_ALREADY_EXISTS + ":web-service")) + .andExpect(jsonPath("$.timestamp").exists()) .andExpect(jsonPath("$.error_description").exists()).andExpect( jsonPath("$.error_description").value(TEMPLATE_ALREADY_EXISTS + ":web-service")); } @@ -390,6 +505,7 @@ void postTemplate_409_identifier_already_exists() throws Exception { /// Tests the POST /api/v1/entity-templates endpoint when property type contains /// an invalid enum value. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -397,13 +513,14 @@ void postTemplate_409_identifier_already_exists() throws Exception { void postTemplate_400_property_type_invalid_enum() throws Exception { MvcResult res = postBadRequestAndAssertEquals(ENTITY_TEMPLATE_PATH, ENTITY_TEMPLATE_JSON_TEST_PATH + "postEntityTemplate_400_bad_property_type.json", - "Invalid value 'NOT IN ENUM' for property 'type'"); + "Failed to read request"); assertNotNull(res, "Test executed successfully"); } /// Tests the POST /api/v1/entity-templates endpoint when property format /// contains an invalid enum value. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -411,13 +528,14 @@ void postTemplate_400_property_type_invalid_enum() throws Exception { void postTemplate_400_property_format_invalid_enum() throws Exception { MvcResult res = postBadRequestAndAssertEquals(ENTITY_TEMPLATE_PATH, ENTITY_TEMPLATE_JSON_TEST_PATH + "postEntityTemplate_400_bad_property_format.json", - "Invalid value 'NOT A VALID FORMAT' for property 'format'"); + "Failed to read request"); assertNotNull(res, "Test executed successfully"); } /// Tests the POST /api/v1/entity-templates endpoint with invalid property /// rules. /// This test verifies that rules incompatible with property type are rejected. + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -434,6 +552,7 @@ void postTemplate_400_string_property_with_numeric_rules() throws Exception { /// This test verifies that: /// - Templates can be created without any properties /// - The endpoint returns HTTP 201 Created status + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -451,6 +570,7 @@ void postTemplate_201_without_properties() throws Exception { /// This test verifies that: /// - Templates can be created with an empty properties array /// - The endpoint returns HTTP 201 Created status + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -715,6 +835,7 @@ void putTemplate_200() throws Exception { /// This test verifies that: /// - Templates can be updated without any properties /// - The endpoint returns HTTP 200 OK status + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -735,6 +856,7 @@ void putTemplate_200_without_properties() throws Exception { /// This test verifies that: /// - Templates can be updated with an empty properties array /// - The endpoint returns HTTP 200 OK status + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -758,8 +880,9 @@ void putTemplate_404_withUnknownIdentifier() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent( "integration_test/json/entity-template/v1/putEntityTemplate_200.json"))) - .andExpect(status().isNotFound()).andExpect(content().string( - "{\"error\":\"NOT_FOUND\",\"error_description\":\"Template not found with identifier: unknown-identifier\"}")); + .andExpect(status().isNotFound()).andExpect(jsonPath("$.error").value("NOT_FOUND")) + .andExpect(jsonPath("$.error_description") + .value("Template not found with identifier: unknown-identifier")); } @Test @@ -770,8 +893,9 @@ void putTemplate_400_propertyNameIsMissing() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent( "integration_test/json/entity-template/v1/putEntityTemplate_400_propertyNameIsMissing.json"))) - .andExpect(status().isBadRequest()).andExpect(content().string( - "{\"error\":\"BAD_REQUEST\",\"error_description\":\"Property name is mandatory and cannot be blank\"}")); + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(jsonPath("$.error_description") + .value("Property name is mandatory and cannot be blank")); } @Test @@ -782,8 +906,9 @@ void putTemplate_400_propertyNameIsBlank() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent( "integration_test/json/entity-template/v1/putEntityTemplate_400_propertyNameIsBlank.json"))) - .andExpect(status().isBadRequest()).andExpect(content().string( - "{\"error\":\"BAD_REQUEST\",\"error_description\":\"Property name is mandatory and cannot be blank\"}")); + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(jsonPath("$.error_description") + .value("Property name is mandatory and cannot be blank")); } @Test @@ -794,8 +919,9 @@ void putTemplate_400_propertyDescriptionIsBlank() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent( "integration_test/json/entity-template/v1/putEntityTemplate_400_propertyDescriptionIsBlank.json"))) - .andExpect(status().isBadRequest()).andExpect(content().string( - "{\"error\":\"BAD_REQUEST\",\"error_description\":\"Property description is mandatory and cannot be blank\"}")); + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(jsonPath("$.error_description") + .value("Property description is mandatory and cannot be blank")); } @Test @@ -806,8 +932,9 @@ void putTemplate_400_propertyDescriptionIsMissing() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent( "integration_test/json/entity-template/v1/putEntityTemplate_400_propertyDescriptionIsMissing.json"))) - .andExpect(status().isBadRequest()).andExpect(content().string( - "{\"error\":\"BAD_REQUEST\",\"error_description\":\"Property description is mandatory and cannot be blank\"}")); + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(jsonPath("$.error_description") + .value("Property description is mandatory and cannot be blank")); } @Test @@ -818,8 +945,8 @@ void putTemplate_400_propertyTypeIsMissing() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent( "integration_test/json/entity-template/v1/putEntityTemplate_400_propertyTypeIsMissing.json"))) - .andExpect(status().isBadRequest()).andExpect(content().string( - "{\"error\":\"BAD_REQUEST\",\"error_description\":\"Property type is mandatory\"}")); + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("BAD_REQUEST")) + .andExpect(jsonPath("$.error_description").value("Property type is mandatory")); } @Test @@ -833,8 +960,9 @@ void putTemplate_409_whenIdentifierAlreadyExists() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent( "integration_test/json/entity-template/v1/putEntityTemplate_409_withIdentifierAlreadyExists.json"))) - .andExpect(status().isConflict()).andExpect(content().string( - "{\"error\":\"CONFLICT\",\"error_description\":\"The entity template name Microservice already exists\"}")); + .andExpect(status().isConflict()).andExpect(jsonPath("$.error").value("CONFLICT")) + .andExpect(jsonPath("$.error_description") + .value("The entity template name Microservice already exists")); } /// Tests the PUT /api/v1/entity-templates/{identifier} endpoint when the name @@ -842,6 +970,7 @@ void putTemplate_409_whenIdentifierAlreadyExists() throws Exception { /// missing. /// This test verifies that: /// - Validation error message matches expected template name mandatory + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -862,6 +991,7 @@ void putTemplate_400_name_missing() throws Exception { /// blank. /// This test verifies that: /// - Validation error message contains expected template name mandatory message + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -881,6 +1011,7 @@ void putTemplate_400_name_blank() throws Exception { /// already exists. /// This test verifies that: /// - Validation error message contains expected template name already exists + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -891,8 +1022,9 @@ void putTemplate_409_name_already_exists() throws Exception { .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()) .content(getJsonTestFileContent( "integration_test/json/entity-template/v1/putEntityTemplate_409_name_already_exists.json"))) - .andExpect(status().isConflict()).andExpect(content().string( - "{\"error\":\"CONFLICT\",\"error_description\":\"The entity template name Microservice already exists\"}")); + .andExpect(status().isConflict()).andExpect(jsonPath("$.error").value("CONFLICT")) + .andExpect(jsonPath("$.error_description") + .value("The entity template name Microservice already exists")); } /// Tests the PUT /api/v1/entity-templates/{identifier} endpoint when name field @@ -900,6 +1032,7 @@ void putTemplate_409_name_already_exists() throws Exception { /// too long. /// This test verifies that: /// - Validation error message matches expected template name too long + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -920,6 +1053,7 @@ void putTemplate_400_name_too_long() throws Exception { /// not respect regex pattern. /// This test verifies that: /// - Validation error message matches expected template name pattern + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -939,6 +1073,7 @@ void putTemplate_400_name_invalid_pattern() throws Exception { /// requests with an identifier field in the request body. /// **This test verifies that:** /// - The endpoint returns HTTP 400 Bad Request when identifier is in body + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -1009,6 +1144,7 @@ class DeleteTemplateTests { /// Tests the DELETE /api/v1/entity-templates/{id} endpoint for successful /// template deletion. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -1026,6 +1162,7 @@ void deleteTemplate_204() throws Exception { /// Tests the DELETE /api/v1/entity-templates/{id} endpoint when template does /// not exist. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -1037,7 +1174,8 @@ void deleteTemplate_404_not_found() throws Exception { mockMvc .perform(MockMvcRequestBuilders.delete(ENTITY_TEMPLATE_PATH + "/" + nonExistentId) .accept(APPLICATION_JSON).with(csrf())) - .andExpect(status().isNotFound()).andExpect(content().contentType(APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andExpect(content().contentType(APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.error").value("NOT_FOUND")) .andExpect(jsonPath("$.error_description").exists()); @@ -1048,6 +1186,7 @@ void deleteTemplate_404_not_found() throws Exception { /// is still referenced as a relation target in another template. /// This test verifies that: /// - Returns HTTP 400 Bad Request with appropriate error message + /// /// @throws Exception if the MockMvc request fails @Test @WithMockUser() @@ -1060,7 +1199,8 @@ void deleteTemplate_400_is_relation_target() throws Exception { mockMvc .perform(MockMvcRequestBuilders.delete(ENTITY_TEMPLATE_PATH + "/" + templateId) .accept(APPLICATION_JSON).with(csrf())) - .andExpect(status().isBadRequest()).andExpect(content().contentType(APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.error").value("BAD_REQUEST")) .andExpect(jsonPath("$.error_description").exists()); @@ -1070,6 +1210,7 @@ void deleteTemplate_400_is_relation_target() throws Exception { /// Tests the DELETE /api/v1/entity-templates/{id} endpoint when authentication /// is missing. /// This test verifies that: + /// /// @throws Exception if the MockMvc request fails @Test @DisplayName("Should return 401 when deleting without user token") diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/InboundWebhookManagementControllerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/InboundWebhookManagementControllerTest.java index d2e62838..e38b5e23 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/InboundWebhookManagementControllerTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/InboundWebhookManagementControllerTest.java @@ -35,8 +35,8 @@ /// for all CRUD operations on inbound webhook connectors. @DisplayName("InboundWebhookManagementController Integration Tests") @TestClassOrder(ClassOrderer.OrderAnnotation.class) -@Sql(scripts = {"/db/test/R__1_Insert_test_data.sql", - "/db/test/R__4_insert_webhook_test_data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +@Sql(scripts = {"/db/test/R__1_Insert_test_data.sql", "/db/test/R__4_insert_webhook_test_data.sql", + "/db/test/R__6_insert_principal_user_for_test.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Slf4j class InboundWebhookManagementControllerTest extends AbstractIntegrationTest { @@ -168,6 +168,30 @@ void getWebhooks_200_with_data() throws Exception { .andExpect(jsonPath("$.content[*].identifier", containsInAnyOrder("github-dora-connector", "github-dora-connector-success", "public-connector", "token-connector"))); } + + @Test + @WithMockUser + @DisplayName("Should return 400 when page size exceeds 500") + void getWebhooks_400_size_above_500() throws Exception { + mockMvc.perform(get(WEBHOOK_PATH).param("size", "501").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser + @DisplayName("Should return 400 when page size is zero") + void getWebhooks_400_size_zero() throws Exception { + mockMvc.perform(get(WEBHOOK_PATH).param("size", "0").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser + @DisplayName("Should return 400 when page size is not an integer") + void getWebhooks_400_size_not_integer() throws Exception { + mockMvc.perform(get(WEBHOOK_PATH).param("size", "abc").accept(APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } } @Nested @@ -185,6 +209,17 @@ void postWebhook_401_without_user_token() throws Exception { .andExpect(status().isUnauthorized()); } + @Test + @WithMockUser(username = "standard-human-webhook-creator") + @DisplayName("Should forbid standard humans from creating webhook configurations") + void postWebhook_403_for_standard_human() throws Exception { + mockMvc + .perform(MockMvcRequestBuilders.post(WEBHOOK_PATH).contentType(APPLICATION_JSON) + .accept(APPLICATION_JSON).with(csrf()) + .content(getJsonTestFileContent(JSON_PATH + "postWebhook_201.json"))) + .andExpect(status().isForbidden()); + } + @Test @WithMockUser @DisplayName("Should create connector and return 201") @@ -314,6 +349,48 @@ void postWebhook_201_security_defaults_to_none_when_omitted() throws Exception { .andExpect(status().isCreated()).andExpect(jsonPath("$.security.type").value("NONE")); } + @Test + @WithMockUser + @DisplayName("Should create a disabled connector with an empty security object") + void postWebhook_201_empty_security_when_disabled() throws Exception { + var payload = """ + { + "identifier": "disabled-empty-security-webhook", + "name": "Disabled Empty Security Webhook", + "enabled": false, + "mapping_identifiers": [], + "security": {} + } + """; + + mockMvc + .perform(MockMvcRequestBuilders.post(WEBHOOK_PATH).contentType(APPLICATION_JSON) + .accept(APPLICATION_JSON).with(csrf()).content(payload)) + .andExpect(status().isCreated()).andExpect(jsonPath("$.security.type").value("NONE")) + .andExpect(jsonPath("$.security.config").isEmpty()); + } + + @Test + @WithMockUser + @DisplayName("Should create a disabled connector with null security") + void postWebhook_201_null_security_when_disabled() throws Exception { + var payload = """ + { + "identifier": "disabled-null-security-webhook", + "name": "Disabled Null Security Webhook", + "enabled": false, + "mapping_identifiers": [], + "security": null + } + """; + + mockMvc + .perform(MockMvcRequestBuilders.post(WEBHOOK_PATH).contentType(APPLICATION_JSON) + .accept(APPLICATION_JSON).with(csrf()).content(payload)) + .andExpect(status().isCreated()).andExpect(jsonPath("$.security.type").value("NONE")) + .andExpect(jsonPath("$.security.config").isEmpty()); + } + @Test @WithMockUser @DisplayName("Should create connector with STATIC_TOKEN security and return 201") @@ -602,6 +679,50 @@ void putWebhook_200() throws Exception { assertWebhookTemplateMapping("connector-put-200"); } + @Test + @WithMockUser + @DisplayName("Should update to NONE security when config is omitted") + void putWebhook_200_none_security_without_config() throws Exception { + createWebhookConnector("connector-put-none-no-config", "Connector Put None Initial"); + + var payload = """ + { + "name": "Connector Put None Updated", + "description": "updated without security config", + "enabled": false, + "mapping_identifiers": ["connector-put-none-no-config-mapping"], + "security": { "type": "NONE" } + } + """; + mockMvc + .perform(MockMvcRequestBuilders.put(WEBHOOK_PATH + "/connector-put-none-no-config") + .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) + .andExpect(status().isOk()).andExpect(jsonPath("$.security.type").value("NONE")) + .andExpect(jsonPath("$.security.config").isEmpty()); + } + + @Test + @WithMockUser + @DisplayName("Should update a disabled connector with an empty security object") + void putWebhook_200_empty_security_when_disabled() throws Exception { + createWebhookConnector("connector-put-empty-security", "Connector Empty Security Initial"); + + var payload = """ + { + "name": "Connector Empty Security Updated", + "description": "updated without security", + "enabled": false, + "mapping_identifiers": ["connector-put-empty-security-mapping"], + "security": {} + } + """; + mockMvc + .perform(MockMvcRequestBuilders.put(WEBHOOK_PATH + "/connector-put-empty-security") + .contentType(APPLICATION_JSON).accept(APPLICATION_JSON).with(csrf()).content(payload)) + .andExpect(status().isOk()).andExpect(jsonPath("$.security.type").value("NONE")) + .andExpect(jsonPath("$.security.config").isEmpty()); + } + @Test @WithMockUser @DisplayName("Should return 404 when connector does not exist") @@ -1028,19 +1149,71 @@ void security_none_empty_config_201() throws Exception { @WithMockUser @DisplayName("NONE — Should create connector without config field") void security_none_no_config_201() throws Exception { + // The "config" key is truly omitted from the request body. var payload = """ { "identifier": "sec-none-no-config", "name": "None No Config", "enabled": false, "mapping_identifiers": [], - "security": { "type": "NONE", "config":{} } + "security": { "type": "NONE" } } """; mockMvc .perform(MockMvcRequestBuilders.post(WEBHOOK_PATH).contentType(APPLICATION_JSON) .accept(APPLICATION_JSON).with(csrf()).content(payload)) - .andExpect(status().isCreated()).andExpect(jsonPath("$.security.type").value("NONE")); + .andExpect(status().isCreated()).andExpect(jsonPath("$.security.type").value("NONE")) + .andExpect(jsonPath("$.security.config").isEmpty()); + } + + @Test + @WithMockUser + @DisplayName("NONE — Should create connector with a null config") + void security_none_null_config_201() throws Exception { + var payload = """ + { + "identifier": "sec-none-null-config", + "name": "None Null Config", + "enabled": false, + "mapping_identifiers": [], + "security": { "type": "NONE", "config": null } + } + """; + mockMvc + .perform(MockMvcRequestBuilders.post(WEBHOOK_PATH).contentType(APPLICATION_JSON) + .accept(APPLICATION_JSON).with(csrf()).content(payload)) + .andExpect(status().isCreated()).andExpect(jsonPath("$.security.type").value("NONE")) + .andExpect(jsonPath("$.security.config").isEmpty()); + } + + @Test + @WithMockUser + @DisplayName("NONE — Should return 400 when config is not empty") + void security_none_non_empty_config_400() throws Exception { + mockMvc + .perform(MockMvcRequestBuilders.post(WEBHOOK_PATH).contentType(APPLICATION_JSON) + .accept(APPLICATION_JSON).with(csrf()).content(buildSecurityPayload( + "sec-none-with-config", "None With Config", "NONE", "{ \"a\": \"b\" }"))) + .andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser + @DisplayName("HMAC_SHA256 — Should return 400 when config is omitted") + void security_hmac_no_config_400() throws Exception { + var payload = """ + { + "identifier": "sec-hmac-no-config", + "name": "HMAC No Config", + "enabled": false, + "mapping_identifiers": [], + "security": { "type": "HMAC_SHA256" } + } + """; + mockMvc + .perform(MockMvcRequestBuilders.post(WEBHOOK_PATH).contentType(APPLICATION_JSON) + .accept(APPLICATION_JSON).with(csrf()).content(payload)) + .andExpect(status().isBadRequest()); } @Test diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/PrincipalControllerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/PrincipalControllerTest.java index 00c94b1e..b5f05a91 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/PrincipalControllerTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/PrincipalControllerTest.java @@ -158,19 +158,15 @@ void jitProvisioning_worksOnAnyEndpoint() throws Exception { } @Nested - @DisplayName("Security Role Assignment") - class SecurityRoleAssignmentTests { + @DisplayName("Global read access") + class GlobalReadAccessTests { @Test - @DisplayName("Should allow access with baseline role assignment") - @WithMockUser(username = "baseline-role-user") - void baselineRole_allowsAccess() throws Exception { - // Given: User with baseline role (assigned via JwtAuthenticationConverter) - - // When: Access protected endpoint - mockMvc.perform(get(PRINCIPAL_ME_PATH).accept(APPLICATION_JSON)) - // Then: Access granted (baseline role * provides access) - .andExpect(status().isOk()).andExpect(jsonPath("$.identifier", is("baseline-role-user"))); + @DisplayName("Should allow a standard human to read their principal") + @WithMockUser(username = "standard-human-reader") + void standardHuman_canReadPrincipal() throws Exception { + mockMvc.perform(get(PRINCIPAL_ME_PATH).accept(APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$.identifier", is("standard-human-reader"))); } } } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiErrorResponseWriterTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiErrorResponseWriterTest.java new file mode 100644 index 00000000..2dcd46e0 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiErrorResponseWriterTest.java @@ -0,0 +1,47 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.handler; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; + +class ApiErrorResponseWriterTest { + + private final ObjectMapper objectMapper = new ObjectMapper(); + private final ApiErrorResponseWriter writer = new ApiErrorResponseWriter(objectMapper); + + @ParameterizedTest + @MethodSource("authorizationErrors") + void shouldWriteProblemDetailFieldsAndLegacyExtensionsAtTopLevel(HttpStatus status) + throws Exception { + var request = new MockHttpServletRequest("GET", "/api/v1/entity-templates"); + var response = new MockHttpServletResponse(); + String description = "Principal is not authorized to perform this operation"; + + writer.write(request, response, status, description); + + var body = objectMapper.readTree(response.getContentAsByteArray()); + assertThat(response.getStatus()).isEqualTo(status.value()); + assertThat(response.getContentType()).startsWith("application/problem+json"); + assertThat(body.get("type").asText()).isEqualTo("about:blank"); + assertThat(body.get("title").asText()).isEqualTo(status.getReasonPhrase()); + assertThat(body.get("status").asInt()).isEqualTo(status.value()); + assertThat(body.get("detail").asText()).isEqualTo(description); + assertThat(body.get("instance").asText()).isEqualTo("/api/v1/entity-templates"); + assertThat(body.get("error").asText()).isEqualTo(status.name()); + assertThat(body.get("error_description").asText()).isEqualTo(description); + assertThat(body.get("timestamp").asText()).isNotBlank(); + } + + private static Stream authorizationErrors() { + return Stream.of(Arguments.of(HttpStatus.UNAUTHORIZED), Arguments.of(HttpStatus.FORBIDDEN)); + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiExceptionHandlerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiExceptionHandlerTest.java index f29c7213..45383461 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiExceptionHandlerTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/handler/ApiExceptionHandlerTest.java @@ -1,651 +1,686 @@ package com.decathlon.idp_core.infrastructure.adapters.api.handler; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; - import java.lang.reflect.Constructor; +import java.net.URI; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Set; -import java.util.stream.Stream; import jakarta.validation.ConstraintViolation; import jakarta.validation.ConstraintViolationException; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.context.MessageSourceResolvable; import org.springframework.core.MethodParameter; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; - +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.method.annotation.ExceptionHandlerMethodResolver; +import org.springframework.web.method.annotation.HandlerMethodValidationException; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +import com.decathlon.idp_core.domain.constant.ValidationMessages; +import com.decathlon.idp_core.domain.exception.authorization.PrincipalNotAuthorizedException; import com.decathlon.idp_core.domain.exception.entity.EntityAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.entity.EntityDeletionBlockedException; +import com.decathlon.idp_core.domain.exception.entity.EntityNotFoundException; import com.decathlon.idp_core.domain.exception.entity.EntityValidationException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingAlreadyInUseException; import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingConfigurationException; import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingHasNoPropertiesException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingHasNoRelationsException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingJsltErrorException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingNotFoundException; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.ExpressionEvaluationFailedException; import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateAlreadyExistsException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateIdentifierCannotChangeException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateIsRelationTargetException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateNameAlreadyExistsException; import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateNotFoundException; +import com.decathlon.idp_core.domain.exception.entity_template.EntityTemplateUsedByDynamicMappingException; +import com.decathlon.idp_core.domain.exception.entity_template.PropertyDefinitionRulesConflictException; +import com.decathlon.idp_core.domain.exception.entity_template.PropertyNameAlreadyExistsException; import com.decathlon.idp_core.domain.exception.entity_template.PropertyNameNotFoundEntityTemplatePropertiesException; +import com.decathlon.idp_core.domain.exception.entity_template.PropertyTypeChangeException; +import com.decathlon.idp_core.domain.exception.entity_template.RelationCannotTargetItselfException; +import com.decathlon.idp_core.domain.exception.entity_template.RelationNameAlreadyExistsException; import com.decathlon.idp_core.domain.exception.entity_template.RelationNameNotFoundEntityTemplateRelationsException; +import com.decathlon.idp_core.domain.exception.entity_template.RelationTargetTemplateChangeException; +import com.decathlon.idp_core.domain.exception.entity_template.TargetTemplateNotFoundException; +import com.decathlon.idp_core.domain.exception.filter.InvalidFilterDslException; +import com.decathlon.idp_core.domain.exception.principal.PrincipalNotFoundException; +import com.decathlon.idp_core.domain.exception.search.InvalidSearchQueryException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookAuthenticationException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookConnectorAlreadyExistException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookConnectorNotFoundException; +import com.decathlon.idp_core.domain.exception.webhook.WebhookConnectorTitleAlreadyExistsException; import com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; -/// Comprehensive unit tests for [ApiExceptionHandler]. -/// -/// Tests all exception handler methods and utility functions to ensure proper -/// error handling and response formatting across the API layer. -@DisplayName("ApiExceptionHandler Tests") class ApiExceptionHandlerTest { private ApiExceptionHandler exceptionHandler; @BeforeEach void setUp() throws Exception { - // Use reflection to create instance since constructor is private Constructor constructor = ApiExceptionHandler.class .getDeclaredConstructor(); constructor.setAccessible(true); exceptionHandler = constructor.newInstance(); } - @Nested - @DisplayName("Domain Exception Handling") - class DomainExceptionTests { - - /// Tests the handling of [EntityTemplateNotFoundException] by the - /// [ApiExceptionHandler]. - /// - /// **This test verifies that:** - /// - EntityTemplateNotFoundException is properly caught and handled - /// - HTTP 404 Not Found status is returned - /// - Error response contains the correct error status and description - /// - Original exception message is preserved in the response - @Test - @DisplayName("Should handle EntityTemplateNotFoundException with 404 status") - void shouldHandleEntityTemplateNotFoundException() { - // Given - String errorMessage = "Template with ID 'test-id' not found"; - EntityTemplateNotFoundException exception = new EntityTemplateNotFoundException(errorMessage); - - // When - ResponseEntity response = exceptionHandler - .handleTemplateNotFoundException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.NOT_FOUND.name(), body.getError()); - assertEquals(errorMessage, body.getErrorDescription()); - } + /** + * Creates a mocked {@link WebRequest} with a stubbed description, matching the + * framework's non-null contract for {@code getDescription(boolean)}. + */ + private static WebRequest mockWebRequest() { + WebRequest request = mock(WebRequest.class); + when(request.getDescription(false)).thenReturn("uri=/api/v1/test"); + return request; + } - /// Tests the handling of [EntityTemplateAlreadyExistsException] by the - /// [ApiExceptionHandler]. - /// - /// **This test verifies that:** - /// - EntityTemplateAlreadyExistsException is properly caught and handled - /// - HTTP 409 Conflict status is returned - /// - Error response contains the correct error status and formatted description - /// - Exception message is properly formatted with validation constants - @Test - @DisplayName("Should handle EntityTemplateAlreadyExistsException with 409 status") - void shouldHandleEntityTemplateAlreadyExistsException() { - // Given - String identifier = "duplicate-id"; - EntityTemplateAlreadyExistsException exception = new EntityTemplateAlreadyExistsException( - identifier); - String expectedMessage = "An Entity Template already exists with the same identifier:duplicate-id"; - - // When - ResponseEntity response = exceptionHandler - .handleEntityTemplateAlreadyExistsException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.CONFLICT, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.CONFLICT.name(), body.getError()); - assertEquals(expectedMessage, body.getErrorDescription()); - } + @Test + void shouldHandleEntityTemplateNotFoundException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityTemplateNotFoundException("missing")); + assertProblemDetail(body, HttpStatus.NOT_FOUND, "missing", "NOT_FOUND"); + } - /// Tests the handling of [EntityAlreadyExistsException] by the - /// [ApiExceptionHandler]. - /// - /// **This test verifies that:** - /// - EntityAlreadyExistsException is properly caught and handled - /// - HTTP 409 Conflict status is returned - /// - Error response contains the original domain exception message - @Test - @DisplayName("Should handle EntityAlreadyExistsException with 409 status") - void shouldHandleEntityAlreadyExistsException() { - // Given - EntityAlreadyExistsException exception = new EntityAlreadyExistsException("my-web-service", - "api-gateway"); - - // When - ResponseEntity response = exceptionHandler - .handleEntityAlreadyExistsException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.CONFLICT, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.CONFLICT.name(), body.getError()); - assertEquals(exception.getMessage(), body.getErrorDescription()); - } + @Test + void shouldHandleEntityTemplateAlreadyExistsException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityTemplateAlreadyExistsException("duplicate-id")); + assertProblemDetail(body, HttpStatus.CONFLICT, + "An Entity Template already exists with the same identifier:duplicate-id", "CONFLICT"); + } - @Test - @DisplayName("Should handle EntityValidationException with 400 status") - void shouldHandleEntityValidationException() { - EntityValidationException exception = new EntityValidationException( - java.util.List.of("Invalid property")); - - ResponseEntity response = exceptionHandler - .handleEntityValidationException(exception); - - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - assertEquals(exception.getMessage(), body.getErrorDescription()); - } + @Test + void shouldHandleEntityAlreadyExistsException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityAlreadyExistsException("a", "b")); + assertProblemDetail(body, HttpStatus.CONFLICT, + "Entity with name 'b' already exists for template 'a'", "CONFLICT"); + } - @Nested - @DisplayName("Validation Exception Handling") - class ValidationExceptionTests { - - @Test - @DisplayName("Should handle EntityDynamicMappingConfigurationException with 400 status") - void shouldHandleEntityDynamicMappingConfigurationException() { - String details = "Syntax Error in 'properties.deployment_id': Parse error"; - EntityDynamicMappingConfigurationException exception = new EntityDynamicMappingConfigurationException( - details); - - ResponseEntity response = exceptionHandler - .handleEntityDynamicMappingConfigurationException(exception); - - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - assertEquals(details, body.getErrorDescription()); - } - - @Test - @DisplayName("Should handle PropertyNameNotFoundEntityTemplatePropertiesException with 400 status") - void shouldHandlePropertyNameNotFoundEntityTemplatePropertiesException() { - String details = "Property name additionalProp3 not found in entity entityTemplateIdentifier properties"; - PropertyNameNotFoundEntityTemplatePropertiesException exception = new PropertyNameNotFoundEntityTemplatePropertiesException( - details); - - ResponseEntity response = exceptionHandler - .handlePropertyNameNotFoundEntityTemplatePropertiesException(exception); - - assertNotNull(response); - assertEquals(HttpStatus.UNPROCESSABLE_CONTENT, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.UNPROCESSABLE_CONTENT.name(), body.getError()); - assertEquals(details, body.getErrorDescription()); - } - - @Test - @DisplayName("Should handle RelationNameNotFoundEntityTemplateRelationsException with 400 status") - void shouldHandleRelationNameNotFoundEntityTemplateRelationsException() { - // Given - String details = "Relation name github_repository not found in entity entityTemplateIdentifier relations"; - RelationNameNotFoundEntityTemplateRelationsException exception = new RelationNameNotFoundEntityTemplateRelationsException( - details); - - // When - ResponseEntity response = exceptionHandler - .handleRelationNameNotFoundEntityTemplateRelationsException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.UNPROCESSABLE_CONTENT, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.UNPROCESSABLE_CONTENT.name(), body.getError()); - assertEquals(details, body.getErrorDescription()); - } - - @Test - @DisplayName("Should handle EntityDynamicMappingHasNoPropertiesException with 400 status") - void shouldHandleEntityDynamicMappingHasNoPropertiesException() { - String details = "The mapping defines properties but the target entityTemplateIdentifier has no property definitions"; - EntityDynamicMappingHasNoPropertiesException exception = new EntityDynamicMappingHasNoPropertiesException( - details); - - ResponseEntity response = exceptionHandler - .handleEntityDynamicMappingHasNoPropertiesException(exception); - - assertNotNull(response); - assertEquals(HttpStatus.UNPROCESSABLE_CONTENT, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.UNPROCESSABLE_CONTENT.name(), body.getError()); - assertEquals(details, body.getErrorDescription()); - } - - @Test - @DisplayName("Should handle WebhookSecurityConfigurationException with 400 status") - void shouldHandleWebhookSecurityConfigurationException() { - String details = "Webhook security type is mandatory"; - WebhookSecurityConfigurationException exception = new WebhookSecurityConfigurationException( - details); - - ResponseEntity response = exceptionHandler - .handleWebhookSecurityConfigurationException(exception); - - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - assertEquals(details, body.getErrorDescription()); - } - - /// Tests the handling of [ConstraintViolationException] with a single - /// validation violation. - /// - /// **This test verifies that:** - /// - ConstraintViolationException is properly caught and handled - /// - HTTP 400 Bad Request status is returned - /// - Single violation message is correctly extracted and returned - /// - Error response format matches expected structure - @Test - @DisplayName("Should handle ConstraintViolationException with single violation") - void shouldHandleConstraintViolationExceptionSingleViolation() { - // Given - ConstraintViolation violation = createMockConstraintViolation( - "Field must not be null"); - Set> violations = Set.of(violation); - ConstraintViolationException exception = new ConstraintViolationException( - "Validation failed", violations); - - // When - ResponseEntity response = exceptionHandler - .handleConstraintViolationException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - assertEquals("Field must not be null", body.getErrorDescription()); - } - - /// Tests the handling of [ConstraintViolationException] with multiple - /// validation violations. - /// - /// **This test verifies that:** - /// - ConstraintViolationException with multiple violations is properly handled - /// - HTTP 400 Bad Request status is returned - /// - All violation messages are concatenated with comma separation - /// - Error response contains all validation error messages - @Test - @DisplayName("Should handle ConstraintViolationException with multiple violations") - void shouldHandleConstraintViolationExceptionMultipleViolations() { - // Given - ConstraintViolation violation1 = createMockConstraintViolation( - "Field1 must not be null"); - ConstraintViolation violation2 = createMockConstraintViolation( - "Field2 must not be blank"); - Set> violations = Set.of(violation1, violation2); - ConstraintViolationException exception = new ConstraintViolationException( - "Validation failed", violations); - - // When - ResponseEntity response = exceptionHandler - .handleConstraintViolationException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - - String errorDescription = body.getErrorDescription(); - assertTrue(errorDescription.contains("Field1 must not be null")); - assertTrue(errorDescription.contains("Field2 must not be blank")); - assertTrue(errorDescription.contains(", ")); - } - - /// Tests the handling of [MethodArgumentNotValidException] with field - /// validation errors. - /// - /// **This test verifies that:** - /// - MethodArgumentNotValidException is properly caught and handled - /// - HTTP 400 Bad Request status is returned - /// - Field error messages from binding result are extracted and concatenated - /// - All field validation errors are included in the response with comma - /// separation - /// - /// @throws Exception if reflection fails during test setup - @Test - @DisplayName("Should handle MethodArgumentNotValidException with field errors") - void shouldHandleMethodArgumentNotValidException() throws Exception { - // Given - Object target = new Object(); - BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, - "testObject"); - bindingResult.addError(new FieldError("testObject", "field1", "Field1 is required")); - bindingResult.addError(new FieldError("testObject", "field2", "Field2 must be valid")); - - // Create a proper MethodParameter mock with required methods - MethodParameter methodParameter = mock(MethodParameter.class); - when(methodParameter.getExecutable()).thenReturn(this.getClass().getMethod("testMethod")); - - MethodArgumentNotValidException exception = new MethodArgumentNotValidException( - methodParameter, bindingResult); - - // When - ResponseEntity response = exceptionHandler - .handleMethodArgumentNotValidException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - String errorDescription = body.getErrorDescription(); - assertTrue(errorDescription.contains("Field1 is required")); - assertTrue(errorDescription.contains("Field2 must be valid")); - assertTrue(errorDescription.contains(", ")); - } - - // Helper method for mocking - public void testMethod() { - // Empty method for testing purposes - } - - @SuppressWarnings("unchecked") - private ConstraintViolation createMockConstraintViolation(String message) { - ConstraintViolation violation = mock(ConstraintViolation.class); - when(violation.getMessage()).thenReturn(message); - return violation; - } - } + @Test + void shouldHandleEntityValidationException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new EntityValidationException(java.util.List.of("Invalid property"))); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "Entity validation failed: Invalid property", + "BAD_REQUEST"); + } - /// Tests the handling of [ConstraintViolationException] with multiple - /// validation violations. - /// - /// **This test verifies that:** - /// - ConstraintViolationException with multiple violations is properly handled - /// - HTTP 400 Bad Request status is returned - /// - All violation messages are concatenated with comma separation - /// - Error response contains all validation error messages - @Test - @DisplayName("Should handle ConstraintViolationException with multiple violations") - void shouldHandleConstraintViolationExceptionMultipleViolations() { - // Given - ConstraintViolation violation1 = createMockConstraintViolation( - "Field1 must not be null"); - ConstraintViolation violation2 = createMockConstraintViolation( - "Field2 must not be blank"); - Set> violations = Set.of(violation1, violation2); - ConstraintViolationException exception = new ConstraintViolationException("Validation failed", - violations); - - // When - ResponseEntity response = exceptionHandler - .handleConstraintViolationException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - - String errorDescription = body.getErrorDescription(); - assertTrue(errorDescription.contains("Field1 must not be null")); - assertTrue(errorDescription.contains("Field2 must not be blank")); - assertTrue(errorDescription.contains(", ")); - } + @Test + void shouldHandleConstraintViolationException() { + ConstraintViolation violation = mock(ConstraintViolation.class); + when(violation.getMessage()).thenReturn("Field must not be null"); + ProblemDetail body = exceptionHandler.handleConstraintViolationException( + new ConstraintViolationException("failed", Set.of(violation))); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "Field must not be null", "BAD_REQUEST"); + } - /// Tests the handling of [MethodArgumentNotValidException] with field - /// validation errors. - /// - /// **This test verifies that:** - /// - MethodArgumentNotValidException is properly caught and handled - /// - HTTP 400 Bad Request status is returned - /// - Field error messages from binding result are extracted and concatenated - /// - All field validation errors are included in the response with comma - /// separation - /// - /// @throws Exception if reflection fails during test setup - @Test - @DisplayName("Should handle MethodArgumentNotValidException with field errors") - void shouldHandleMethodArgumentNotValidException() throws Exception { - // Given - Object target = new Object(); - BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, "testObject"); - bindingResult.addError(new FieldError("testObject", "field1", "Field1 is required")); - bindingResult.addError(new FieldError("testObject", "field2", "Field2 must be valid")); - - // Create a proper MethodParameter mock with required methods - MethodParameter methodParameter = mock(MethodParameter.class); - when(methodParameter.getExecutable()).thenReturn(this.getClass().getMethod("testMethod")); - - MethodArgumentNotValidException exception = new MethodArgumentNotValidException( - methodParameter, bindingResult); - - // When - ResponseEntity response = exceptionHandler - .handleMethodArgumentNotValidException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - String errorDescription = body.getErrorDescription(); - assertTrue(errorDescription.contains("Field1 is required")); - assertTrue(errorDescription.contains("Field2 must be valid")); - assertTrue(errorDescription.contains(", ")); - } + @Test + void shouldHandleMethodArgumentNotValidViaFrameworkOverride() throws Exception { + BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(new Object(), "obj"); + bindingResult.addError(new FieldError("obj", "field", "Field is required")); + MethodParameter methodParameter = new MethodParameter( + ApiExceptionHandlerTest.class.getDeclaredMethod("setUp"), -1); + MethodArgumentNotValidException ex = new MethodArgumentNotValidException(methodParameter, + bindingResult); + ProblemDetail body = (ProblemDetail) exceptionHandler.handleMethodArgumentNotValid(ex, + new HttpHeaders(), HttpStatus.BAD_REQUEST, mockWebRequest()).getBody(); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "Field is required", "BAD_REQUEST"); + } - // Helper method for mocking - public void testMethod() { - // Empty method for testing purposes - } + @Test + void shouldHandleHandlerMethodValidationViaFrameworkOverride() { + HandlerMethodValidationException ex = mock(HandlerMethodValidationException.class); + MessageSourceResolvable error = mock(MessageSourceResolvable.class); + when(error.getDefaultMessage()).thenReturn("Parameter is invalid"); + doReturn(List.of(error)).when(ex).getAllErrors(); - @SuppressWarnings("unchecked") - private ConstraintViolation createMockConstraintViolation(String message) { - ConstraintViolation violation = mock(ConstraintViolation.class); - when(violation.getMessage()).thenReturn(message); - return violation; - } + ResponseEntity response = exceptionHandler.handleHandlerMethodValidationException(ex, + new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, mockWebRequest()); + ProblemDetail body = (ProblemDetail) response.getBody(); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "Parameter is invalid", "BAD_REQUEST"); } - @Nested - @DisplayName("HTTP Message Exception Handling") - class HttpMessageExceptionTests { - - /// Provides test data for [HttpMessageNotReadableException] scenarios. Each - /// argument contains: input message and expected error description. - static Stream httpMessageNotReadableExceptionTestData() { - return Stream.of( - Arguments.of("Required request body is missing: public ResponseEntity", - "Request body is required"), - Arguments.of("JSON parse error: Unexpected character", - "Invalid JSON format in request body"), - Arguments.of( - "Cannot deserialize value of type `PropertyType` from String \"INVALID_TYPE\": not one of the values accepted for Enum class", - "Invalid value 'INVALID_TYPE' for property 'type'"), - Arguments.of( - "Cannot deserialize value of type `PropertyFormat` from String \"INVALID_FORMAT\": not one of the values accepted for Enum class", - "Invalid value 'INVALID_FORMAT' for property 'format'"), - Arguments.of( - "Cannot deserialize value of type `UnknownEnum` from String \"VALUE\": not one of the values accepted for Enum class", - "Invalid enum value in request body"), - Arguments.of("Cannot deserialize value of type `com.example.SomeType`: some other error", - "Invalid type: expected SomeType"), - Arguments.of("Something completely unexpected happened", "Invalid request body format"), - Arguments.of( - "Cannot deserialize value of type `PropertyType`: not one of the values accepted for Enum class", - "Invalid value for property 'type'")); - } + @Test + void shouldHandlePageTypeMismatchViaFrameworkOverride() { + MethodArgumentTypeMismatchException ex = new MethodArgumentTypeMismatchException("1.5", + Integer.class, "page", null, null); - /// Tests the handling of [HttpMessageNotReadableException] when exception - /// message is null. - /// - /// **This test verifies that:** - /// - HttpMessageNotReadableException with null message is properly handled - /// - HTTP 400 Bad Request status is returned - /// - Default error message is provided when original message is null - /// - Graceful handling of edge case scenarios - @Test - @DisplayName("Should handle HttpMessageNotReadableException with null message") - void shouldHandleHttpMessageNotReadableExceptionWithNullMessage() { - // Given - HttpMessageNotReadableException exception = mock(HttpMessageNotReadableException.class); - when(exception.getMessage()).thenReturn(null); - - // When - ResponseEntity response = exceptionHandler - .handleHttpMessageNotReadableException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - assertEquals("Invalid request body format", body.getErrorDescription()); - } + ResponseEntity response = exceptionHandler.handleTypeMismatch(ex, new HttpHeaders(), + HttpStatus.BAD_REQUEST, mockWebRequest()); - /// Parameterized test for handling [HttpMessageNotReadableException] with - /// various error scenarios. - /// - /// **This test verifies that different types of HttpMessageNotReadableException - /// are properly parsed and converted to user-friendly error messages:** - /// - Missing request body errors → "Request body is required" - /// - JSON parse errors → "Invalid JSON format in request body" - /// - PropertyType enum deserialization errors → Specific property and value - /// information - /// - Unknown enum deserialization errors → Generic enum error message - /// - /// **Each test case validates that:** - /// - HTTP 400 Bad Request status is returned - /// - Original complex error message is parsed and simplified - /// - User-friendly error description is provided - /// - Error response structure is consistent - /// - /// @param originalMessage the original exception message to be - /// processed - /// @param expectedErrorDescription the expected user-friendly error description - @ParameterizedTest - @MethodSource("httpMessageNotReadableExceptionTestData") - @DisplayName("Should handle HttpMessageNotReadableException with various error types") - void shouldHandleHttpMessageNotReadableExceptionWithVariousErrorTypes(String originalMessage, - String expectedErrorDescription) { - // Given - HttpMessageNotReadableException exception = mock(HttpMessageNotReadableException.class); - when(exception.getMessage()).thenReturn(originalMessage); - - // When - ResponseEntity response = exceptionHandler - .handleHttpMessageNotReadableException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.BAD_REQUEST.name(), body.getError()); - assertEquals(expectedErrorDescription, body.getErrorDescription()); - } + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertProblemDetail((ProblemDetail) response.getBody(), HttpStatus.BAD_REQUEST, + ValidationMessages.PAGE_INDEX_NOT_INTEGER, "BAD_REQUEST"); } - @Nested - @DisplayName("Generic Exception Handling") - class GenericExceptionTests { - - /// Tests the handling of generic Exception as a fallback mechanism. - /// - /// **This test verifies that:** - /// - Unexpected exceptions are caught by the generic handler - /// - HTTP 500 Internal Server Error status is returned - /// - Generic error message is provided to avoid exposing internal details - /// - Exception is properly logged for debugging purposes - @Test - @DisplayName("Should handle generic Exception with 500 status") - void shouldHandleGenericException() { - // Given - Exception exception = new RuntimeException("Unexpected error"); - - // When - ResponseEntity response = exceptionHandler.handleGenericException(exception); - - // Then - assertNotNull(response); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - ErrorResponse body = response.getBody(); - assertNotNull(body); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.name(), body.getError()); - assertEquals("An unexpected error occurred. Please try again later.", - body.getErrorDescription()); - } + @Test + void shouldHandleSizeTypeMismatchViaFrameworkOverride() { + MethodArgumentTypeMismatchException ex = new MethodArgumentTypeMismatchException("abc", + Integer.class, "size", null, null); + + ResponseEntity response = exceptionHandler.handleTypeMismatch(ex, new HttpHeaders(), + HttpStatus.BAD_REQUEST, mockWebRequest()); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertProblemDetail((ProblemDetail) response.getBody(), HttpStatus.BAD_REQUEST, + ValidationMessages.PAGE_SIZE_NOT_INTEGER, "BAD_REQUEST"); } - @Nested - @DisplayName("ErrorResponse Class Tests") - class ErrorResponseTests { - - /// Tests the creation of [ErrorResponse] using the all-arguments constructor. - /// - /// **This test verifies that:** - /// - ErrorResponse can be instantiated with HttpStatus and description - /// - All fields are properly initialized with provided values - /// - Getter methods return the expected values - /// - Object is successfully created and accessible - @Test - @DisplayName("Should create ErrorResponse with all args constructor") - void shouldCreateErrorResponseWithAllArgsConstructor() { - // Given - HttpStatus status = HttpStatus.BAD_REQUEST; - String description = "Test error message"; - - // When - ErrorResponse errorResponse = new ErrorResponse(status.name(), description); - - // Then - assertNotNull(errorResponse); - assertEquals(status.name(), errorResponse.getError()); - assertEquals(description, errorResponse.getErrorDescription()); - } + @Test + void shouldPreserveValueAndExpectedTypeForOtherParameterTypeMismatches() { + MethodArgumentTypeMismatchException ex = new MethodArgumentTypeMismatchException("deep", + Integer.class, "depth", null, null); + + ResponseEntity response = exceptionHandler.handleTypeMismatch(ex, new HttpHeaders(), + HttpStatus.BAD_REQUEST, mockWebRequest()); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertProblemDetail((ProblemDetail) response.getBody(), HttpStatus.BAD_REQUEST, + "Invalid value 'deep' for parameter 'depth'. Expected type: Integer.", "BAD_REQUEST"); + } + + @Test + void shouldPreserveAllowedValuesForEnumParameterTypeMismatches() { + MethodArgumentTypeMismatchException ex = new MethodArgumentTypeMismatchException("UNKNOWN", + AuthorizationAction.class, "action", null, null); + + ResponseEntity response = exceptionHandler.handleTypeMismatch(ex, new HttpHeaders(), + HttpStatus.BAD_REQUEST, mockWebRequest()); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertProblemDetail((ProblemDetail) response.getBody(), HttpStatus.BAD_REQUEST, + "Invalid value 'UNKNOWN' for parameter 'action'. " + + "Allowed values: [CREATE, READ, UPDATE, DELETE, UNSUPPORTED].", + "BAD_REQUEST"); + } + + @Test + void shouldDeclareUnambiguousExceptionHandlerMappings() { + assertDoesNotThrow(() -> new ExceptionHandlerMethodResolver(ApiExceptionHandler.class)); + } + + @Test + void shouldUseNativeProblemDetailForUnreadableMessage() throws Exception { + HttpMessageNotReadableException ex = new HttpMessageNotReadableException( + "Cannot deserialize value of type `PropertyType` from String \"INVALID_TYPE\"", + new HttpInputMessage() { + @Override + public HttpHeaders getHeaders() { + return new HttpHeaders(); + } + + @Override + public java.io.InputStream getBody() { + return java.io.InputStream.nullInputStream(); + } + }); + ProblemDetail body = (ProblemDetail) exceptionHandler.handleException(ex, mockWebRequest()) + .getBody(); + + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "Failed to read request", "BAD_REQUEST"); + } - /// Tests the creation of [ErrorResponse] using the no-arguments constructor. - /// - /// **This test verifies that:** - /// - ErrorResponse can be instantiated without parameters - /// - Object is successfully created with default/null field values - /// - Constructor works with `@NoArgsConstructor(force = true)` annotation - /// - Provides flexibility for frameworks requiring default constructors - @Test - @DisplayName("Should create ErrorResponse with no args constructor") - void shouldCreateErrorResponseWithNoArgsConstructor() { - ErrorResponse errorResponse = new ErrorResponse(); - assertNotNull(errorResponse); + @Test + void shouldSetInstanceOnDomainErrorsFromCurrentRequest() { + MockHttpServletRequest servletRequest = new MockHttpServletRequest(); + servletRequest.setRequestURI("/api/v1/entities/x"); + org.springframework.web.context.request.RequestContextHolder.setRequestAttributes( + new org.springframework.web.context.request.ServletRequestAttributes(servletRequest)); + try { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityAlreadyExistsException("a", "b")); + assertEquals("/api/v1/entities/x", String.valueOf(body.getInstance())); + } finally { + org.springframework.web.context.request.RequestContextHolder.resetRequestAttributes(); } } + + @Test + void shouldHandleGenericExceptionWithoutExposingInternalDetails() { + ProblemDetail body = exceptionHandler + .handleDomainException(new RuntimeException("Sensitive internal details")); + + assertProblemDetail(body, HttpStatus.INTERNAL_SERVER_ERROR, + "An unexpected error occurred. Please try again later.", "INTERNAL_SERVER_ERROR"); + } + + @Test + void shouldNormalizeInheritedFrameworkProblemDetails() throws Exception { + MockHttpServletRequest servletRequest = new MockHttpServletRequest(); + servletRequest.setRequestURI("/api/v1/test"); + ServletWebRequest webRequest = new ServletWebRequest(servletRequest); + + ResponseEntity response = exceptionHandler.handleException( + new MissingServletRequestParameterException("page", "integer"), webRequest); + ProblemDetail body = (ProblemDetail) response.getBody(); + + assertNotNull(body); + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + assertEquals(body.getDetail(), body.getProperties().get("error_description")); + assertNotNull(body.getProperties().get("timestamp")); + assertEquals("/api/v1/test", body.getInstance().toString()); + } + + @Test + void shouldPreserveExistingProblemDetailExtensionsAndInstance() { + ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input"); + Instant timestamp = Instant.parse("2026-10-14T08:00:00Z"); + body.setProperty("error", "CUSTOM_ERROR"); + body.setProperty("error_description", "Custom description"); + body.setProperty("timestamp", timestamp); + body.setInstance(URI.create("/original")); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setRequestURI("/replacement"); + + ResponseEntity response = exceptionHandler.createResponseEntity(body, new HttpHeaders(), + HttpStatus.BAD_REQUEST, new ServletWebRequest(request)); + + assertSame(body, response.getBody()); + assertEquals("CUSTOM_ERROR", body.getProperties().get("error")); + assertEquals("Custom description", body.getProperties().get("error_description")); + assertEquals(timestamp, body.getProperties().get("timestamp")); + assertEquals(URI.create("/original"), body.getInstance()); + } + + @Test + void shouldAddMissingExtensionsWithoutReplacingExistingProperties() { + ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input"); + body.setProperty("traceId", "trace-123"); + body.setProperty("error", "CUSTOM_ERROR"); + + exceptionHandler.createResponseEntity(body, new HttpHeaders(), HttpStatus.BAD_REQUEST, + mockWebRequest()); + + assertEquals("trace-123", body.getProperties().get("traceId")); + assertEquals("CUSTOM_ERROR", body.getProperties().get("error")); + assertEquals("Invalid input", body.getProperties().get("error_description")); + assertInstanceOf(Instant.class, body.getProperties().get("timestamp")); + assertNull(body.getInstance()); + } + + @Test + void shouldEnrichProblemDetailWithEmptyProperties() { + ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input"); + body.setProperties(new LinkedHashMap<>()); + + exceptionHandler.createResponseEntity(body, new HttpHeaders(), HttpStatus.BAD_REQUEST, + mockWebRequest()); + + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "Invalid input", "BAD_REQUEST"); + } + + @Test + void shouldUseNumericErrorForNonStandardHttpStatus() { + HttpStatusCode status = HttpStatusCode.valueOf(599); + ProblemDetail body = ProblemDetail.forStatusAndDetail(status, "Non-standard error"); + + ResponseEntity response = exceptionHandler.createResponseEntity(body, new HttpHeaders(), + status, mockWebRequest()); + + assertEquals(status, response.getStatusCode()); + assertEquals("599", body.getProperties().get("error")); + assertEquals("Non-standard error", body.getProperties().get("error_description")); + assertInstanceOf(Instant.class, body.getProperties().get("timestamp")); + } + + @Test + void shouldLeaveNonProblemDetailResponseUnchanged() { + Map body = Map.of("message", "original"); + HttpHeaders headers = new HttpHeaders(); + headers.add("X-Test", "unchanged"); + + ResponseEntity response = exceptionHandler.createResponseEntity(body, headers, + HttpStatus.BAD_REQUEST, mockWebRequest()); + + assertSame(body, response.getBody()); + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals("unchanged", response.getHeaders().getFirst("X-Test")); + } + + @Test + void shouldAllowResponseWithoutBody() { + ResponseEntity response = exceptionHandler.createResponseEntity(null, new HttpHeaders(), + HttpStatus.NO_CONTENT, mockWebRequest()); + + assertNull(response.getBody()); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + void shouldHandlePrincipalNotFoundException() { + PrincipalNotFoundException ex = new PrincipalNotFoundException("missing-principal"); + + ProblemDetail body = exceptionHandler.handleDomainException(ex); + + assertProblemDetail(body, HttpStatus.NOT_FOUND, ex.getMessage(), "NOT_FOUND"); + } + + @Test + void shouldHandlePrincipalNotAuthorizedException() { + PrincipalNotAuthorizedException ex = new PrincipalNotAuthorizedException( + "unauthorized-principal"); + + ProblemDetail body = exceptionHandler.handleDomainException(ex); + + assertProblemDetail(body, HttpStatus.FORBIDDEN, ex.getMessage(), "FORBIDDEN"); + } + + @Test + void shouldHandleMissingPathVariableViaFrameworkOverride() { + ProblemDetail body = (ProblemDetail) exceptionHandler.handleMissingPathVariable( + mock(org.springframework.web.bind.MissingPathVariableException.class), new HttpHeaders(), + HttpStatus.BAD_REQUEST, mockWebRequest()).getBody(); + assertNotNull(body); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldSetInstanceWhenWebRequestIsPresent() { + ServletWebRequest request = mock(ServletWebRequest.class); + when(request.getDescription(false)).thenReturn("uri=/api/v1/test"); + ProblemDetail body = (ProblemDetail) exceptionHandler.handleMissingPathVariable( + mock(org.springframework.web.bind.MissingPathVariableException.class), new HttpHeaders(), + HttpStatus.BAD_REQUEST, request).getBody(); + + assertNotNull(body); + assertNotNull(body.getInstance()); + assertEquals("/api/v1/test", body.getInstance().toString()); + } + + @Test + void shouldHandleInvalidFilterDslException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new InvalidFilterDslException("bad filter")); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "bad filter", "BAD_REQUEST"); + } + + @Test + void shouldHandleInvalidSearchQueryException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new InvalidSearchQueryException("bad query")); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "bad query", "BAD_REQUEST"); + } + + @Test + void shouldHandleEntityTemplateNameAlreadyExistsException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityTemplateNameAlreadyExistsException("duplicate-name")); + assertEquals(HttpStatus.CONFLICT.value(), body.getStatus()); + assertEquals("CONFLICT", body.getProperties().get("error")); + } + + @Test + void shouldHandleEntityTemplateIdentifierCannotChangeException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityTemplateIdentifierCannotChangeException("template-id")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandleWrongPropertyRulesException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new PropertyDefinitionRulesConflictException("property-test", "STRING", "not allowed")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandlePropertyNameAlreadyExistsException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new PropertyNameAlreadyExistsException("property-test")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandleRelationNameAlreadyExistsException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new RelationNameAlreadyExistsException("belongsto")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandleTargetTemplateNotFoundException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new TargetTemplateNotFoundException("non-existent")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandleEntityTemplateIsRelationTargetException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityTemplateIsRelationTargetException("microservice")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandleTypeChangeException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new PropertyTypeChangeException("name", "STRING", "NUMBER")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandleRelationTargetTemplateChangeException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new RelationTargetTemplateChangeException("dependencies", "service", "service-modified")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandleRelationCannotTargetItselfException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new RelationCannotTargetItselfException("circular", "self-ref-template")); + assertEquals(HttpStatus.BAD_REQUEST.value(), body.getStatus()); + assertEquals("BAD_REQUEST", body.getProperties().get("error")); + } + + @Test + void shouldHandleEntityDynamicMappingConfigurationException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new EntityDynamicMappingConfigurationException("invalid configuration")); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "invalid configuration", "BAD_REQUEST"); + } + + @Test + void shouldHandleExpressionEvaluationFailedException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new ExpressionEvaluationFailedException(".foo", "syntax error", null)); + assertEquals(HttpStatus.UNPROCESSABLE_CONTENT.value(), body.getStatus()); + assertEquals("UNPROCESSABLE_CONTENT", body.getProperties().get("error")); + } + + @Test + void shouldHandleEntityDynamicMappingJsltErrorException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityDynamicMappingJsltErrorException("jslt failed")); + assertProblemDetail(body, HttpStatus.UNPROCESSABLE_CONTENT, "jslt failed", + "UNPROCESSABLE_CONTENT"); + } + + @Test + void shouldHandlePropertyNameNotFoundEntityTemplatePropertiesException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new PropertyNameNotFoundEntityTemplatePropertiesException("unknown property")); + assertProblemDetail(body, HttpStatus.UNPROCESSABLE_CONTENT, "unknown property", + "UNPROCESSABLE_CONTENT"); + } + + @Test + void shouldHandleRelationNameNotFoundEntityTemplateRelationsException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new RelationNameNotFoundEntityTemplateRelationsException("unknown relation")); + assertProblemDetail(body, HttpStatus.UNPROCESSABLE_CONTENT, "unknown relation", + "UNPROCESSABLE_CONTENT"); + } + + @Test + void shouldHandleEntityDynamicMappingHasNoPropertiesException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new EntityDynamicMappingHasNoPropertiesException("missing properties")); + assertProblemDetail(body, HttpStatus.UNPROCESSABLE_CONTENT, "missing properties", + "UNPROCESSABLE_CONTENT"); + } + + @Test + void shouldHandleEntityDynamicMappingHasNoRelationsException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new EntityDynamicMappingHasNoRelationsException("missing relations")); + assertProblemDetail(body, HttpStatus.UNPROCESSABLE_CONTENT, "missing relations", + "UNPROCESSABLE_CONTENT"); + } + + @Test + void shouldHandleWebhookSecurityConfigurationException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new WebhookSecurityConfigurationException("invalid security")); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "invalid security", "BAD_REQUEST"); + } + + @Test + void shouldHandleEntityNotFoundException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityNotFoundException("template", "entity-id")); + assertEquals(HttpStatus.NOT_FOUND.value(), body.getStatus()); + assertEquals("NOT_FOUND", body.getProperties().get("error")); + } + + @Test + void shouldHandleEntityDeletionBlockedException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new EntityDeletionBlockedException("template", "entity-id", List.of("child-id"))); + assertEquals(HttpStatus.CONFLICT.value(), body.getStatus()); + assertEquals("CONFLICT", body.getProperties().get("error")); + } + + @Test + void shouldHandleWebhookAuthenticationException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new WebhookAuthenticationException("invalid signature")); + assertProblemDetail(body, HttpStatus.UNAUTHORIZED, "invalid signature", "UNAUTHORIZED"); + } + + @Test + void shouldHandleWebhookConnectorNotFoundException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new WebhookConnectorNotFoundException("connector-id")); + assertEquals(HttpStatus.NOT_FOUND.value(), body.getStatus()); + assertEquals("NOT_FOUND", body.getProperties().get("error")); + } + + @Test + void shouldHandleEntityDynamicMappingNotFoundException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityDynamicMappingNotFoundException("mapping-id")); + assertEquals(HttpStatus.NOT_FOUND.value(), body.getStatus()); + assertEquals("NOT_FOUND", body.getProperties().get("error")); + } + + @Test + void shouldHandleEntityDynamicMappingAlreadyExistsException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityDynamicMappingAlreadyExistsException("mapping-id")); + assertEquals(HttpStatus.CONFLICT.value(), body.getStatus()); + assertEquals("CONFLICT", body.getProperties().get("error")); + } + + @Test + void shouldHandleEntityDynamicMappingAlreadyInUseException() { + ProblemDetail body = exceptionHandler.handleDomainException( + new EntityDynamicMappingAlreadyInUseException(List.of("mapping-id"))); + assertEquals(HttpStatus.CONFLICT.value(), body.getStatus()); + assertEquals("CONFLICT", body.getProperties().get("error")); + } + + @Test + void shouldHandleWebhookConnectorAlreadyExistException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new WebhookConnectorAlreadyExistException("connector-id")); + assertEquals(HttpStatus.CONFLICT.value(), body.getStatus()); + assertEquals("CONFLICT", body.getProperties().get("error")); + } + + @Test + void shouldHandleTemplateAlreadyMappedInWebhookConfiguration() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityTemplateUsedByDynamicMappingException("template in use")); + assertProblemDetail(body, HttpStatus.CONFLICT, "template in use", "CONFLICT"); + } + + @Test + void shouldHandleWebhookConnectorTitleAlreadyExistsException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new WebhookConnectorTitleAlreadyExistsException("connector-name")); + assertEquals(HttpStatus.CONFLICT.value(), body.getStatus()); + assertEquals("CONFLICT", body.getProperties().get("error")); + } + + @Test + void shouldHandleDataIntegrityViolationException() { + Throwable rootCause = new RuntimeException("constraint violation"); + org.springframework.dao.DataIntegrityViolationException ex = mock( + org.springframework.dao.DataIntegrityViolationException.class); + when(ex.getMostSpecificCause()).thenReturn(rootCause); + + ProblemDetail body = exceptionHandler.handleDataIntegrityViolationException(ex); + + assertProblemDetail(body, HttpStatus.CONFLICT, + "The request conflicts with the current state of the resource", "CONFLICT"); + } + + @Test + void shouldHandleNoHandlerFoundExceptionViaFrameworkOverride() { + ProblemDetail body = (ProblemDetail) exceptionHandler.handleNoHandlerFoundException( + mock(org.springframework.web.servlet.NoHandlerFoundException.class), new HttpHeaders(), + HttpStatus.NOT_FOUND, mockWebRequest()).getBody(); + assertProblemDetail(body, HttpStatus.NOT_FOUND, + "Malformed request URL or missing path variable.", "NOT_FOUND"); + } + + private static void assertProblemDetail(ProblemDetail body, HttpStatus status, String detail, + String error) { + assertNotNull(body); + assertEquals(status.value(), body.getStatus()); + assertEquals(status.getReasonPhrase(), body.getTitle()); + assertEquals(detail, body.getDetail()); + assertEquals(error, body.getProperties().get("error")); + assertEquals(detail, body.getProperties().get("error_description")); + assertNotNull(body.getProperties().get("timestamp")); + } } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity/EntityDtoOutFromEntityNodeMapperTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity/EntityDtoOutFromEntityNodeMapperTest.java new file mode 100644 index 00000000..b0a2f967 --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/entity/EntityDtoOutFromEntityNodeMapperTest.java @@ -0,0 +1,67 @@ +package com.decathlon.idp_core.infrastructure.adapters.api.mapper.entity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.UUID; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.decathlon.idp_core.domain.model.entity.Property; +import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphNode; +import com.decathlon.idp_core.domain.model.entity_graph.EntityGraphRelation; +import com.decathlon.idp_core.domain.model.entity_template.EntityTemplate; +import com.decathlon.idp_core.domain.model.entity_template.PropertyDefinition; +import com.decathlon.idp_core.domain.model.enums.PropertyType; +import com.decathlon.idp_core.domain.service.entity_template.EntityTemplateService; + +@DisplayName("EntityDtoOutFromEntityNodeMapper tests") +class EntityDtoOutFromEntityNodeMapperTest { + + private final EntityTemplateService entityTemplateService = mock(EntityTemplateService.class); + + private EntityDtoOutFromEntityNodeMapper mapper; + + @BeforeEach + void setUp() { + mapper = new EntityDtoOutFromEntityNodeMapper(entityTemplateService); + } + + @Test + @DisplayName("Uses each related entity template to convert its properties") + void mapsRelatedPropertiesUsingRelatedTemplate() { + var rootTemplate = new EntityTemplate(UUID.randomUUID(), "root-template", "Root", null, + List.of(new PropertyDefinition(UUID.randomUUID(), "count", "Root count", + PropertyType.STRING, false, null)), + List.of()); + var relatedTemplate = new EntityTemplate(UUID.randomUUID(), "related-template", "Related", null, + List.of( + new PropertyDefinition(UUID.randomUUID(), "count", "Related count", PropertyType.NUMBER, + false, null), + new PropertyDefinition(UUID.randomUUID(), "enabled", "Related enabled", + PropertyType.BOOLEAN, false, null)), + List.of()); + when(entityTemplateService.getEntityTemplateByIdentifier("root-template")) + .thenReturn(rootTemplate); + when(entityTemplateService.getEntityTemplateByIdentifier("related-template")) + .thenReturn(relatedTemplate); + + var relatedNode = new EntityGraphNode("related-template", "related-1", "Related entity", + List.of(new Property(UUID.randomUUID(), "count", "42"), + new Property(UUID.randomUUID(), "enabled", "true")), + List.of(), List.of()); + var rootNode = new EntityGraphNode("root-template", "root-1", "Root entity", + List.of(new Property(UUID.randomUUID(), "count", "root-value")), + List.of(new EntityGraphRelation("uses", List.of(relatedNode))), List.of()); + + var result = mapper.toDto(rootNode, "root-template", 1, true); + + assertThat(result.properties()).containsEntry("count", "root-value"); + assertThat(result.relations().get("uses").get(0).properties()).containsEntry("count", 42.0) + .containsEntry("enabled", true); + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/webhook/InboundWebhookMapperTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/webhook/InboundWebhookMapperTest.java index 843cafc1..871e0bf5 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/webhook/InboundWebhookMapperTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/mapper/webhook/InboundWebhookMapperTest.java @@ -1,14 +1,17 @@ package com.decathlon.idp_core.infrastructure.adapters.api.mapper.webhook; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.Map; import java.util.UUID; +import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException; import com.decathlon.idp_core.domain.model.entity_mapping.EntityDynamicMapping; import com.decathlon.idp_core.domain.model.entity_mapping.MappingAction; import com.decathlon.idp_core.domain.model.entity_mapping.RelationMapping; @@ -75,11 +78,10 @@ void shouldThrowForUnknownSecurityType() { "Uses custom security", true, List.of("deployment-mapping"), new InboundWebhookSecurityContractDtoIn("CUSTOM_UNKNOWN_TYPE", Map.of("customKey", "customValue"))); + var mappings = List.of(resolvedMapping()); - org.assertj.core.api.Assertions - .assertThatThrownBy(() -> mapper.toDomain(request, List.of(resolvedMapping()))) - .isInstanceOf( - com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException.class) + Assertions.assertThatThrownBy(() -> mapper.toDomain(request, mappings)).isInstanceOf( + com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException.class) .hasMessageContaining("CUSTOM_UNKNOWN_TYPE"); } @@ -96,6 +98,32 @@ void shouldMapNoneSecurityTypeExplicitly() { assertThat(domain.security().config()).isEmpty(); } + @Test + @DisplayName("Should normalize an omitted (null) config of a NONE security to an empty map") + void shouldNormalizeNullConfigForNoneSecurity() { + InboundWebhookCreateDtoIn request = new InboundWebhookCreateDtoIn("my-connector", "No Auth", + "Webhook without authentication", true, List.of("deployment-mapping"), + new InboundWebhookSecurityContractDtoIn("NONE", null)); + + WebhookConnector domain = mapper.toDomain(request, List.of(resolvedMapping())); + + assertThat(domain.security().type()).isEqualTo(WebhookSecurityType.NONE); + assertThat(domain.security().config()).isNotNull().isEmpty(); + } + + @Test + @DisplayName("Should normalize an omitted (null) config on update for a NONE security") + void shouldNormalizeNullConfigOnUpdateForNoneSecurity() { + InboundWebhookUpdateDtoIn request = new InboundWebhookUpdateDtoIn("No Auth", + "Webhook without authentication", true, List.of("deployment-mapping"), + new InboundWebhookSecurityContractDtoIn("NONE", null)); + + WebhookConnector domain = mapper.toDomainForUpdate("identifier_from_path", request, + List.of(resolvedMapping())); + + assertThat(domain.security().config()).isNotNull().isEmpty(); + } + @Test @DisplayName("Should default to NONE when security section is missing") void shouldDefaultToNoneWhenSecurityIsMissing() { @@ -107,4 +135,68 @@ void shouldDefaultToNoneWhenSecurityIsMissing() { assertThat(domain.security().type()).isEqualTo(WebhookSecurityType.NONE); assertThat(domain.security().config()).isEmpty(); } + + @Test + @DisplayName("Should default an empty security object to NONE for a disabled connector") + void shouldDefaultEmptySecurityToNoneWhenDisabled() { + var request = new InboundWebhookCreateDtoIn("my-connector", "No Auth", "Disabled webhook", + false, List.of(), new InboundWebhookSecurityContractDtoIn(null, null)); + + var domain = mapper.toDomain(request, List.of()); + + assertThat(domain.security().type()).isEqualTo(WebhookSecurityType.NONE); + assertThat(domain.security().config()).isEmpty(); + } + + @Test + @DisplayName("Should reject an empty security object for an enabled connector") + void shouldRejectEmptySecurityWhenEnabled() { + var request = new InboundWebhookCreateDtoIn("my-connector", "No Auth", "Enabled webhook", true, + List.of("deployment-mapping"), new InboundWebhookSecurityContractDtoIn(null, null)); + var mappings = List.of(resolvedMapping()); + + assertThatThrownBy(() -> mapper.toDomain(request, mappings)) + .isInstanceOf(WebhookSecurityConfigurationException.class) + .hasMessageContaining("type is mandatory"); + } + + @Test + @DisplayName("Should default empty security to NONE when creating with no mappings") + void shouldDefaultEmptySecurityToNoneWhenCreatingWithNoMappings() { + var request = new InboundWebhookCreateDtoIn("my-connector", "No Auth", "Enabled webhook", true, + List.of(), new InboundWebhookSecurityContractDtoIn(null, null)); + + var domain = mapper.toDomain(request, List.of()); + + assertThat(domain.enabled()).isTrue(); + assertThat(domain.mappings()).isEmpty(); + assertThat(domain.security().type()).isEqualTo(WebhookSecurityType.NONE); + assertThat(domain.security().config()).isEmpty(); + } + + @Test + @DisplayName("Should default empty security to NONE when updating with no mappings") + void shouldDefaultEmptySecurityToNoneWhenUpdatingWithNoMappings() { + var request = new InboundWebhookUpdateDtoIn("No Auth", "Enabled webhook", true, List.of(), + new InboundWebhookSecurityContractDtoIn(null, null)); + + var domain = mapper.toDomainForUpdate("identifier_from_path", request, List.of()); + + assertThat(domain.enabled()).isTrue(); + assertThat(domain.mappings()).isEmpty(); + assertThat(domain.security().type()).isEqualTo(WebhookSecurityType.NONE); + assertThat(domain.security().config()).isEmpty(); + } + + @Test + @DisplayName("Should default an empty security object to NONE on disabled update") + void shouldDefaultEmptySecurityToNoneOnDisabledUpdate() { + var request = new InboundWebhookUpdateDtoIn("No Auth", "Disabled webhook", false, List.of(), + new InboundWebhookSecurityContractDtoIn(null, Map.of())); + + var domain = mapper.toDomainForUpdate("identifier_from_path", request, List.of()); + + assertThat(domain.security().type()).isEqualTo(WebhookSecurityType.NONE); + assertThat(domain.security().config()).isEmpty(); + } } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltEngineTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltEngineTest.java new file mode 100644 index 00000000..d14f24db --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltEngineTest.java @@ -0,0 +1,97 @@ +package com.decathlon.idp_core.infrastructure.adapters.entity_mapping.jslt; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.locks.LockSupport; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.decathlon.idp_core.domain.constant.JsltConstraints; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingJsltErrorException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.schibsted.spt.data.jslt.Function; + +/// Unit tests for the DoS protections of JsltEngine: expression length and evaluation timeout. +@DisplayName("JsltEngine") +class JsltEngineTest { + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Test + @DisplayName("Should evaluate a valid expression") + void shouldEvaluateValidExpression() throws Exception { + var engine = new JsltEngine(List.of()); + JsonNode payload = objectMapper.readTree("{\"name\":\"repo\"}"); + + JsonNode result = engine.evaluate(".name", payload); + + assertThat(result.asText()).isEqualTo("repo"); + } + + @Test + @DisplayName("Should reject an expression longer than the maximum length on validation") + void shouldRejectOversizedExpressionOnValidation() { + var engine = new JsltEngine(List.of()); + String expression = oversizedExpression(); + + assertThatThrownBy(() -> engine.validateExpression(expression)) + .isInstanceOf(EntityDynamicMappingJsltErrorException.class) + .hasMessageContaining("maximum length"); + } + + @Test + @DisplayName("Should reject an expression longer than the maximum length on evaluation") + void shouldRejectOversizedExpressionOnEvaluation() throws Exception { + var engine = new JsltEngine(List.of()); + JsonNode payload = objectMapper.readTree("{}"); + String expression = oversizedExpression(); + + assertThatThrownBy(() -> engine.evaluate(expression, payload)) + .isInstanceOf(EntityDynamicMappingJsltErrorException.class) + .hasMessageContaining("maximum length"); + } + + @Test + @DisplayName("Should fail evaluation that exceeds the evaluation timeout") + void shouldFailEvaluationExceedingTimeout() throws Exception { + var engine = new JsltEngine(List.of(new SlowFunction())); + JsonNode payload = objectMapper.readTree("{}"); + + assertThatThrownBy(() -> engine.evaluate("slow()", payload)) + .isInstanceOf(EntityDynamicMappingJsltErrorException.class) + .hasMessageContaining("exceeded timeout"); + } + + private static String oversizedExpression() { + return "\"" + "a".repeat(JsltConstraints.MAX_EXPRESSION_LENGTH) + "\""; + } + + private static final class SlowFunction implements Function { + + @Override + public String getName() { + return "slow"; + } + + @Override + public int getMinArguments() { + return 0; + } + + @Override + public int getMaxArguments() { + return 0; + } + + @Override + public JsonNode call(JsonNode input, JsonNode[] arguments) { + LockSupport.parkNanos(Duration.ofSeconds(30).toNanos()); + return input; + } + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltMappingEngineAdapterTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltMappingEngineAdapterTest.java index 9a73291e..76894dfc 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltMappingEngineAdapterTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/entity_mapping/jslt/JsltMappingEngineAdapterTest.java @@ -1,6 +1,8 @@ package com.decathlon.idp_core.infrastructure.adapters.entity_mapping.jslt; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Collections; import java.util.List; @@ -10,6 +12,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import com.decathlon.idp_core.domain.constant.JsltConstraints; +import com.decathlon.idp_core.domain.exception.entity_dynamic_mapping.EntityDynamicMappingConfigurationException; import com.decathlon.idp_core.domain.model.entity_mapping.EntityDynamicMapping; import com.decathlon.idp_core.domain.model.entity_mapping.MappingAction; import com.decathlon.idp_core.domain.model.entity_mapping.RelationMapping; @@ -120,4 +124,45 @@ void shouldExtractRelationFromArrayOfObjects() { .containsExactly("398cb790-9117-4bfe-830e-bbb0e423c26e"); } + @Test + @DisplayName("Should reject a payload larger than the maximum payload size") + void shouldRejectOversizedPayload() { + var mapping = new EntityDynamicMapping(null, "mapping", "microservice", ".action == \"pushed\"", + MappingAction.UPDATE_ENTITY, "Mapping", "desc", ".repository.full_name", ".repository.name", + Map.of(), List.of()); + var payload = "{\"data\":\"" + "a".repeat(JsltConstraints.MAX_PAYLOAD_BYTES) + "\"}"; + + assertThatThrownBy(() -> adapter.mapToEntity(payload, mapping)) + .isInstanceOf(EntityDynamicMappingConfigurationException.class) + .hasMessageContaining("maximum size"); + } + + @Test + @DisplayName("Should accept a payload nested at the maximum depth") + void shouldAcceptPayloadAtMaximumDepth() { + var mapping = new EntityDynamicMapping(null, "mapping", "microservice", ".action == \"pushed\"", + MappingAction.UPDATE_ENTITY, "Mapping", "desc", ".repository.full_name", ".repository.name", + Map.of(), List.of()); + var payload = nestedObject(JsltConstraints.MAX_JSON_DEPTH); + + assertThatCode(() -> adapter.mapToEntity(payload, mapping)).doesNotThrowAnyException(); + } + + @Test + @DisplayName("Should reject a payload nested beyond the maximum depth") + void shouldRejectPayloadBeyondMaximumDepth() { + var mapping = new EntityDynamicMapping(null, "mapping", "microservice", ".action == \"pushed\"", + MappingAction.UPDATE_ENTITY, "Mapping", "desc", ".repository.full_name", ".repository.name", + Map.of(), List.of()); + var payload = nestedObject(JsltConstraints.MAX_JSON_DEPTH + 1); + + assertThatThrownBy(() -> adapter.mapToEntity(payload, mapping)) + .isInstanceOf(EntityDynamicMappingConfigurationException.class) + .hasMessageContaining("maximum depth"); + } + + private static String nestedObject(int depth) { + return "{\"a\":".repeat(depth) + "1" + "}".repeat(depth); + } + } diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/InboundWebhookIngestionRouteTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/InboundWebhookIngestionRouteTest.java index 5454f971..e2f88d4c 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/InboundWebhookIngestionRouteTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/InboundWebhookIngestionRouteTest.java @@ -3,9 +3,11 @@ import static com.decathlon.idp_core.infrastructure.adapters.ingestion.configuration.IngestionConstants.HTTP_BAD_REQUEST; import static com.decathlon.idp_core.infrastructure.adapters.ingestion.configuration.IngestionConstants.HTTP_CREATED; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; @@ -37,6 +39,7 @@ import org.springframework.context.annotation.Primary; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.test.context.jdbc.Sql; @@ -218,9 +221,20 @@ private void assertJsonSuccessResponse(Exchange exchange) throws Exception { private void assertJsonErrorResponse(Exchange exchange, String expectedError, String expectedDescription) throws Exception { + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + int statusCode = exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class); JsonNode response = objectMapper.readTree(exchange.getMessage().getBody(String.class)); + HttpStatus status = HttpStatus.valueOf(statusCode); + assertEquals("about:blank", response.path("type").asText()); + assertEquals(status.getReasonPhrase(), response.path("title").asText()); + assertEquals(statusCode, response.path("status").asInt()); + assertEquals(expectedDescription, response.path("detail").asText()); assertEquals(expectedError, response.get("error").asText()); assertEquals(expectedDescription, response.get("error_description").asText()); + assertFalse(response.path("timestamp").isMissingNode()); + assertFalse(response.path("timestamp").isNull()); + assertFalse(response.path("timestamp").asText().isBlank()); } private void assertSecurityValidationSucceeded(Exchange exchange) { @@ -244,7 +258,8 @@ void postWebhookRoute_404_whenWebhookDoesNotExist() throws Exception { Exchange exchange = invokeIngestionRoute("does-not-exist"); assertEquals(404, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_connector_not_found", "Webhook configuration not found"); } @@ -255,7 +270,8 @@ void postWebhookRoute_403_whenWebhookIsDisabled() throws Exception { Exchange exchange = invokeIngestionRoute("disabled-connector"); assertEquals(403, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_connector_disabled", "Webhook connector is disabled"); } @@ -266,7 +282,8 @@ void postWebhookRoute_401_whenWebhookAuthenticationIsMissing() throws Exception Exchange exchange = invokeIngestionRoute("token-connector"); assertEquals(401, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_authentication_failed", "Webhook authentication failed"); } @@ -278,7 +295,8 @@ void postWebhookRoute_403_whenWebhookAuthenticationFails() throws Exception { Map.of("X-Auth-Token", "invalid-token")); assertEquals(403, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_forbidden", "Invalid credentials"); } @@ -326,7 +344,8 @@ void postWebhookRoute_401_whenHmacSignaturePrefixIsInvalid() throws Exception { null, Map.of("X-Hub-Signature-256", "sha1=abc123")); assertEquals(401, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_authentication_failed", "Webhook authentication failed"); } @@ -368,7 +387,8 @@ void validateSecurityRoute_401_whenBasicSchemeIsInvalid() throws Exception { Map.of("Authorization", "Bearer not-basic")); assertEquals(401, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_authentication_failed", "Webhook authentication failed"); } @@ -386,7 +406,8 @@ void validateSecurityRoute_403_whenBasicUsernameIsRejected() throws Exception { Map.of("Authorization", "Basic " + credentials)); assertEquals(403, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_forbidden", "Invalid credentials"); } @@ -403,7 +424,8 @@ void validateSecurityRoute_403_whenBasicPasswordIsRejected() throws Exception { Map.of("Authorization", "Basic " + credentials)); assertEquals(403, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_forbidden", "Invalid credentials"); } @@ -436,7 +458,7 @@ void validateSecurityRoute_acceptsJwtBearerMode() { @Test @DisplayName("Validate-security route returns 403 when the JWKS host is not allow-listed") - void validateSecurityRoute_403_whenJwksHostIsNotAllowListed() { + void validateSecurityRoute_403_whenJwksHostIsNotAllowListed() throws Exception { String jwksUri = "https://github.com/oauth2/certs"; when(jwtDecoderProvider.get(jwksUri)) .thenThrow(new WebhookJwksHostForbiddenException("github.com")); @@ -448,14 +470,7 @@ void validateSecurityRoute_403_whenJwksHostIsNotAllowListed() { Map.of("Authorization", "Bearer signed-token")); assertEquals(403, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); - try { - JsonNode response = objectMapper.readTree(exchange.getMessage().getBody(String.class)); - assertEquals("webhook_forbidden", response.get("error").asText()); - assertEquals("Invalid credentials", response.get("error_description").asText()); - } catch (Exception exception) { - throw new AssertionError("Unable to read webhook error response", exception); - } + assertJsonErrorResponse(exchange, "webhook_forbidden", "Invalid credentials"); } @Test @@ -464,7 +479,8 @@ void postWebhookRoute_500_whenWebhookConfigurationIsMissing() throws Exception { Exchange exchange = invokeValidationWithoutWebhookConfig(); assertEquals(500, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_configuration_missing", "Webhook configuration unavailable"); } @@ -488,7 +504,8 @@ void postWebhookRoute_400_whenGzipHeaderPayloadIsCorrupted() throws Exception { "gzip"); assertEquals(HTTP_BAD_REQUEST, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "invalid_compressed_payload", "Invalid, unsupported, or oversized compressed payload"); } @@ -499,7 +516,8 @@ void postWebhookRoute_400_whenGzipHeaderPayloadIsNull() throws Exception { Exchange exchange = invokeIngestionRoute("public-connector", null, "gzip"); assertEquals(HTTP_BAD_REQUEST, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "invalid_compressed_payload", "Invalid, unsupported, or oversized compressed payload"); } @@ -527,7 +545,8 @@ void validateSecurityRoute_401_whenMatchingStrategyIsNotAuthenticator() throws E Map.of("X-Auth-Token", "any-token")); assertEquals(401, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); - assertEquals("application/json", exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); + assertEquals(APPLICATION_PROBLEM_JSON_VALUE, + exchange.getMessage().getHeader(Exchange.CONTENT_TYPE)); assertJsonErrorResponse(exchange, "webhook_authentication_failed", "Webhook authentication failed"); } finally { diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/exception_handler/WebhookExceptionHandlerHelperTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/exception_handler/WebhookExceptionHandlerHelperTest.java new file mode 100644 index 00000000..e576192a --- /dev/null +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/exception_handler/WebhookExceptionHandlerHelperTest.java @@ -0,0 +1,65 @@ +package com.decathlon.idp_core.infrastructure.adapters.ingestion.exception_handler; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.decathlon.idp_core.infrastructure.adapters.ingestion.exception.WebhookDecodingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@DisplayName("Webhook exception handler helper tests") +class WebhookExceptionHandlerHelperTest { + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Test + @DisplayName("Maps decoding exceptions to RFC 7807 responses") + void registerHandler_whenDecodingException_returnsProblemDetail() throws Exception { + var context = new DefaultCamelContext(); + var handlerHelper = new WebhookExceptionHandlerHelper(objectMapper); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + handlerHelper.registerHandler(this, WebhookDecodingException.class, + WebhookErrorCode.INVALID_COMPRESSED_PAYLOAD); + from("direct:decode").process(exchange -> { + throw new WebhookDecodingException("Corrupted gzip payload"); + }); + } + }); + + ProducerTemplate producerTemplate = null; + try { + context.start(); + producerTemplate = context.createProducerTemplate(); + producerTemplate.start(); + + Exchange response = producerTemplate.request("direct:decode", exchange -> { + exchange.getMessage().setHeader(Exchange.HTTP_PATH, "/api/v1/inbound_webhooks/test"); + }); + + assertEquals(400, response.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); + assertEquals("application/problem+json", + response.getMessage().getHeader(Exchange.CONTENT_TYPE)); + JsonNode body = objectMapper.readTree(response.getMessage().getBody(String.class)); + assertEquals("about:blank", body.path("type").asText()); + assertEquals("Bad Request", body.path("title").asText()); + assertEquals(400, body.path("status").asInt()); + assertEquals("Invalid, unsupported, or oversized compressed payload", + body.path("detail").asText()); + assertEquals("/api/v1/inbound_webhooks/test", body.path("instance").asText()); + assertEquals("invalid_compressed_payload", body.path("error").asText()); + } finally { + if (producerTemplate != null) { + producerTemplate.stop(); + } + context.stop(); + } + } +} diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/IngestionProcessorTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/IngestionProcessorTest.java index 67855a54..8c2b872f 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/IngestionProcessorTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/processor/IngestionProcessorTest.java @@ -14,12 +14,16 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.LoggerFactory; @@ -94,6 +98,43 @@ private WebhookConnector createWebhookConnector(String identifier, Map.of("header_name", "X-Hub-Signature-256", "secret_alias", "MY_SECRET"))); } + @ParameterizedTest + @MethodSource("principalMappingOperations") + void ingest_doesNotApplyProtectedPrincipalProperties(MappingAction action, boolean exists) { + String payload = "{\"action\": \"pushed\"}"; + EntityDynamicMapping mapping = createTestMapping(action); + WebhookConnector connector = createWebhookConnector("principal-connector", List.of(mapping)); + Entity mappedPrincipal = new Entity(UUID.randomUUID(), "principal", "Mapped Principal", + "mapped-user", + List.of(new Property(null, "kind", "SERVICE_ACCOUNT"), + new Property(null, "is_admin", "true"), new Property(null, "is_idp_user", "true"), + new Property(null, "display_name", "Mapped User")), + List.of()); + when(mappingEngine.mapToEntity(payload, mapping)).thenReturn(mappedPrincipal); + when(entityService.entityExists("principal", "mapped-user")).thenReturn(exists); + + ingestionProcessor.ingest(payload, connector); + + if (exists) { + verify(entityService).patchEntity(eq("principal"), eq("mapped-user"), + argThat(patch -> containsOnlyUnprotectedProperties(patch.properties()))); + } else { + verify(entityService) + .createEntity(argThat(entity -> containsOnlyUnprotectedProperties(entity.properties()))); + } + } + + private static Stream principalMappingOperations() { + return Stream.of(MappingAction.UPDATE_ENTITY, MappingAction.UPDATE_PROPERTIES) + .flatMap(action -> Stream.of(false, true).map(exists -> Arguments.of(action, exists))); + } + + private static boolean containsOnlyUnprotectedProperties(List properties) { + return properties.stream() + .noneMatch(property -> List.of("kind", "is_admin", "is_idp_user").contains(property.name())) + && properties.stream().anyMatch(property -> "display_name".equals(property.name())); + } + @Nested @DisplayName("Ingestion with single mapping") class IngestionTest { diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/JwtBearerSecurityValidatorTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/JwtBearerSecurityValidatorTest.java index a6da25bd..f0b0e256 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/JwtBearerSecurityValidatorTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/JwtBearerSecurityValidatorTest.java @@ -135,7 +135,7 @@ void shouldThrowWhenJwksUriPointsToPrivateIpAddress() { @DisplayName("Should accept a host when it is allow-listed in security properties") void shouldAcceptAllowListedHost() { JwtBearerSecurityValidator safeValidator = new JwtBearerSecurityValidator(jwtDecoderProvider, - new WebhookSecurityProperties(Set.of("github.com"))) { + new WebhookSecurityProperties(Set.of("github.com"), false)) { @Override protected InetAddress[] resolveHostAddresses(String host) { throw new AssertionError("JWKS host validation should not run for allow-listed hosts"); @@ -152,7 +152,7 @@ protected InetAddress[] resolveHostAddresses(String host) { @DisplayName("Should reject a host when it is not allow-listed in security properties") void shouldRejectNonAllowListedHost() { JwtBearerSecurityValidator safeValidator = new JwtBearerSecurityValidator(jwtDecoderProvider, - new WebhookSecurityProperties(Set.of("auth.decathlon.com"))) { + new WebhookSecurityProperties(Set.of("auth.decathlon.com"), false)) { @Override protected InetAddress[] resolveHostAddresses(String host) { throw new AssertionError( @@ -225,15 +225,29 @@ void shouldThrowWhenClientIdValuesIsEnvironmentReference() { } @Test - @DisplayName("Should throw when client_id_field is neither azp nor email") - void shouldThrowWhenClientIdFieldIsUnsupported() { + @DisplayName("Should accept any non-empty claim name as client_id_field") + void shouldAcceptAnyNonEmptyClientIdField() { + JwtBearerSecurityValidator safeValidator = validatorWithPublicHostResolution(); + + for (String field : List.of("client_id", "sub", "azp", "email", "custom_tenant_id")) { + Map config = Map.of("jwks_uri", "https://issuer/.well-known/jwks.json", + "client_id_field", field, "client_id_values", "expected@example.com"); + + assertThatCode(() -> safeValidator.validateConfiguration(config)) + .doesNotThrowAnyException(); + } + } + + @Test + @DisplayName("Should throw when client_id_field is blank") + void shouldThrowWhenClientIdFieldIsBlank() { JwtBearerSecurityValidator safeValidator = validatorWithPublicHostResolution(); Map config = Map.of("jwks_uri", "https://issuer/.well-known/jwks.json", - "client_id_field", "sub", "client_id_values", "expected@example.com"); + "client_id_field", " ", "client_id_values", "expected@example.com"); assertThatThrownBy(() -> safeValidator.validateConfiguration(config)).isInstanceOf( com.decathlon.idp_core.domain.exception.webhook.WebhookSecurityConfigurationException.class) - .hasMessageContaining("azp").hasMessageContaining("email"); + .hasMessageContaining("client_id_field"); } @Test @@ -394,6 +408,33 @@ void shouldUseAzpClaimWhenConfigured() { .doesNotThrowAnyException(); } + @Test + @DisplayName("Should accept custom client_id claim when configured") + void shouldUseCustomClientIdClaim() { + when(jwtDecoderProvider.get("https://issuer/.well-known/jwks.json")).thenReturn(jwtDecoder); + Map config = Map.of("jwks_uri", "https://issuer/.well-known/jwks.json", + "client_id_field", "client_id", "client_id_values", "app_abc123"); + Map headers = Map.of("Authorization", "Bearer signed-token"); + when(jwtDecoder.decode("signed-token")).thenReturn(jwtWithClaim("client_id", "app_abc123")); + + assertThatCode(() -> validator.validateRequest(headers, new byte[0], config)) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("Should return unauthorized when configured claim is missing in JWT") + void shouldReturnUnauthorizedWhenConfiguredClaimMissing() { + when(jwtDecoderProvider.get("https://issuer/.well-known/jwks.json")).thenReturn(jwtDecoder); + Map config = Map.of("jwks_uri", "https://issuer/.well-known/jwks.json", + "client_id_field", "custom_tenant_id", "client_id_values", "tenant"); + Map headers = Map.of("Authorization", "Bearer signed-token"); + when(jwtDecoder.decode("signed-token")).thenReturn(jwtWithClaim("email", "a@b.c")); + + assertThatThrownBy(() -> validator.validateRequest(headers, new byte[0], config)) + .isInstanceOf(WebhookAuthUnauthorizedException.class) + .hasMessageContaining("custom_tenant_id"); + } + @Test @DisplayName("Should reject request when client_id_field is missing at runtime") void shouldRejectWhenClientIdFieldMissingAtRuntime() { diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookJwtDecoderProviderTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookJwtDecoderProviderTest.java index 436231f2..3440d0bd 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookJwtDecoderProviderTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/ingestion/security/WebhookJwtDecoderProviderTest.java @@ -31,7 +31,7 @@ void buildSecureRestTemplate_usesApacheHttpClientWithSecureDnsResolver() throws @DisplayName("accepts an allow-listed localhost JWKS host at runtime") void get_acceptsAllowListedLocalhost() { WebhookJwtDecoderProvider provider = new WebhookJwtDecoderProvider( - new WebhookSecurityProperties(Set.of("localhost"))); + new WebhookSecurityProperties(Set.of("localhost"), false)); assertThatCode(() -> provider.get("https://localhost/.well-known/jwks.json")) .doesNotThrowAnyException(); @@ -41,7 +41,7 @@ void get_acceptsAllowListedLocalhost() { @DisplayName("rejects a runtime JWKS host that is not allow-listed") void get_rejectsNonAllowListedHost() { WebhookJwtDecoderProvider provider = new WebhookJwtDecoderProvider( - new WebhookSecurityProperties(Set.of("auth.decathlon.com"))); + new WebhookSecurityProperties(Set.of("auth.decathlon.com"), false)); assertThatThrownBy(() -> provider.get("https://github.com/.well-known/jwks.json")) .isInstanceOf(WebhookJwksHostForbiddenException.class); diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/PostgresEntityAdapterTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/PostgresEntityAdapterTest.java index 67499886..60d01bf0 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/PostgresEntityAdapterTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/PostgresEntityAdapterTest.java @@ -1,6 +1,8 @@ package com.decathlon.idp_core.infrastructure.adapters.persistence; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -15,8 +17,16 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.Specification; import com.decathlon.idp_core.domain.model.entity.Entity; +import com.decathlon.idp_core.domain.model.search.LogicalConnector; +import com.decathlon.idp_core.domain.model.search.PaginationCriteria; +import com.decathlon.idp_core.domain.model.search.SearchFilterNode; import com.decathlon.idp_core.infrastructure.adapters.persistence.mapper.EntityPersistenceMapper; import com.decathlon.idp_core.infrastructure.adapters.persistence.model.entity.EntityJpaEntity; import com.decathlon.idp_core.infrastructure.adapters.persistence.repository.JpaEntityRepository; @@ -40,6 +50,19 @@ void setUp() { MockitoAnnotations.openMocks(this); } + @Test + @DisplayName("Should apply shared sort parsing to global search") + void shouldApplySharedSortParsingToSearch() { + when(jpaEntityRepository.findAll(any(Specification.class), any(Pageable.class))) + .thenReturn(new PageImpl<>(List.of())); + + adapter.search(new SearchFilterNode.Group(LogicalConnector.AND, List.of()), null, + new PaginationCriteria(0, 20, "identifier,desc")); + + verify(jpaEntityRepository).findAll(any(Specification.class), + eq(PageRequest.of(0, 20, Sort.by(Sort.Direction.DESC, "identifier")))); + } + @Nested @DisplayName("findAllByTemplateIdentifierAndIdentifierIn Tests") class FindAllByTemplateIdentifierAndIdentifierInTests { diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/CustomRevisionListenerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/CustomRevisionListenerTest.java index f46ea34a..55423b12 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/CustomRevisionListenerTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/CustomRevisionListenerTest.java @@ -12,7 +12,7 @@ import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; -import com.decathlon.idp_core.infrastructure.adapters.api.auth.UserIdentityProvider; +import com.decathlon.idp_core.domain.port.audit.AuditIdentityProviderPort; /** * Unit tests for CustomRevisionListener. @@ -25,7 +25,7 @@ class CustomRevisionListenerTest { @Mock - private UserIdentityProvider userIdentityProvider; + private AuditIdentityProviderPort userIdentityProvider; @Mock private CustomRevisionEntity revisionEntity; diff --git a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/UserIdentityProviderHolderTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/UserIdentityProviderHolderTest.java index a325f104..00a0d2a7 100644 --- a/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/UserIdentityProviderHolderTest.java +++ b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/persistence/model/audit/UserIdentityProviderHolderTest.java @@ -9,20 +9,20 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import com.decathlon.idp_core.infrastructure.adapters.api.auth.UserIdentityProvider; +import com.decathlon.idp_core.domain.port.audit.AuditIdentityProviderPort; /// Unit tests for UserIdentityProviderHolder. /// Covers the static holder pattern used to bridge Spring-managed beans with Hibernate Envers. @DisplayName("UserIdentityProviderHolder Tests") class UserIdentityProviderHolderTest { - private UserIdentityProvider mockProvider; + private AuditIdentityProviderPort mockProvider; @BeforeEach void setUp() { // Reset the static holder before each test resetHolder(); - mockProvider = mock(UserIdentityProvider.class); + mockProvider = mock(AuditIdentityProviderPort.class); } /// Helper to reset the static holder for test isolation @@ -72,7 +72,7 @@ void shouldInitializeStaticProvider() { @DisplayName("Should use injected provider during initialization") void shouldUseInjectedProvider() { // Given - UserIdentityProvider customProvider = mock(UserIdentityProvider.class); + AuditIdentityProviderPort customProvider = mock(AuditIdentityProviderPort.class); var holder = new UserIdentityProviderHolder(customProvider); // When @@ -95,8 +95,8 @@ void shouldThrowExceptionIfNotInitialized() { @DisplayName("Should reinitialize with new provider") void shouldReinitializeWithNewProvider() { // Given - var provider1 = mock(UserIdentityProvider.class); - var provider2 = mock(UserIdentityProvider.class); + var provider1 = mock(AuditIdentityProviderPort.class); + var provider2 = mock(AuditIdentityProviderPort.class); var holder1 = new UserIdentityProviderHolder(provider1); holder1.init(); @@ -118,8 +118,8 @@ class ThreadSafetyTests { @DisplayName("Should handle concurrent initialization safely") void shouldHandleConcurrentInitializationSafely() throws InterruptedException { // Given - var provider1 = mock(UserIdentityProvider.class); - var provider2 = mock(UserIdentityProvider.class); + var provider1 = mock(AuditIdentityProviderPort.class); + var provider2 = mock(AuditIdentityProviderPort.class); var thread1Results = new java.util.concurrent.CountDownLatch(1); var thread2Results = new java.util.concurrent.CountDownLatch(1); @@ -151,7 +151,7 @@ void shouldHandleConcurrentInitializationSafely() throws InterruptedException { @DisplayName("Should allow concurrent reads after initialization") void shouldAllowConcurrentReadsAfterInitialization() throws InterruptedException { // Given - var provider = mock(UserIdentityProvider.class); + var provider = mock(AuditIdentityProviderPort.class); var holder = new UserIdentityProviderHolder(provider); holder.init(); @@ -164,7 +164,7 @@ void shouldAllowConcurrentReadsAfterInitialization() throws InterruptedException new Thread(() -> { try { barrier.await(); - UserIdentityProvider result = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort result = UserIdentityProviderHolder.getUserIdentityProvider(); assertThat(result).isEqualTo(provider); } catch (Exception e) { throw new RuntimeException(e); @@ -192,7 +192,7 @@ void shouldReturnInitializedProvider() { holder.init(); // When - UserIdentityProvider result = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort result = UserIdentityProviderHolder.getUserIdentityProvider(); // Then assertThat(result).isEqualTo(mockProvider); @@ -206,9 +206,9 @@ void shouldPersistProviderAcrossAccesses() { holder.init(); // When & Then - UserIdentityProvider result1 = UserIdentityProviderHolder.getUserIdentityProvider(); - UserIdentityProvider result2 = UserIdentityProviderHolder.getUserIdentityProvider(); - UserIdentityProvider result3 = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort result1 = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort result2 = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort result3 = UserIdentityProviderHolder.getUserIdentityProvider(); assertThat(result1).isEqualTo(result2).isEqualTo(result3).isEqualTo(mockProvider); } @@ -217,12 +217,13 @@ void shouldPersistProviderAcrossAccesses() { @DisplayName("Should work as bridge for Hibernate Envers listeners") void shouldBridgeHibernateEnversAccess() { // Given - var provider = mock(UserIdentityProvider.class); + var provider = mock(AuditIdentityProviderPort.class); var holder = new UserIdentityProviderHolder(provider); holder.init(); // When - Simulate Envers listener access (non-Spring context) - UserIdentityProvider enversProvider = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort enversProvider = UserIdentityProviderHolder + .getUserIdentityProvider(); // Then assertThat(enversProvider).isNotNull().isEqualTo(provider); @@ -234,7 +235,7 @@ void shouldBridgeHibernateEnversAccess() { class ConstructorTests { @Test - @DisplayName("Should accept UserIdentityProvider in constructor") + @DisplayName("Should accept AuditIdentityProviderPort in constructor") void shouldAcceptProviderInConstructor() { // When UserIdentityProviderHolder holder = new UserIdentityProviderHolder(mockProvider); @@ -302,7 +303,7 @@ void shouldFollowSpringComponentPattern() { holder.init(); // Then - Simulates what Spring would do - UserIdentityProvider provider = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort provider = UserIdentityProviderHolder.getUserIdentityProvider(); assertThat(provider).isEqualTo(mockProvider); } @@ -310,10 +311,10 @@ void shouldFollowSpringComponentPattern() { @DisplayName("Should enable Hibernate Envers listener to access provider") void shouldEnableHibernateEnversAccess() { // Given - var provider = mock(UserIdentityProvider.class); + var provider = mock(AuditIdentityProviderPort.class); var holder = new UserIdentityProviderHolder(provider); holder.init(); - UserIdentityProvider enversAccessibleProvider = UserIdentityProviderHolder + AuditIdentityProviderPort enversAccessibleProvider = UserIdentityProviderHolder .getUserIdentityProvider(); // Then @@ -327,8 +328,8 @@ void shouldServeSingletonPatternForNonSpringCode() { var holder = new UserIdentityProviderHolder(mockProvider); holder.init(); - UserIdentityProvider access1 = UserIdentityProviderHolder.getUserIdentityProvider(); - UserIdentityProvider access2 = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort access1 = UserIdentityProviderHolder.getUserIdentityProvider(); + AuditIdentityProviderPort access2 = UserIdentityProviderHolder.getUserIdentityProvider(); assertThat(access1).isSameAs(access2).isEqualTo(mockProvider); } diff --git a/src/test/resources/application-test.yml b/src/test/resources/application-test.yml index 3ffe9025..9cab8771 100644 --- a/src/test/resources/application-test.yml +++ b/src/test/resources/application-test.yml @@ -29,8 +29,8 @@ spring: # Added App Security configuration app: security: - roles: - baseline-role: "*" + principal-provisioning: + mode: JIT authentication: jwt: enabled: true @@ -38,14 +38,17 @@ app: enabled: false mock: enabled: false + principal-extraction: + human-indicator-claims: + - sub + human: + id-claim: sub + machine: + id-claim: client_id + id-prefix: "machine:" user-claim-mappings: sub: "sub" preferred_username: "preferred_username" - service-account-detection: - enabled: true - mode: "legacy" - legacy-fallback-claims: "grant_type,service_name,client_id" - # ✅ Un-indented: Now properly binds to app.security.authentication.jit-provisioning-excluded-paths jit-provisioning-excluded-paths: "/,/actuator/**,/swagger-ui/**,/swagger-ui.html,/v3/api-docs/**" ingestion: webhook: @@ -61,6 +64,9 @@ app: jwks-env-key: JWKS_URI jwks-env-value: https://auth.example.com/.well-known/jwks.json management: + # Tests must not create or export traces. + tracing: + enabled: false endpoint: health: probes: @@ -82,3 +88,4 @@ idp: # Comma-separated allow-list for trusted JWKS hosts. # Example: ALLOWED_JWKS_HOSTS=github.com,auth.decathlon.com allowed-jwks-hosts: github.com,www.googleapis.com + allow-none: true diff --git a/src/test/resources/db/test/R__1_Insert_test_data.sql b/src/test/resources/db/test/R__1_Insert_test_data.sql index 1742bcc1..94dad35d 100644 --- a/src/test/resources/db/test/R__1_Insert_test_data.sql +++ b/src/test/resources/db/test/R__1_Insert_test_data.sql @@ -95,7 +95,8 @@ INSERT INTO property_definition (id, name, description, type, required, rules_id -- Principal properties ('550e8400-e29b-41d4-a716-446655440045', 'kind', 'Kind of principal', 'STRING', true, '550e8400-e29b-41d4-a716-446655440016'), ('550e8400-e29b-41d4-a716-446655440046', 'email', 'Email address (for HUMAN principals)', 'STRING', false, '550e8400-e29b-41d4-a716-446655440015'), -('550e8400-e29b-41d4-a716-446655440047', 'is_admin', 'is_admin', 'BOOLEAN', false, NULL); +('550e8400-e29b-41d4-a716-446655440047', 'is_admin', 'is_admin', 'BOOLEAN', false, NULL), +('550e8400-e29b-41d4-a716-446655440048', 'is_idp_user', 'is idp user', 'BOOLEAN', false, NULL); -- Insert diverse relation definitions INSERT INTO relation_definition (id, name, target_template_identifier, required, to_many) VALUES @@ -155,7 +156,8 @@ INSERT INTO entity_template (id, identifier, name, description) VALUES INSERT INTO entity_template_properties_definitions (entity_template_id, properties_definitions_id) VALUES ('550e8400-e29b-41d4-a716-446655440062', '550e8400-e29b-41d4-a716-446655440045'), -- kind ('550e8400-e29b-41d4-a716-446655440062', '550e8400-e29b-41d4-a716-446655440046'), -- email -('550e8400-e29b-41d4-a716-446655440062', '550e8400-e29b-41d4-a716-446655440047'); -- is_admin +('550e8400-e29b-41d4-a716-446655440062', '550e8400-e29b-41d4-a716-446655440047'), -- is_admin +('550e8400-e29b-41d4-a716-446655440062', '550e8400-e29b-41d4-a716-446655440048'); -- is_idp_user -- Link web-service template (comprehensive web API) INSERT INTO entity_template_properties_definitions (entity_template_id, properties_definitions_id) VALUES diff --git a/src/test/resources/db/test/R__6_insert_principal_user_for_test.sql b/src/test/resources/db/test/R__6_insert_principal_user_for_test.sql new file mode 100644 index 00000000..fb149dfa --- /dev/null +++ b/src/test/resources/db/test/R__6_insert_principal_user_for_test.sql @@ -0,0 +1,52 @@ +-- Test data for Principal Users +-- Purpose: provide pre-configured principal users for integration testing + +-- Clear existing data (for repeatable migrations) +DELETE +FROM idp_core.entity_properties +WHERE entity_id IN ('90000000-0000-0000-0000-000000000001', + '90000000-0000-0000-0000-000000000002', + '90000000-0000-0000-0000-000000000003'); +DELETE +FROM idp_core.property +WHERE id IN ('90000000-0000-0000-0000-000000001001', + '90000000-0000-0000-0000-000000001002', + '90000000-0000-0000-0000-000000001003', + '90000000-0000-0000-0000-000000001004', + '90000000-0000-0000-0000-000000001005', + '90000000-0000-0000-0000-000000001006', + '90000000-0000-0000-0000-000000001007', + '90000000-0000-0000-0000-000000001008'); +DELETE +FROM idp_core.entity +WHERE id IN ('90000000-0000-0000-0000-000000000001', + '90000000-0000-0000-0000-000000000002', + '90000000-0000-0000-0000-000000000003', + '90000000-0000-0000-0000-000000000004'); + +INSERT INTO idp_core.entity (id, identifier, name, template_identifier) +VALUES ('90000000-0000-0000-0000-000000000001', 'test-admin', 'Test Admin', 'principal'), + ('90000000-0000-0000-0000-000000000002', 'latest-tester', 'Latest user Admin', 'principal'), + ('90000000-0000-0000-0000-000000000003', 'webhook-service', 'Webhook Service', 'principal'), + ('90000000-0000-0000-0000-000000000004', 'user', 'Default Mock User', 'principal'); + +INSERT INTO idp_core.property (id, name, value) +VALUES ('90000000-0000-0000-0000-000000001001', 'kind', 'HUMAN'), + ('90000000-0000-0000-0000-000000001002', 'is_admin', 'true'), + ('90000000-0000-0000-0000-000000001003', 'kind', 'HUMAN'), + ('90000000-0000-0000-0000-000000001004', 'is_admin', 'true'), + ('90000000-0000-0000-0000-000000001005', 'kind', 'SERVICE_ACCOUNT'), + ('90000000-0000-0000-0000-000000001006', 'is_admin', 'false'), + ('90000000-0000-0000-0000-000000001007', 'kind', 'HUMAN'), + ('90000000-0000-0000-0000-000000001008', 'is_admin', 'true'); + + +INSERT INTO idp_core.entity_properties (entity_id, property_id) +VALUES ('90000000-0000-0000-0000-000000000001', '90000000-0000-0000-0000-000000001001'), + ('90000000-0000-0000-0000-000000000001', '90000000-0000-0000-0000-000000001002'), + ('90000000-0000-0000-0000-000000000002', '90000000-0000-0000-0000-000000001003'), + ('90000000-0000-0000-0000-000000000002', '90000000-0000-0000-0000-000000001004'), + ('90000000-0000-0000-0000-000000000003', '90000000-0000-0000-0000-000000001005'), + ('90000000-0000-0000-0000-000000000003', '90000000-0000-0000-0000-000000001006'), + ('90000000-0000-0000-0000-000000000004', '90000000-0000-0000-0000-000000001007'), + ('90000000-0000-0000-0000-000000000004', '90000000-0000-0000-0000-000000001008'); diff --git a/src/test/resources/integration_test/json/entity/v1/postEntity_400_relation_target_entity_does_not_exist.json b/src/test/resources/integration_test/json/entity/v1/postEntity_optional_missing_relation_target.json similarity index 100% rename from src/test/resources/integration_test/json/entity/v1/postEntity_400_relation_target_entity_does_not_exist.json rename to src/test/resources/integration_test/json/entity/v1/postEntity_optional_missing_relation_target.json