diff --git a/.github/workflows/basic_code_checks.yml b/.github/workflows/basic_code_checks.yml index 6e7d1214..0d0d63fb 100644 --- a/.github/workflows/basic_code_checks.yml +++ b/.github/workflows/basic_code_checks.yml @@ -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 diff --git a/docs/src/concepts/entity-filtering.md b/docs/src/concepts/entity-filtering.md index de6843f8..e434ad3f 100644 --- a/docs/src/concepts/entity-filtering.md +++ b/docs/src/concepts/entity-filtering.md @@ -203,7 +203,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 by default (configurable with `MAX_PAGE_SIZE`). -- `sort`: `field,asc|desc`. Allowed sort fields: `identifier`, `name`, `templateIdentifier`. +- `sort`: `field:asc|desc`. Allowed sort fields: `identifier`, `name`, `templateIdentifier`. ### Operator semantics 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 7b0f7f9b..c9f89612 100644 --- a/docs/src/contributing/code/exception-handling.md +++ b/docs/src/contributing/code/exception-handling.md @@ -6,27 +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, including errors written directly by security filters: +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" } ``` + +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/static/swagger.yaml b/docs/src/static/swagger.yaml index b4dde0d7..bd634ffa 100644 --- a/docs/src/static/swagger.yaml +++ b/docs/src/static/swagger.yaml @@ -29,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 @@ -46,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 @@ -72,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 @@ -117,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 @@ -137,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 @@ -163,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/ProblemDetail' + '400': + description: Entity template identifier is mandatory or target entity template not found + content: + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $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 @@ -209,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 @@ -229,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 @@ -255,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 @@ -288,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 @@ -320,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 @@ -330,17 +324,15 @@ 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. + description: When true, include property values for related entities. Defaults to false. required: false schema: type: boolean @@ -349,15 +341,15 @@ paths: '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 @@ -381,44 +373,51 @@ 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" + $ref: '#/components/schemas/ProblemDetail' delete: 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. + 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 @@ -439,37 +438,44 @@ paths: '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/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '500': description: Unexpected server-side failure content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' patch: tags: - Entities Management summary: Partially update an existing entity - description: Partially update an existing entity in the system with the provided - information + description: Partially update an existing entity in the system with the provided information operationId: patchEntity parameters: - name: templateIdentifier @@ -488,38 +494,46 @@ paths: content: application/json: schema: - "$ref": "#/components/schemas/EntityPatchDtoIn" + $ref: '#/components/schemas/EntityPatchDtoIn' 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" - "/webhooks/{webhookIdentifier}": + $ref: '#/components/schemas/ProblemDetail' + /webhooks/{webhookIdentifier}: post: tags: - spring-boot-platform-http-consumer @@ -527,7 +541,7 @@ paths: responses: '200': description: OK - "/api/v1/inbound_webhooks": + /api/v1/inbound_webhooks: get: tags: - Inbound Webhook Management @@ -539,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. Must be between 1 and - 500. + 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: field[,asc|desc]' + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' content: - "*/*": + '*/*': schema: type: string default: identifier,asc @@ -564,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. Must be between 1 and - 500. + 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: field[,asc|desc]' + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' content: - "*/*": + '*/*': schema: type: string default: identifier,asc @@ -643,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 @@ -736,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. Must be between 1 and - 500. + 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: field[,asc|desc]' + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' content: - "*/*": + '*/*': schema: type: string default: identifier,asc @@ -761,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 @@ -780,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 @@ -808,17 +815,16 @@ 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. Must be between 1 and - 500. + description: Number of items per page. Defaults to 20. Must be between 1 and 500. required: false content: - "*/*": + '*/*': schema: type: integer default: '20' @@ -836,31 +842,39 @@ paths: required: true schema: type: string + - name: sort + in: query + description: 'Sorting criteria in the format: property(,asc|desc). Defaults to identifier,asc.' + required: false + content: + '*/*': + schema: + type: string + default: identifier,asc - name: q 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: '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 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 @@ -878,57 +892,64 @@ 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 @@ -948,23 +969,22 @@ paths: '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 @@ -981,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 @@ -990,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 @@ -1010,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 @@ -1019,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 @@ -1031,41 +1048,53 @@ 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/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '404': description: Entity not found with the provided identifier content: - "*/*": + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/entities/principals/me": + $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). + 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': @@ -1073,38 +1102,38 @@ paths: content: application/json: schema: - "$ref": "#/components/schemas/EntityDtoOut" + $ref: '#/components/schemas/EntityDtoOut' '401': description: Unauthorized - Missing or invalid token content: - application/json: + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '403': description: Insufficient rights content: - application/json: + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '404': description: Principal not found in catalog (JIT provisioning may have failed) content: - application/json: + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" + $ref: '#/components/schemas/ProblemDetail' '500': description: Unexpected server-side failure content: - application/json: + application/problem+json: schema: - "$ref": "#/components/schemas/ErrorResponse" - "/api/v1/audit/entities/{templateIdentifier}/{entityIdentifier}": + $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 @@ -1123,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 @@ -1167,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 @@ -1228,7 +1264,7 @@ components: items: type: string security: - "$ref": "#/components/schemas/InboundWebhookSecurityContractDtoIn" + $ref: '#/components/schemas/InboundWebhookSecurityContractDtoIn' required: - name EntityDynamicMappingDtoOut: @@ -1252,7 +1288,7 @@ components: description: type: string entity: - "$ref": "#/components/schemas/InboundWebhookEntityMappingDtoOut" + $ref: '#/components/schemas/InboundWebhookEntityMappingDtoOut' InboundWebhookDtoOut: type: object properties: @@ -1267,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: @@ -1284,7 +1320,7 @@ components: relations: type: array items: - "$ref": "#/components/schemas/RelationMappingDtoOut" + $ref: '#/components/schemas/RelationMappingDtoOut' InboundWebhookSecurityDtoOut: type: object properties: @@ -1303,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: @@ -1347,7 +1402,7 @@ components: description: type: string entity: - "$ref": "#/components/schemas/EntityMappingDtoIn" + $ref: '#/components/schemas/EntityMappingDtoIn' required: - action - entity @@ -1370,7 +1425,7 @@ components: relations: type: array items: - "$ref": "#/components/schemas/EntityDynamicMappingRelationDtoIn" + $ref: '#/components/schemas/EntityDynamicMappingRelationDtoIn' required: - identifier - name @@ -1384,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 @@ -1393,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: @@ -1429,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 @@ -1457,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 @@ -1525,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 @@ -1556,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: @@ -1581,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 @@ -1643,7 +1698,7 @@ components: type: array description: List of relations for this entity items: - "$ref": "#/components/schemas/RelationDtoIn" + $ref: '#/components/schemas/RelationDtoIn' required: - name RelationDtoIn: @@ -1683,7 +1738,7 @@ components: additionalProperties: type: array items: - "$ref": "#/components/schemas/EntitySummaryDto" + $ref: '#/components/schemas/EntitySummaryDto' EntitySummaryDto: type: object properties: @@ -1696,8 +1751,7 @@ components: properties: type: object additionalProperties: {} - description: Property values for the related entity; included only when - include_relations_properties=true + description: Property values for the related entity; included only when include_relations_properties=true InboundWebhookCreateDtoIn: type: object properties: @@ -1718,7 +1772,7 @@ components: items: type: string security: - "$ref": "#/components/schemas/InboundWebhookSecurityContractDtoIn" + $ref: '#/components/schemas/InboundWebhookSecurityContractDtoIn' required: - identifier - name @@ -1747,7 +1801,7 @@ components: description: type: string entity: - "$ref": "#/components/schemas/EntityMappingDtoIn" + $ref: '#/components/schemas/EntityMappingDtoIn' required: - action - entity @@ -1760,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: @@ -1787,7 +1841,7 @@ components: type: array description: Extracted relations items: - "$ref": "#/components/schemas/DryRunRelationDto" + $ref: '#/components/schemas/DryRunRelationDto' DryRunEntityResultDto: type: object properties: @@ -1798,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 @@ -1831,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 @@ -1847,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 @@ -1856,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 @@ -1891,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 @@ -1901,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 @@ -1919,45 +1971,39 @@ components: type: integer format: int32 default: 20 - description: Number of items per page. Defaults to 20. Must be between 1 - and 500. + 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: field[,asc|desc]' + 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 @@ -1966,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: + first: type: boolean numberOfElements: type: integer format: int32 sort: - "$ref": "#/components/schemas/SortObject" - first: - type: boolean + $ref: '#/components/schemas/SortObject' size: type: integer format: int32 @@ -2007,7 +2053,7 @@ components: type: integer format: int32 sort: - "$ref": "#/components/schemas/SortObject" + $ref: '#/components/schemas/SortObject' unpaged: type: boolean SortObject: @@ -2038,7 +2084,7 @@ components: type: array description: List of relations for this entity items: - "$ref": "#/components/schemas/RelationDtoIn" + $ref: '#/components/schemas/RelationDtoIn' WebhookConnectorPageResponse: type: object description: Paginated response containing Inbound Webhook Connector objects @@ -2046,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: + first: type: boolean numberOfElements: type: integer format: int32 sort: - "$ref": "#/components/schemas/SortObject" - first: - type: boolean + $ref: '#/components/schemas/SortObject' size: type: integer format: int32 @@ -2079,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: + first: type: boolean numberOfElements: type: integer format: int32 sort: - "$ref": "#/components/schemas/SortObject" - first: - type: boolean + $ref: '#/components/schemas/SortObject' size: type: integer format: int32 @@ -2112,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: + first: type: boolean numberOfElements: type: integer format: int32 sort: - "$ref": "#/components/schemas/SortObject" - first: - type: boolean + $ref: '#/components/schemas/SortObject' size: type: integer format: int32 @@ -2160,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: @@ -2184,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 @@ -2208,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 @@ -2230,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/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 index 54259d82..9191811d 100644 --- 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 @@ -50,7 +50,8 @@ public class GlobalAuthorizationFilter extends OncePerRequestFilter { /// @param authorizationPolicy configured policy for authenticated requests /// @param authorizationRequestFactory maps HTTP input to domain authorization /// context - /// @param errorResponseWriter writes standard JSON errors at the filter + /// @param errorResponseWriter writes standard ProblemDetail errors at the + /// filter /// boundary public GlobalAuthorizationFilter(PrincipalExtractor principalExtractor, PrincipalProvisioningService provisioningService, @@ -82,7 +83,7 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, : null; Optional principalInfo = principalContext != null ? Optional.of(principalContext.principal()) - : extractPrincipal(authentication, response); + : extractPrincipal(authentication, request, response); if (principalInfo.isEmpty()) { return; } @@ -103,7 +104,7 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, authorizationRequest.resource().type(), request.getMethod(), request.getRequestURI()); log.warn("Authorization denied for principal {} on {} {}", principal.identifier(), request.getMethod(), request.getRequestURI()); - errorResponseWriter.write(response, HttpStatus.FORBIDDEN, + errorResponseWriter.write(request, response, HttpStatus.FORBIDDEN, "Principal is not authorized to perform this operation"); return; } @@ -117,12 +118,12 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, } private Optional extractPrincipal(Authentication authentication, - HttpServletResponse response) throws IOException { + HttpServletRequest request, HttpServletResponse response) throws IOException { try { return Optional.of(principalExtractor.extractPrincipalInfo(authentication)); } catch (MissingPrincipalIdentifierException exception) { log.warn("Authentication rejected: {}", exception.getMessage()); - errorResponseWriter.write(response, HttpStatus.UNAUTHORIZED, 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 c6791685..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 @@ -117,7 +117,7 @@ private boolean provisionPrincipalSafely(HttpServletRequest request, HttpServlet principalInfo = principalExtractor.extractPrincipalInfo(authentication); } catch (MissingPrincipalIdentifierException exception) { log.warn("Authentication rejected: {}", exception.getMessage()); - errorResponseWriter.write(response, HttpStatus.UNAUTHORIZED, exception.getMessage()); + errorResponseWriter.write(request, response, HttpStatus.UNAUTHORIZED, exception.getMessage()); return false; } @@ -143,7 +143,7 @@ private boolean provisionPrincipalSafely(HttpServletRequest request, HttpServlet log.debug("Principal evaluation rejected: mode={}, principal={}, kind={}, linked=false", PrincipalProvisioningMode.LINK_ONLY, principalInfo.identifier(), principalInfo.kind()); - errorResponseWriter.write(response, HttpStatus.UNAUTHORIZED, + errorResponseWriter.write(request, response, HttpStatus.UNAUTHORIZED, "No linked principal matches the authenticated identity"); return false; } @@ -160,7 +160,7 @@ private boolean provisionPrincipalSafely(HttpServletRequest request, HttpServlet if (matchingPrincipal.isEmpty()) { log.debug("Principal evaluation rejected: mode={}, principal={}, kind={}, linked=false", PrincipalProvisioningMode.JIT, principalInfo.identifier(), principalInfo.kind()); - errorResponseWriter.write(response, HttpStatus.UNAUTHORIZED, + errorResponseWriter.write(request, response, HttpStatus.UNAUTHORIZED, "No linked principal matches the authenticated identity"); return false; } @@ -174,7 +174,7 @@ private boolean provisionPrincipalSafely(HttpServletRequest request, HttpServlet return true; } catch (Exception e) { log.warn("JIT provisioning failed for authenticated principal: {}", e.getMessage(), e); - errorResponseWriter.write(response, HttpStatus.SERVICE_UNAVAILABLE, + errorResponseWriter.write(request, response, HttpStatus.SERVICE_UNAVAILABLE, "Unable to verify your access at this time. Please try again later."); return false; } 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/controller/AuditController.java b/src/main/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/AuditController.java index 1b3c7a6f..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; @@ -32,7 +33,6 @@ 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; @@ -79,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 e8984822..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 @@ -64,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; @@ -104,7 +106,6 @@ 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; @@ -161,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 @@ -168,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"))) @@ -178,9 +180,8 @@ public class EntityController { @ResponseStatus(OK) @GetMapping("/{templateIdentifier}") public Page getEntities(@RequestParam(defaultValue = "0") int page, - @RequestParam(required = false) Integer size, - @RequestParam(defaultValue = "identifier,asc") String sort, - @PathVariable String templateIdentifier, @RequestParam(required = false) String q) { + @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); @@ -224,7 +225,7 @@ public Page getEntities(@RequestParam(defaultValue = "0") int page @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")) @@ -260,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, @@ -297,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, @@ -324,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, @@ -355,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, @@ -384,7 +393,7 @@ public void deleteEntity(@NotBlank @PathVariable String templateIdentifier, @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) 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 798e46fd..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 @@ -11,6 +11,7 @@ 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; @@ -30,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; @@ -75,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"))) @@ -90,7 +90,7 @@ 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, @@ -105,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( @@ -119,11 +119,11 @@ 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, @@ -152,11 +152,11 @@ private void authorizePrincipalMapping(HttpServletRequest request, Authorization @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) 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 d10aa52b..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 @@ -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; @@ -35,7 +36,6 @@ 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; @@ -81,8 +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 = BAD_REQUEST_CODE, description = RESPONSE_INVALID_GRAPH_QUERY, content = @Content(schema = @Schema(implementation = ErrorResponse.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 e383d204..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 @@ -37,6 +37,8 @@ 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; @@ -59,7 +61,6 @@ 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; @@ -107,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"))) @@ -128,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) { @@ -146,7 +147,7 @@ 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( @@ -173,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) { @@ -192,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 92f064df..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,6 +8,7 @@ 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; @@ -19,7 +20,6 @@ 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; @@ -62,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"))) @@ -77,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) { @@ -88,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) { @@ -100,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 2209aa31..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; @@ -25,7 +26,6 @@ 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; @@ -75,10 +75,10 @@ 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); 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 index 5d9d061d..b9c6e063 100644 --- 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 @@ -1,38 +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.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.RequiredArgsConstructor; -/// Writes the standard API error body from servlet filters. +/// Writes the standard ProblemDetail response from servlet filters. @Component @RequiredArgsConstructor public class ApiErrorResponseWriter { private final ObjectMapper objectMapper; - /// Writes an error status and the standard JSON error response. + /// 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(HttpServletResponse response, HttpStatus status, String description) - throws IOException { + 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_JSON_VALUE); + response.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); - objectMapper.writeValue(response.getOutputStream(), - new ErrorResponse(status.name(), description)); + 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 9ef4c381..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,27 +1,41 @@ 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.time.Instant; import java.util.Arrays; -import java.util.List; 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; @@ -29,681 +43,287 @@ 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.api.exception.MissingPrincipalIdentifierException; -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() { } - /// Rejects authenticated principals that do not provide their configured - /// identifier claim. - @ExceptionHandler(MissingPrincipalIdentifierException.class) - public ResponseEntity handleMissingPrincipalIdentifierException( - MissingPrincipalIdentifierException ex) { - log.warn("Authentication rejected: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.UNAUTHORIZED, ex.getMessage()); - } - - /// 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); + /** + * 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 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); + /** + * 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 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); + /** 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 non-integer query or path parameters, such as `size=abc`. - /// - /// **HTTP mapping:** Maps Spring MethodArgumentTypeMismatchException to HTTP - /// 400 with a message naming the offending parameter, instead of the generic - /// HTTP 500 fallback. - @ExceptionHandler(MethodArgumentTypeMismatchException.class) - public ResponseEntity handleMethodArgumentTypeMismatchException( - MethodArgumentTypeMismatchException ex) { - String errorMessage = switch (ex.getName()) { - case "page" -> ValidationMessages.PAGE_INDEX_NOT_INTEGER; - case "size" -> ValidationMessages.PAGE_SIZE_NOT_INTEGER; - default -> "Invalid value '%s' for parameter '%s'.".formatted(ex.getValue(), ex.getName()); - }; - if (!"page".equals(ex.getName()) && !"size".equals(ex.getName())) { - Class requiredType = ex.getRequiredType(); - if (requiredType != null && requiredType.isEnum()) { - errorMessage += " Allowed values: " + Arrays.toString(requiredType.getEnumConstants()) - + "."; - } else if (requiredType != null) { - errorMessage += " Expected type: " + requiredType.getSimpleName() + "."; - } + /** 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("Request parameter type mismatch: {}", errorMessage); - return createErrorResponse(HttpStatus.BAD_REQUEST, errorMessage); - } - - /// 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()); - } - - /// 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()); - } - - /// 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()); + log.warn("{}: {}", ex.getClass().getSimpleName(), ex.getMessage()); + return buildProblemDetail(status, ex.getMessage(), null); } - /// 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()); - } - - /// 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 domain exception when a principal is not authorized. - /// - /// **HTTP mapping:** Maps PrincipalNotAuthorizedException to HTTP 403 - /// Forbidden. - @ExceptionHandler(PrincipalNotAuthorizedException.class) - public ResponseEntity handlePrincipalNotAuthorizedException( - PrincipalNotAuthorizedException ex) { - log.warn("Principal not authorized: {}", ex.getMessage()); - return createErrorResponse(HttpStatus.FORBIDDEN, ex.getMessage()); - } - - /// 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/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/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/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/infrastructure/adapters/api/auth/GlobalAuthorizationFilterTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/auth/GlobalAuthorizationFilterTest.java index 44984e68..95d71c2e 100644 --- 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 @@ -156,9 +156,13 @@ void shouldReturnForbiddenAndStopChainWhenAuthorizationIsDenied() filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(403); - assertThat(response.getContentType()).startsWith("application/json"); - assertThat(response.getContentAsString()).contains("\"error\":\"FORBIDDEN\"", - "\"error_description\":\"Principal is not authorized to perform this operation\""); + 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); } @@ -173,8 +177,13 @@ void shouldRejectMissingPrincipalIdentifierAsUnauthorized() throws ServletExcept filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(401); - assertThat(response.getContentAsString()).contains("\"error\":\"UNAUTHORIZED\"", - "\"error_description\":\"Required principal identifier claim 'id' is missing or blank\""); + 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()); } 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 f6a53e26..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 @@ -160,7 +160,7 @@ void doFilterInternal_inLinkOnlyMode_rejectsMissingIdentity() jitProvisioningFilter.doFilterInternal(request, response, filterChain); verify(provisioningService, never()).provisionPrincipal(any()); - verify(errorResponseWriter).write(response, HttpStatus.UNAUTHORIZED, + verify(errorResponseWriter).write(request, response, HttpStatus.UNAUTHORIZED, "No linked principal matches the authenticated identity"); verify(filterChain, never()).doFilter(any(), any()); } @@ -191,7 +191,7 @@ void doFilterInternal_inLinkOnlyMode_provisionsAndAllowsUnlinkedGlobalPrincipal( verify(request).setAttribute(ProvisionedPrincipalContext.REQUEST_ATTRIBUTE, new ProvisionedPrincipalContext(principalInfo, Optional.of(principalEntity))); verify(filterChain).doFilter(request, response); - verify(errorResponseWriter, never()).write(any(), any(), any()); + verify(errorResponseWriter, never()).write(any(), any(), any(), any()); } @ParameterizedTest(name = "{0} {1} wrongKind={2}") @@ -233,9 +233,9 @@ void doFilterInternal_appliesProvisioningModeForBothActorKinds(PrincipalProvisio if (shouldContinue) { verify(filterChain).doFilter(request, response); - verify(errorResponseWriter, never()).write(any(), any(), any()); + verify(errorResponseWriter, never()).write(any(), any(), any(), any()); } else { - verify(errorResponseWriter).write(response, HttpStatus.UNAUTHORIZED, + verify(errorResponseWriter).write(request, response, HttpStatus.UNAUTHORIZED, "No linked principal matches the authenticated identity"); verify(filterChain, never()).doFilter(any(), any()); } @@ -319,7 +319,7 @@ void doFilterInternal_whenProvisioningThrowsException_failsClosed() // Act & Assert (Should not throw exception) jitProvisioningFilter.doFilterInternal(request, response, filterChain); - verify(errorResponseWriter).write(response, HttpStatus.SERVICE_UNAVAILABLE, + 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()); } @@ -339,7 +339,7 @@ void doFilterInternal_inLinkOnlyMode_whenPrincipalLookupThrowsException_failsClo jitProvisioningFilter.doFilterInternal(request, response, filterChain); - verify(errorResponseWriter).write(response, HttpStatus.SERVICE_UNAVAILABLE, + 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()); } @@ -355,7 +355,7 @@ void doFilterInternal_whenIdentifierClaimIsMissing_rejectsAuthentication() jitProvisioningFilter.doFilterInternal(request, response, filterChain); - verify(errorResponseWriter).write(response, HttpStatus.UNAUTHORIZED, + 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()); @@ -375,7 +375,7 @@ void doFilterInternal_whenOtherPrincipalExtractionFailureOccurs_propagatesIt() () -> jitProvisioningFilter.doFilterInternal(request, response, filterChain)) .isInstanceOf(IllegalStateException.class).hasMessage("Unexpected extraction failure"); - verify(errorResponseWriter, never()).write(any(), any(), any()); + verify(errorResponseWriter, never()).write(any(), any(), any(), any()); verify(filterChain, never()).doFilter(any(), any()); } 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/controller/EntityControllerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityControllerTest.java index 2a7a9ae2..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 @@ -5,6 +5,7 @@ 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; @@ -148,8 +149,16 @@ void getEntities_nonIntegerPage_400() throws Exception { @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 @@ -301,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 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 a6e42276..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 @@ -3,6 +3,7 @@ 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; @@ -18,6 +19,7 @@ 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; @@ -257,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"))); } @@ -289,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"))); } @@ -316,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"))); } @@ -345,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"))); } @@ -377,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 = """ { @@ -410,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 @@ -441,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"))); } @@ -513,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"))); } @@ -563,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"))); } } @@ -599,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()); } @@ -639,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()); } @@ -689,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)); } } @@ -717,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 @@ -727,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()); } @@ -738,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"))); } } @@ -1202,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"))); } @@ -1225,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"))); } @@ -1254,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"))); } @@ -1290,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"))); } @@ -1338,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"))); } @@ -1370,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))); } @@ -1406,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"))); } @@ -1456,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"))); } @@ -1498,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]"))); } @@ -1549,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"))); } @@ -1743,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/EntityTemplateControllerTest.java b/src/test/java/com/decathlon/idp_core/infrastructure/adapters/api/controller/EntityTemplateControllerTest.java index 60ce4c1d..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,6 +5,7 @@ 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; @@ -488,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")); } @@ -504,7 +513,7 @@ 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"); } @@ -519,7 +528,7 @@ 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"); } @@ -871,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 @@ -883,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 @@ -895,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 @@ -907,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 @@ -919,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 @@ -931,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 @@ -946,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 @@ -1007,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 @@ -1158,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()); @@ -1182,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()); 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 cc2f3723..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,770 +1,686 @@ package com.decathlon.idp_core.infrastructure.adapters.api.handler; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +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.CsvSource; -import org.junit.jupiter.params.provider.EnumSource; -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.test.web.servlet.client.RestTestClient; +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.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.controller.EntityGraphController; -import com.decathlon.idp_core.infrastructure.adapters.api.exception.MissingPrincipalIdentifierException; -import com.decathlon.idp_core.infrastructure.adapters.common.model.ErrorResponse; - -/// 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") +import com.decathlon.idp_core.domain.model.authorization.AuthorizationAction; + 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("Request parameter conversion") - class RequestParameterConversionTests { + /** + * 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; + } - private EntityGraphService graphService; - private RestTestClient client; + @Test + void shouldHandleEntityTemplateNotFoundException() { + ProblemDetail body = exceptionHandler + .handleDomainException(new EntityTemplateNotFoundException("missing")); + assertProblemDetail(body, HttpStatus.NOT_FOUND, "missing", "NOT_FOUND"); + } - @BeforeEach - void setUpClient() { - graphService = mock(EntityGraphService.class); - client = RestTestClient.bindToController(new EntityGraphController(graphService)) - .configureServer(builder -> builder.setControllerAdvice(exceptionHandler)).build(); - } + @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"); + } - @ParameterizedTest - @CsvSource({"traversal_mode, OUTBOUND_ONL", "traversal_mode, UNKNOWN", - "traversal_mode, outbound_only", "depth, abc", "include_data, invalid"}) - @DisplayName("Should return 400 with a description for invalid graph parameters") - void shouldRejectInvalidGraphParameters(String parameter, String value) { - client.get().uri("/api/v1/entities/product/test/graph?{parameter}={value}", parameter, value) - .exchange().expectStatus().isBadRequest().expectBody(ErrorResponse.class).value(body -> { - assertEquals("BAD_REQUEST", body.getError()); - assertTrue(body.getErrorDescription().contains(parameter)); - assertTrue(body.getErrorDescription().contains(value)); - if ("traversal_mode".equals(parameter)) { - assertTrue(body.getErrorDescription() - .contains("Allowed values: [DIRECT_LINEAGE, BIDIRECTIONAL, OUTBOUND_ONLY].")); - } - }); - verifyNoInteractions(graphService); - } + @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"); + } - @ParameterizedTest - @EnumSource(EntityGraphTraversalMode.class) - @DisplayName("Should continue accepting all supported traversal modes") - void shouldAcceptSupportedTraversalModes(EntityGraphTraversalMode mode) { - client.get().uri("/api/v1/entities/product/test/graph?traversal_mode={mode}", mode).exchange() - .expectStatus().isOk(); + @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"); + } - verify(graphService).getEntityGraph("product", "test", - new EntityGraphQueryOptions(1, false, false, Set.of(), Set.of(), mode)); - } + @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"); + } - @Test - @DisplayName("Should preserve the default traversal mode") - void shouldPreserveDefaultTraversalMode() { - client.get().uri("/api/v1/entities/product/test/graph").exchange().expectStatus().isOk(); + @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"); + } - verify(graphService).getEntityGraph("product", "test", new EntityGraphQueryOptions(1, false, - false, Set.of(), Set.of(), EntityGraphTraversalMode.DIRECT_LINEAGE)); - } + @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(); - @Test - @DisplayName("Should describe the expected type for non-enum parameters") - void shouldDescribeExpectedType() { - var exception = new MethodArgumentTypeMismatchException("abc", int.class, "depth", - mock(MethodParameter.class), new IllegalArgumentException()); + ResponseEntity response = exceptionHandler.handleHandlerMethodValidationException(ex, + new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, mockWebRequest()); + ProblemDetail body = (ProblemDetail) response.getBody(); - var response = exceptionHandler.handleMethodArgumentTypeMismatchException(exception); + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "Parameter is invalid", "BAD_REQUEST"); + } - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - assertNotNull(response.getBody()); - assertEquals("Invalid value 'abc' for parameter 'depth'. Expected type: int.", - response.getBody().getErrorDescription()); - } + @Test + void shouldHandlePageTypeMismatchViaFrameworkOverride() { + MethodArgumentTypeMismatchException ex = new MethodArgumentTypeMismatchException("1.5", + Integer.class, "page", null, null); - @Test - @DisplayName("Should handle parameter type mismatches without a required type") - void shouldHandleUnknownRequiredType() { - var exception = new MethodArgumentTypeMismatchException("invalid", null, "parameter", - mock(MethodParameter.class), new IllegalArgumentException()); + ResponseEntity response = exceptionHandler.handleTypeMismatch(ex, new HttpHeaders(), + HttpStatus.BAD_REQUEST, mockWebRequest()); - var response = exceptionHandler.handleMethodArgumentTypeMismatchException(exception); + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertProblemDetail((ProblemDetail) response.getBody(), HttpStatus.BAD_REQUEST, + ValidationMessages.PAGE_INDEX_NOT_INTEGER, "BAD_REQUEST"); + } - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - assertNotNull(response.getBody()); - assertEquals("Invalid value 'invalid' for parameter 'parameter'.", - response.getBody().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("Domain Exception Handling") - class DomainExceptionTests { + @Test + void shouldPreserveValueAndExpectedTypeForOtherParameterTypeMismatches() { + MethodArgumentTypeMismatchException ex = new MethodArgumentTypeMismatchException("deep", + Integer.class, "depth", null, null); - @Test - void shouldHandlePrincipalNotAuthorizedExceptionWith403Status() { - var exception = new PrincipalNotAuthorizedException("platform-user"); + ResponseEntity response = exceptionHandler.handleTypeMismatch(ex, new HttpHeaders(), + HttpStatus.BAD_REQUEST, mockWebRequest()); - ResponseEntity response = exceptionHandler - .handlePrincipalNotAuthorizedException(exception); + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertProblemDetail((ProblemDetail) response.getBody(), HttpStatus.BAD_REQUEST, + "Invalid value 'deep' for parameter 'depth'. Expected type: Integer.", "BAD_REQUEST"); + } - assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); - assertEquals(HttpStatus.FORBIDDEN.name(), response.getBody().getError()); - assertEquals(exception.getMessage(), response.getBody().getErrorDescription()); - } + @Test + void shouldPreserveAllowedValuesForEnumParameterTypeMismatches() { + MethodArgumentTypeMismatchException ex = new MethodArgumentTypeMismatchException("UNKNOWN", + AuthorizationAction.class, "action", null, null); - @Test - void shouldHandleMissingPrincipalIdentifierAsUnauthorized() { - var exception = new MissingPrincipalIdentifierException("id"); + ResponseEntity response = exceptionHandler.handleTypeMismatch(ex, new HttpHeaders(), + HttpStatus.BAD_REQUEST, mockWebRequest()); - ResponseEntity response = exceptionHandler - .handleMissingPrincipalIdentifierException(exception); + 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"); + } - assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); - assertEquals(HttpStatus.UNAUTHORIZED.name(), response.getBody().getError()); - assertEquals(exception.getMessage(), response.getBody().getErrorDescription()); - } + @Test + void shouldDeclareUnambiguousExceptionHandlerMappings() { + assertDoesNotThrow(() -> new ExceptionHandlerMethodResolver(ApiExceptionHandler.class)); + } - /// 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()); - } + @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 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 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(); } + } - /// 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 shouldHandleGenericExceptionWithoutExposingInternalDetails() { + ProblemDetail body = exceptionHandler + .handleDomainException(new RuntimeException("Sensitive internal details")); - @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()); - } + assertProblemDetail(body, HttpStatus.INTERNAL_SERVER_ERROR, + "An unexpected error occurred. Please try again later.", "INTERNAL_SERVER_ERROR"); + } - /// 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 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()); + } - /// 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 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()); + } - // Helper method for mocking - public void testMethod() { - // Empty method for testing purposes - } + @Test + void shouldAddMissingExtensionsWithoutReplacingExistingProperties() { + ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input"); + body.setProperty("traceId", "trace-123"); + body.setProperty("error", "CUSTOM_ERROR"); - @SuppressWarnings("unchecked") - private ConstraintViolation createMockConstraintViolation(String message) { - ConstraintViolation violation = mock(ConstraintViolation.class); - when(violation.getMessage()).thenReturn(message); - return violation; - } + exceptionHandler.createResponseEntity(body, new HttpHeaders(), HttpStatus.BAD_REQUEST, + mockWebRequest()); - @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; - } - } + 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()); } - @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 shouldEnrichProblemDetailWithEmptyProperties() { + ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input"); + body.setProperties(new LinkedHashMap<>()); - /// 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()); - } + exceptionHandler.createResponseEntity(body, 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()); - } + assertProblemDetail(body, HttpStatus.BAD_REQUEST, "Invalid input", "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 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")); } - @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 shouldLeaveNonProblemDetailResponseUnchanged() { + Map body = Map.of("message", "original"); + HttpHeaders headers = new HttpHeaders(); + headers.add("X-Test", "unchanged"); - /// 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); - } + 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/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(); + } + } +}