diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 9f66b35cac..a7b2edc9cb 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -46,24 +46,36 @@ duplicate override IDs. | **APIs** | CreateRestApi, ImportRestApi, PutRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi | | **Resources** | CreateResource, GetResource, GetResources, UpdateResource, DeleteResource | | **Methods** | PutMethod, GetMethod, UpdateMethod, DeleteMethod | -| **Method Responses** | PutMethodResponse, GetMethodResponse | +| **Method Responses** | PutMethodResponse, GetMethodResponse, DeleteMethodResponse | | **Integrations** | PutIntegration, GetIntegration, UpdateIntegration, DeleteIntegration | -| **Integration Responses** | PutIntegrationResponse, GetIntegrationResponse | -| **Deployments** | CreateDeployment, GetDeployments | +| **Integration Responses** | PutIntegrationResponse, GetIntegrationResponse, UpdateIntegrationResponse, DeleteIntegrationResponse | +| **Deployments** | CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment | | **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage | -| **Authorizers** | CreateAuthorizer, GetAuthorizer, GetAuthorizers | -| **API Keys** | CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey | -| **Usage Plans** | CreateUsagePlan, GetUsagePlans, DeleteUsagePlan | +| **Authorizers** | CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer | +| **API Keys** | CreateApiKey, ImportApiKeys, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey | +| **Usage Plans** | CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan | | **Usage Plan Keys** | CreateUsagePlanKey, GetUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey | -| **Request Validators** | CreateRequestValidator, GetRequestValidator, GetRequestValidators, DeleteRequestValidator | -| **Models** | CreateModel, GetModel, GetModels, DeleteModel | -| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName | -| **Base Path Mappings** | CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping | +| **Request Validators** | CreateRequestValidator, GetRequestValidator, GetRequestValidators, UpdateRequestValidator, DeleteRequestValidator | +| **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel | +| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName | +| **Base Path Mappings** | CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, UpdateBasePathMapping, DeleteBasePathMapping | | **Account** | GetAccount, UpdateAccount | | **Tags** | TagResource, UntagResource, GetTags (ListTagsForResource) | ### API Key Behaviour Notes +#### `CreateApiKey` and `ImportApiKeys` share one route + +Both operations are `POST /apikeys`, and AWS tells them apart by the query string, not by +`Content-Type`: `ImportApiKeys` carries `?mode=import&format=csv` and a CSV body, `CreateApiKey` +carries no query parameters and a JSON body. The SDKs send `ImportApiKeys` with no `Content-Type` +header at all, so Floci accepts any media type on this route and dispatches on `mode`. + +The CSV header row is addressed by name, not position. AWS's own column set is +`Name,Key,Description,Enabled,UsagePlanIds`; a `Key` column is required, and a missing `Enabled` +column defaults to `true`. Duplicate key values are reported in the `warnings` array, and +`failonwarnings=true` turns those warnings into a `BadRequestException`. + #### `generateDistinctId` Controls whether the key's `id` and `value` fields are distinct. AWS's undocumented default behaviour is that they are **the same string** unless `generateDistinctId=true` is explicitly requested. @@ -97,11 +109,8 @@ immediately. These management-plane operations have no handler in v1. Calls will return `404` or an error: -- Deployment detail and lifecycle: `GetDeployment`, `UpdateDeployment`, `DeleteDeployment` -- Authorizer lifecycle: `UpdateAuthorizer`, `DeleteAuthorizer`, `TestInvokeAuthorizer` -- API key detail: `ImportApiKeys` -- Usage plan detail: `GetUsagePlan`, `UpdateUsagePlan` -- Model updates and templates: `UpdateModel`, `GetModelTemplate` +- Authorizer testing: `TestInvokeAuthorizer` +- Model templates: `GetModelTemplate` - Gateway Responses (the entire family: `PutGatewayResponse`, `GetGatewayResponse`, etc.) - Documentation parts and versions (the entire family, 10 operations) - VPC Links (5 operations) @@ -221,7 +230,7 @@ this default hostname with `404 Not Found`, matching AWS HTTP API behavior. | Category | Operations | |---|---| -| **APIs** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi | +| **APIs** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, DeleteCorsConfiguration | | **Routes** | CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute | | **Route Responses** | CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse | | **Integrations** | CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration | @@ -232,6 +241,7 @@ this default hostname with `404 Not Found`, matching AWS HTTP API behavior. | **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel | | **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName | | **API Mappings** | CreateApiMapping, GetApiMapping, GetApiMappings, DeleteApiMapping | +| **VPC Links** | CreateVpcLink, GetVpcLink, GetVpcLinks, DeleteVpcLink | | **Tags** | TagResource, UntagResource, GetTags | ### WebSocket Data-Plane {#websocket-data-plane} @@ -294,7 +304,7 @@ DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Disconn ### Not Implemented - `ReimportApi`, `ExportApi`, `UpdateDomainName`, `UpdateApiMapping` -- `CreateVpcLink`, `GetVpcLink`, `GetVpcLinks`, `UpdateVpcLink`, `DeleteVpcLink` +- `UpdateVpcLink` — the other four VPC Link operations are implemented; see the table above ### Examples diff --git a/docs/services/index.md b/docs/services/index.md index fcd51a7fda..d5639ea608 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -20,8 +20,8 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 | | [Lambda](lambda.md) | `/2015-03-31/functions/...` | REST JSON | 30 | | [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 | -| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 64 | -| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 48 + data-plane | +| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 79 | +| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane | | [IAM](iam.md) | `POST /` with `Action=` param | Query | 76 | | [STS](sts.md) | `POST /` with `Action=` param | Query | 7 | | [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 | diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java index 3353c2f706..9bc62c4ddc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -77,6 +78,49 @@ public class ApiGatewayController { this.objectMapper = objectMapper; } + private static final TypeReference>> PATCH_OPERATIONS = + new TypeReference<>() { }; + + /** + * The {@code op} enum, verbatim from the model. Wider than what any one handler implements on + * purpose: whether a handler supports {@code move} is its own business, but a value outside the + * enum never reaches a handler at all. + */ + private static final Set PATCH_OPS = Set.of("add", "remove", "replace", "move", "copy", "test"); + + /** + * Reads the {@code patchOperations} envelope shared by every PATCH operation. A body that is not + * JSON, an envelope that is not an array of string-valued operations, and a structured operation + * value are all client errors; AWS answers BadRequestException for each. + * + *

The {@code op} value is checked here too. Handlers each decide which operations they + * implement, and several skip anything they do not recognise — so without a boundary check an + * unmodelled {@code op} was answered 200 with the resource silently untouched. + */ + private List> parsePatchOperations(String body) { + List> patchOperations; + try { + patchOperations = + objectMapper.convertValue(objectMapper.readTree(body).path("patchOperations"), PATCH_OPERATIONS); + } catch (IOException | IllegalArgumentException e) { + throw new AwsException("BadRequestException", "Invalid patchOperations: " + e.getMessage(), 400); + } + if (patchOperations != null) { + for (Map operation : patchOperations) { + if (operation == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + String op = operation.get("op"); + if (op != null && !PATCH_OPS.contains(op)) { + throw new AwsException("BadRequestException", + "Invalid patch operation '" + op + "'. Must be one of: add, remove, replace, " + + "move, copy, test", 400); + } + } + } + return patchOperations; + } + // ──────────────────────────── Specific v1 Paths (ORDER MATTERS) ──────────────────────────── @GET @@ -109,6 +153,18 @@ public class ApiGatewayController { } } + @DELETE + @Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/responses/{statusCode}") + public Response deleteMethodResponse(@Context HttpHeaders headers, + @PathParam("apiId") String apiId, + @PathParam("resourceId") String resourceId, + @PathParam("httpMethod") String httpMethod, + @PathParam("statusCode") String statusCode) { + String region = regionResolver.resolveRegion(headers); + service.deleteMethodResponse(region, apiId, resourceId, httpMethod, statusCode); + return Response.noContent().build(); + } + @GET @Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{statusCode}") public Response getIntegrationResponse(@Context HttpHeaders headers, @@ -139,6 +195,32 @@ public class ApiGatewayController { } } + @DELETE + @Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{statusCode}") + public Response deleteIntegrationResponse(@Context HttpHeaders headers, + @PathParam("apiId") String apiId, + @PathParam("resourceId") String resourceId, + @PathParam("httpMethod") String httpMethod, + @PathParam("statusCode") String statusCode) { + String region = regionResolver.resolveRegion(headers); + service.deleteIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode); + return Response.noContent().build(); + } + + @PATCH + @Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{statusCode}") + public Response updateIntegrationResponse(@Context HttpHeaders headers, + @PathParam("apiId") String apiId, + @PathParam("resourceId") String resourceId, + @PathParam("httpMethod") String httpMethod, + @PathParam("statusCode") String statusCode, + String body) { + String region = regionResolver.resolveRegion(headers); + List> patchOperations = parsePatchOperations(body); + io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse integrationResponse = service.updateIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode, patchOperations); + return Response.ok(toIntegrationResponseNode(integrationResponse).toString()).type(MediaType.APPLICATION_JSON).build(); + } + @GET @Path("/restapis/{apiId}/authorizers/{authorizerId}") public Response getAuthorizer(@Context HttpHeaders headers, @@ -282,15 +364,9 @@ public class ApiGatewayController { @Path("/restapis/{apiId}") public Response updateRestApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) { String region = regionResolver.resolveRegion(headers); - try { - com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations"); - @SuppressWarnings("unchecked") - List> patchOperations = objectMapper.convertValue(node, List.class); - RestApi api = service.updateRestApi(region, apiId, patchOperations); - return Response.ok(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build(); - } catch (IOException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } + List> patchOperations = parsePatchOperations(body); + RestApi api = service.updateRestApi(region, apiId, patchOperations); + return Response.ok(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build(); } @DELETE @@ -330,15 +406,9 @@ public class ApiGatewayController { @PathParam("resourceId") String resourceId, String body) { String region = regionResolver.resolveRegion(headers); - try { - com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations"); - @SuppressWarnings("unchecked") - List> patchOperations = objectMapper.convertValue(node, List.class); - ApiGatewayResource resource = service.updateResource(region, apiId, resourceId, patchOperations); - return Response.ok(toResourceNode(resource).toString()).type(MediaType.APPLICATION_JSON).build(); - } catch (IOException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } + List> patchOperations = parsePatchOperations(body); + ApiGatewayResource resource = service.updateResource(region, apiId, resourceId, patchOperations); + return Response.ok(toResourceNode(resource).toString()).type(MediaType.APPLICATION_JSON).build(); } @POST @@ -365,7 +435,7 @@ public class ApiGatewayController { @PathParam("resourceId") String resourceId) { String region = regionResolver.resolveRegion(headers); service.deleteResource(region, apiId, resourceId); - return Response.noContent().build(); + return Response.accepted().build(); } // ──────────────────────────── Methods (v1) ──────────────────────────── @@ -406,15 +476,9 @@ public class ApiGatewayController { @PathParam("httpMethod") String httpMethod, String body) { String region = regionResolver.resolveRegion(headers); - try { - com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations"); - @SuppressWarnings("unchecked") - List> patchOperations = objectMapper.convertValue(node, List.class); - MethodConfig method = service.updateMethod(region, apiId, resourceId, httpMethod, patchOperations); - return Response.ok(toMethodNode(method).toString()).type(MediaType.APPLICATION_JSON).build(); - } catch (IOException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } + List> patchOperations = parsePatchOperations(body); + MethodConfig method = service.updateMethod(region, apiId, resourceId, httpMethod, patchOperations); + return Response.ok(toMethodNode(method).toString()).type(MediaType.APPLICATION_JSON).build(); } @DELETE @@ -466,15 +530,9 @@ public class ApiGatewayController { @PathParam("httpMethod") String httpMethod, String body) { String region = regionResolver.resolveRegion(headers); - try { - com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations"); - @SuppressWarnings("unchecked") - List> patchOperations = objectMapper.convertValue(node, List.class); - io.github.hectorvent.floci.services.apigateway.model.Integration integration = service.updateIntegration(region, apiId, resourceId, httpMethod, patchOperations); - return Response.ok(toIntegrationNode(integration).toString()).type(MediaType.APPLICATION_JSON).build(); - } catch (IOException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } + List> patchOperations = parsePatchOperations(body); + io.github.hectorvent.floci.services.apigateway.model.Integration integration = service.updateIntegration(region, apiId, resourceId, httpMethod, patchOperations); + return Response.ok(toIntegrationNode(integration).toString()).type(MediaType.APPLICATION_JSON).build(); } @DELETE @@ -528,6 +586,15 @@ public class ApiGatewayController { .type(MediaType.APPLICATION_JSON).build(); } + @PATCH + @Path("/restapis/{apiId}/deployments/{deploymentId}") + public Response updateDeployment(@Context HttpHeaders headers, @PathParam("apiId") String apiId, @PathParam("deploymentId") String deploymentId, String body) { + String region = regionResolver.resolveRegion(headers); + List> patchOperations = parsePatchOperations(body); + io.github.hectorvent.floci.services.apigateway.model.Deployment deployment = service.updateDeployment(region, apiId, deploymentId, patchOperations); + return Response.ok(toDeploymentNode(deployment).toString()).type(MediaType.APPLICATION_JSON).build(); + } + @DELETE @Path("/restapis/{apiId}/deployments/{deploymentId}") public Response deleteDeployment(@Context HttpHeaders headers, @@ -535,7 +602,7 @@ public class ApiGatewayController { @PathParam("deploymentId") String deploymentId) { String region = regionResolver.resolveRegion(headers); service.deleteDeployment(region, apiId, deploymentId); - return Response.noContent().build(); + return Response.accepted().build(); } @POST @@ -561,15 +628,9 @@ public class ApiGatewayController { @PathParam("stageName") String stageName, String body) { String region = regionResolver.resolveRegion(headers); - try { - com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations"); - @SuppressWarnings("unchecked") - List> patchOperations = objectMapper.convertValue(node, List.class); - io.github.hectorvent.floci.services.apigateway.model.Stage stage = service.updateStage(region, apiId, stageName, patchOperations); - return Response.ok(toStageNode(stage).toString()).type(MediaType.APPLICATION_JSON).build(); - } catch (IOException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } + List> patchOperations = parsePatchOperations(body); + io.github.hectorvent.floci.services.apigateway.model.Stage stage = service.updateStage(region, apiId, stageName, patchOperations); + return Response.ok(toStageNode(stage).toString()).type(MediaType.APPLICATION_JSON).build(); } @DELETE @@ -600,9 +661,43 @@ public class ApiGatewayController { } } + @PATCH + @Path("/restapis/{apiId}/authorizers/{authorizerId}") + public Response updateAuthorizer(@Context HttpHeaders headers, @PathParam("apiId") String apiId, @PathParam("authorizerId") String authorizerId, String body) { + String region = regionResolver.resolveRegion(headers); + List> patchOperations = parsePatchOperations(body); + io.github.hectorvent.floci.services.apigateway.model.Authorizer authorizer = service.updateAuthorizer(region, apiId, authorizerId, patchOperations); + return Response.ok(toAuthorizerNode(authorizer).toString()).type(MediaType.APPLICATION_JSON).build(); + } + + @DELETE + @Path("/restapis/{apiId}/authorizers/{authorizerId}") + public Response deleteAuthorizer(@Context HttpHeaders headers, @PathParam("apiId") String apiId, @PathParam("authorizerId") String authorizerId) { + String region = regionResolver.resolveRegion(headers); + service.deleteAuthorizer(region, apiId, authorizerId); + return Response.accepted().build(); + } + + /** + * CreateApiKey and ImportApiKeys share {@code POST /apikeys} and are told apart by the + * {@code mode} query parameter, never by media type: botocore sends ImportApiKeys with no + * Content-Type at all, so a media-type-keyed handler is unreachable from a real client. + */ @POST @Path("/apikeys") - public Response createApiKey(@Context HttpHeaders headers, String body) { + @Consumes(MediaType.WILDCARD) + public Response postApiKeys(@Context HttpHeaders headers, + @QueryParam("mode") String mode, + @QueryParam("format") String format, + @QueryParam("failonwarnings") boolean failOnWarnings, + String body) { + if (mode == null && format == null) { + return createApiKey(headers, body); + } + return importApiKeys(headers, mode, format, failOnWarnings, body); + } + + private Response createApiKey(HttpHeaders headers, String body) { String region = regionResolver.resolveRegion(headers); try { @SuppressWarnings("unchecked") @@ -614,6 +709,23 @@ public class ApiGatewayController { } } + private Response importApiKeys(HttpHeaders headers, String mode, String format, boolean failOnWarnings, String body) { + if (!"import".equals(mode) || !"csv".equals(format)) { + throw new AwsException("BadRequestException", "mode=import and format=csv are required", 400); + } + String region = regionResolver.resolveRegion(headers); + ApiGatewayService.ImportApiKeysResult result = service.importApiKeys(region, body); + if (failOnWarnings && !result.warnings().isEmpty()) { + throw new AwsException("BadRequestException", String.join("; ", result.warnings()), 400); + } + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode idArray = root.putArray("ids"); + result.ids().forEach(idArray::add); + ArrayNode warningArray = root.putArray("warnings"); + result.warnings().forEach(warningArray::add); + return Response.status(201).entity(root.toString()).type(MediaType.APPLICATION_JSON).build(); + } + @GET @Path("/apikeys") public Response getApiKeys(@Context HttpHeaders headers, @@ -651,15 +763,9 @@ public class ApiGatewayController { @PathParam("apiKeyId") String apiKeyId, String body) { String region = regionResolver.resolveRegion(headers); - try { - com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations"); - @SuppressWarnings("unchecked") - List> patchOperations = objectMapper.convertValue(node, List.class); - ApiKey key = service.updateApiKey(region, apiKeyId, patchOperations); - return Response.ok(toApiKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build(); - } catch (IOException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } + List> patchOperations = parsePatchOperations(body); + ApiKey key = service.updateApiKey(region, apiKeyId, patchOperations); + return Response.ok(toApiKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build(); } @DELETE @@ -696,6 +802,24 @@ public class ApiGatewayController { return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build(); } + @GET + @Path("/usageplans/{usagePlanId}") + public Response getUsagePlan(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId) { + String region = regionResolver.resolveRegion(headers); + UsagePlan plan = service.getUsagePlan(region, usagePlanId); + ObjectNode node = toUsagePlanNode(plan); + return Response.ok(node.toString()).type(MediaType.APPLICATION_JSON).build(); + } + + @PATCH + @Path("/usageplans/{usagePlanId}") + public Response updateUsagePlan(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId, String body) { + String region = regionResolver.resolveRegion(headers); + List> patchOperations = parsePatchOperations(body); + UsagePlan plan = service.updateUsagePlan(region, usagePlanId, patchOperations); + return Response.ok(toUsagePlanNode(plan).toString()).type(MediaType.APPLICATION_JSON).build(); + } + @DELETE @Path("/usageplans/{usagePlanId}") public Response deleteUsagePlan(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId) { @@ -780,6 +904,18 @@ public class ApiGatewayController { return Response.ok(toRequestValidatorNode(service.getRequestValidator(region, apiId, validatorId)).toString()).type(MediaType.APPLICATION_JSON).build(); } + @PATCH + @Path("/restapis/{apiId}/requestvalidators/{validatorId}") + public Response updateRequestValidator(@Context HttpHeaders headers, + @PathParam("apiId") String apiId, + @PathParam("validatorId") String validatorId, + String body) { + String region = regionResolver.resolveRegion(headers); + List> patchOperations = parsePatchOperations(body); + RequestValidator validator = service.updateRequestValidator(region, apiId, validatorId, patchOperations); + return Response.ok(toRequestValidatorNode(validator).toString()).type(MediaType.APPLICATION_JSON).build(); + } + @DELETE @Path("/restapis/{apiId}/requestvalidators/{validatorId}") public Response deleteRequestValidator(@Context HttpHeaders headers, @@ -826,6 +962,15 @@ public class ApiGatewayController { return Response.ok(toModelNode(service.getModel(region, apiId, modelName)).toString()).type(MediaType.APPLICATION_JSON).build(); } + @PATCH + @Path("/restapis/{apiId}/models/{modelName}") + public Response updateModel(@Context HttpHeaders headers, @PathParam("apiId") String apiId, @PathParam("modelName") String modelName, String body) { + String region = regionResolver.resolveRegion(headers); + List> patchOperations = parsePatchOperations(body); + io.github.hectorvent.floci.services.apigateway.model.Model model = service.updateModel(region, apiId, modelName, patchOperations); + return Response.ok(toModelNode(model).toString()).type(MediaType.APPLICATION_JSON).build(); + } + @DELETE @Path("/restapis/{apiId}/models/{modelName}") public Response deleteModel(@Context HttpHeaders headers, @@ -870,6 +1015,15 @@ public class ApiGatewayController { return Response.ok(toDomainNode(service.getDomainName(region, domainName)).toString()).type(MediaType.APPLICATION_JSON).build(); } + @PATCH + @Path("/domainnames/{domainName}") + public Response updateDomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName, String body) { + String region = regionResolver.resolveRegion(headers); + List> patchOperations = parsePatchOperations(body); + CustomDomain domain = service.updateDomainName(region, domainName, patchOperations); + return Response.ok(toDomainNode(domain).toString()).type(MediaType.APPLICATION_JSON).build(); + } + @DELETE @Path("/domainnames/{domainName}") public Response deleteDomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) { @@ -912,6 +1066,15 @@ public class ApiGatewayController { return Response.ok(toMappingNode(service.getBasePathMapping(region, domainName, basePath)).toString()).type(MediaType.APPLICATION_JSON).build(); } + @PATCH + @Path("/domainnames/{domainName}/basepathmappings/{basePath}") + public Response updateBasePathMapping(@Context HttpHeaders headers, @PathParam("domainName") String domainName, @PathParam("basePath") String basePath, String body) { + String region = regionResolver.resolveRegion(headers); + List> patchOperations = parsePatchOperations(body); + BasePathMapping mapping = service.updateBasePathMapping(region, domainName, basePath, patchOperations); + return Response.ok(toMappingNode(mapping).toString()).type(MediaType.APPLICATION_JSON).build(); + } + @DELETE @Path("/domainnames/{domainName}/basepathmappings/{basePath}") public Response deleteBasePathMapping(@Context HttpHeaders headers, @PathParam("domainName") String domainName, @PathParam("basePath") String basePath) { @@ -977,6 +1140,14 @@ public class ApiGatewayController { } } + @DELETE + @Path("/v2/apis/{apiId}/cors") + public Response deleteCorsConfiguration(@Context HttpHeaders headers, @PathParam("apiId") String apiId) { + String region = regionResolver.resolveRegion(headers); + v2Service.deleteCorsConfiguration(region, apiId); + return Response.noContent().build(); + } + @POST @Path("/v2/apis/{apiId}/routes") public Response createRoute(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) { @@ -1832,6 +2003,9 @@ public class ApiGatewayController { ObjectNode node = objectMapper.createObjectNode(); node.put("id", p.getId()); node.put("name", p.getName()); + if (p.getDescription() != null) { + node.put("description", p.getDescription()); + } if (p.getTags() != null && !p.getTags().isEmpty()) { ObjectNode tags = node.putObject("tags"); p.getTags().forEach(tags::put); @@ -2001,6 +2175,21 @@ public class ApiGatewayController { if (d.getCertificateArn() != null) node.put("certificateArn", d.getCertificateArn()); node.put("regionalDomainName", d.getRegionalDomainName()); node.put("regionalHostedZoneId", d.getRegionalHostedZoneId()); + if (d.getRegionalCertificateName() != null) { + node.put("regionalCertificateName", d.getRegionalCertificateName()); + } + if (d.getRegionalCertificateArn() != null) { + node.put("regionalCertificateArn", d.getRegionalCertificateArn()); + } + if (d.getDistributionDomainName() != null) { + node.put("distributionDomainName", d.getDistributionDomainName()); + } + if (d.getDistributionHostedZoneId() != null) { + node.put("distributionHostedZoneId", d.getDistributionHostedZoneId()); + } + if (d.getSecurityPolicy() != null) { + node.put("securityPolicy", d.getSecurityPolicy()); + } return node; } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java index 8d52067699..4f6dd39952 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java @@ -2,10 +2,12 @@ package io.github.hectorvent.floci.services.apigateway; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration; @@ -309,6 +311,7 @@ public class ApiGatewayService { getRestApi(region, apiId); ApiGatewayResource parent = getResource(region, apiId, parentId); String pathPart = (String) request.get("pathPart"); + assertNoSiblingPathCollision(region, apiId, parentId, pathPart, null); ApiGatewayResource resource = new ApiGatewayResource(); resource.setId(shortId(8)); @@ -385,6 +388,15 @@ public class ApiGatewayService { return mr; } + public void deleteMethodResponse(String region, String apiId, String resourceId, + String httpMethod, String statusCode) { + MethodConfig method = getMethod(region, apiId, resourceId, httpMethod); + if (method.getMethodResponses().remove(statusCode) == null) { + throw new AwsException("NotFoundException", "Invalid response status code specified", 404); + } + resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId)); + } + // ──────────────────────────── Integrations ──────────────────────────── public Integration putIntegration(String region, String apiId, String resourceId, String httpMethod, Map request) { @@ -463,6 +475,35 @@ public class ApiGatewayService { return ir; } + public void deleteIntegrationResponse(String region, String apiId, String resourceId, + String httpMethod, String statusCode) { + Integration integration = getIntegration(region, apiId, resourceId, httpMethod); + if (integration.getIntegrationResponses().remove(statusCode) == null) { + throw new AwsException("NotFoundException", "Invalid response status code specified", 404); + } + resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId)); + } + + public IntegrationResponse updateIntegrationResponse(String region, String apiId, String resourceId, String httpMethod, String statusCode, List> patchOperations) { + IntegrationResponse response = getIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode); + String selectionPattern = response.selectionPattern(); + if (patchOperations != null) { + for (Map patch : patchOperations) { + String op = patch.get("op"); + String path = patch.get("path"); + String value = patch.get("value"); + if (value == null || !("add".equals(op) || "replace".equals(op)) || !"/selectionPattern".equals(path)) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + selectionPattern = value; + } + } + IntegrationResponse newResponse = new IntegrationResponse(response.statusCode(), selectionPattern, response.responseParameters(), response.responseTemplates()); + getIntegration(region, apiId, resourceId, httpMethod).getIntegrationResponses().put(statusCode, newResponse); + resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId)); + return newResponse; + } + // ──────────────────────────── Deployments ──────────────────────────── public Deployment createDeployment(String region, String apiId, Map request) { @@ -525,6 +566,32 @@ public class ApiGatewayService { deploymentStore.delete(deploymentKey(region, apiId, deploymentId)); } + public Deployment updateDeployment(String region, String apiId, String deploymentId, List> patchOperations) { + Deployment existing = getDeployment(region, apiId, deploymentId); + if (patchOperations != null) { + String newDescription = existing.description(); + for (Map op : patchOperations) { + String operation = op.get("op"); + if (!"add".equals(operation) && !"replace".equals(operation)) { + throw new AwsException("BadRequestException", "Unsupported operation", 400); + } + String path = op.get("path"); + String value = op.get("value"); + if (path == null || value == null) { + throw new AwsException("BadRequestException", "Missing path or value", 400); + } + if (!"/description".equals(path)) { + throw new AwsException("BadRequestException", "Unsupported operation or path", 400); + } + newDescription = value; + } + Deployment updated = new Deployment(existing.id(), newDescription, existing.createdDate()); + deploymentStore.put(deploymentKey(region, apiId, deploymentId), updated); + return updated; + } + return existing; + } + // ──────────────────────────── Stages ──────────────────────────── public Stage createStage(String region, String apiId, Map request) { @@ -704,6 +771,58 @@ public class ApiGatewayService { authorizerStore.delete(authorizerKey(region, apiId, authorizerId)); } + public Authorizer updateAuthorizer(String region, String apiId, String authorizerId, List> patchOperations) { + Authorizer authorizer = getAuthorizer(region, apiId, authorizerId); + // The store hands back live objects, so every op is validated against pending values first and + // only applied once the whole patch is known to be good. + String newName = authorizer.getName(); + String newAuthorizerUri = authorizer.getAuthorizerUri(); + String newIdentitySource = authorizer.getIdentitySource(); + String newTtl = authorizer.getAuthorizerResultTtlInSeconds(); + if (patchOperations != null) { + for (Map op : patchOperations) { + if (op == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + String path = op.get("path"); + String value = op.get("value"); + String opType = op.get("op"); + if (!"add".equals(opType) && !"replace".equals(opType)) { + throw new AwsException("BadRequestException", "Invalid operation", 400); + } + if (path == null || value == null) { + throw new AwsException("BadRequestException", "Missing path or value", 400); + } + if ("/name".equals(path)) { + newName = value; + } else if ("/authorizerUri".equals(path)) { + newAuthorizerUri = value; + } else if ("/identitySource".equals(path)) { + newIdentitySource = value; + } else if ("/authorizerResultTtlInSeconds".equals(path)) { + // Validate before accepting: the store hands back live objects, and an unparseable TTL + // would break serialisation on every later GetAuthorizer/GetAuthorizers. + String ttl = value.trim(); + try { + Integer.parseInt(ttl); + } catch (NumberFormatException e) { + throw new AwsException("BadRequestException", + "authorizerResultTtlInSeconds must be an integer", 400); + } + newTtl = ttl; + } else { + throw new AwsException("BadRequestException", "Unsupported path: " + path, 400); + } + } + } + authorizer.setName(newName); + authorizer.setAuthorizerUri(newAuthorizerUri); + authorizer.setIdentitySource(newIdentitySource); + authorizer.setAuthorizerResultTtlInSeconds(newTtl); + authorizerStore.put(authorizerKey(region, apiId, authorizerId), authorizer); + return authorizer; + } + // ──────────────────────────── API Keys ──────────────────────────── public ApiKey createApiKey(String region, Map request) { @@ -741,6 +860,81 @@ public class ApiGatewayService { return apiKey; } + /** Result of ImportApiKeys: the generated key ids plus any non-fatal warnings raised for the CSV. */ + public record ImportApiKeysResult(List ids, List warnings) {} + + /** + * Imports API keys from the AWS CSV format. AWS ships a TitleCase header + * ({@code Name,Key,Description,Enabled,UsagePlanIds}); columns are addressed by name rather than + * position, and {@code value} is accepted as an alias for {@code Key}. + */ + public ImportApiKeysResult importApiKeys(String region, String csv) { + List> rows; + try { + rows = ApiKeyCsvParser.parse(csv); + } catch (IllegalArgumentException e) { + throw new AwsException("BadRequestException", "Invalid CSV: " + e.getMessage(), 400); + } + if (rows.isEmpty()) { + throw new AwsException("BadRequestException", "CSV body is empty", 400); + } + List header = rows.get(0); + Map columns = new HashMap<>(); + for (int i = 0; i < header.size(); i++) { + String column = header.get(i); + if (column == null) { + continue; + } + columns.putIfAbsent(column.trim().toLowerCase(java.util.Locale.ROOT), i); + } + int nameIndex = columns.getOrDefault("name", -1); + int keyIndex = columns.containsKey("key") ? columns.get("key") : columns.getOrDefault("value", -1); + if (nameIndex < 0 || keyIndex < 0) { + throw new AwsException("BadRequestException", + "CSV header must contain Name and Key columns", 400); + } + int descriptionIndex = columns.getOrDefault("description", -1); + int enabledIndex = columns.getOrDefault("enabled", -1); + + List ids = new ArrayList<>(); + List warnings = new ArrayList<>(); + Set seenValues = new HashSet<>(); + for (int i = 1; i < rows.size(); i++) { + List row = rows.get(i); + String name = csvCell(row, nameIndex); + String value = csvCell(row, keyIndex); + if (name.isEmpty() || value.isEmpty()) { + throw new AwsException("BadRequestException", "Invalid CSV row", 400); + } + if (!seenValues.add(value)) { + warnings.add("Duplicate key value on row " + i + " for API key '" + name + "'"); + } + String enabled = csvCell(row, enabledIndex); + Map request = new HashMap<>(); + request.put("name", name); + request.put("value", value); + // Absent or blank Enabled means enabled, matching the AWS default. + request.put("enabled", enabled.isEmpty() || Boolean.parseBoolean(enabled)); + // The CSV Key column is the key VALUE; AWS generates a separate id for the key itself. + request.put("generateDistinctId", true); + String description = csvCell(row, descriptionIndex); + if (!description.isEmpty()) { + request.put("description", description); + } + ids.add(createApiKey(region, request).getId()); + } + return new ImportApiKeysResult(ids, warnings); + } + + /** Reads one CSV cell by column index, tolerating rows shorter than the header. */ + private static String csvCell(List row, int index) { + if (index < 0 || index >= row.size()) { + return ""; + } + String value = row.get(index); + return value == null ? "" : value.trim(); + } + public ApiKey getApiKey(String region, String apiKeyId) { return findApiKey(region, apiKeyId) .orElseThrow(() -> new AwsException("NotFoundException", "Invalid API Key identifier specified", 404)); @@ -824,6 +1018,64 @@ public class ApiGatewayService { .orElseThrow(() -> new AwsException("NotFoundException", "Usage Plan not found", 404)); } + public UsagePlan updateUsagePlan(String region, String usagePlanId, List> patchOperations) { + UsagePlan plan = getUsagePlan(region, usagePlanId); + // The store hands back live objects, so every op is validated against pending values first and + // only applied once the whole patch is known to be good. + String newName = plan.getName(); + String newDescription = plan.getDescription(); + List newApiStages = new ArrayList<>(plan.getApiStages()); + if (patchOperations != null) { + for (Map op : patchOperations) { + if (op == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + String opType = op.get("op"); + String path = op.get("path"); + String value = op.get("value"); + if (path == null || value == null) { + throw new AwsException("BadRequestException", "Missing path or value", 400); + } + if ("/apiStages".equals(path)) { + // AWS models stage membership as add/remove of an "apiId:stage" pair. + if (!"add".equals(opType) && !"remove".equals(opType)) { + throw new AwsException("BadRequestException", "Invalid operation", 400); + } + String[] parts = value.split(":", 2); + if (parts.length != 2 || parts[0].isEmpty() || parts[1].isEmpty()) { + throw new AwsException("BadRequestException", + "apiStages value must be in the form apiId:stage", 400); + } + UsagePlan.ApiStage stage = new UsagePlan.ApiStage(parts[0], parts[1]); + if ("add".equals(opType)) { + if (!newApiStages.contains(stage)) { + newApiStages.add(stage); + } + } else { + newApiStages.remove(stage); + } + continue; + } + if (!"add".equals(opType) && !"replace".equals(opType)) { + throw new AwsException("BadRequestException", "Invalid operation", 400); + } + if ("/name".equals(path)) { + newName = value; + } else if ("/description".equals(path)) { + newDescription = value; + } else { + throw new AwsException("BadRequestException", "Unsupported path: " + path, 400); + } + } + } + plan.setName(newName); + plan.setDescription(newDescription); + plan.getApiStages().clear(); + plan.getApiStages().addAll(newApiStages); + usagePlanStore.put(usagePlanKey(region, usagePlanId), plan); + return plan; + } + public List getUsagePlans(String region) { String prefix = region + "::"; return usagePlanStore.scan(k -> k.startsWith(prefix)); @@ -900,6 +1152,58 @@ public class ApiGatewayService { requestValidatorStore.delete(requestValidatorKey(region, apiId, validatorId)); } + public RequestValidator updateRequestValidator(String region, String apiId, String validatorId, List> patchOperations) { + RequestValidator validator = getRequestValidator(region, apiId, validatorId); + + if (patchOperations == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + + // The store hands back live objects, so every op is validated against pending values first and + // only applied once the whole patch is known to be good. + String newName = validator.getName(); + boolean newValidateRequestBody = validator.isValidateRequestBody(); + boolean newValidateRequestParameters = validator.isValidateRequestParameters(); + + for (Map operation : patchOperations) { + if (operation == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + + String op = operation.get("op"); + String path = operation.get("path"); + String value = operation.get("value"); + + if (op == null || path == null || value == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + + if (!"add".equals(op) && !"replace".equals(op)) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + + switch (path) { + case "/name": + newName = value; + break; + case "/validateRequestBody": + newValidateRequestBody = Boolean.parseBoolean(value); + break; + case "/validateRequestParameters": + newValidateRequestParameters = Boolean.parseBoolean(value); + break; + default: + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + } + + validator.setName(newName); + validator.setValidateRequestBody(newValidateRequestBody); + validator.setValidateRequestParameters(newValidateRequestParameters); + requestValidatorStore.put(requestValidatorKey(region, apiId, validatorId), validator); + return validator; + } + // ──────────────────────────── Models ──────────────────────────── public Model createModel(String region, String apiId, Map request) { @@ -921,6 +1225,49 @@ public class ApiGatewayService { .orElseThrow(() -> new AwsException("NotFoundException", "Invalid model name specified", 404)); } + public Model updateModel(String region, String apiId, String modelName, List> patchOperations) { + Model model = getModel(region, apiId, modelName); + // The store hands back live objects, so every op is validated against pending values first and + // only applied once the whole patch is known to be good. + String newDescription = model.getDescription(); + String newSchema = model.getSchema(); + String newContentType = model.getContentType(); + if (patchOperations != null) { + for (Map op : patchOperations) { + if (op == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + String opType = op.get("op"); + String path = op.get("path"); + String value = op.get("value"); + if (!"add".equals(opType) && !"replace".equals(opType)) { + throw new AwsException("BadRequestException", "Invalid operation", 400); + } + if (path == null || value == null) { + throw new AwsException("BadRequestException", "Missing path or value", 400); + } + if ("/description".equals(path)) { + newDescription = value; + } else if ("/schema".equals(path)) { + newSchema = value; + } else if ("/contentType".equals(path)) { + newContentType = value; + } else if ("/name".equals(path)) { + // AWS treats the model name as an immutable identifier. + throw new AwsException("BadRequestException", + "Model name cannot be changed", 400); + } else { + throw new AwsException("BadRequestException", "Unsupported path: " + path, 400); + } + } + } + model.setDescription(newDescription); + model.setSchema(newSchema); + model.setContentType(newContentType); + modelStore.put(modelKey(region, apiId, modelName), model); + return model; + } + public List getModels(String region, String apiId) { getRestApi(region, apiId); String prefix = region + "::" + apiId + "::"; @@ -1003,6 +1350,75 @@ public class ApiGatewayService { basePathMappingStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(basePathMappingStore::delete); } + public CustomDomain updateDomainName(String region, String domainName, List> patchOperations) { + String domainKey = domainKey(region, domainName); + CustomDomain domain = getDomainName(region, domainName); + if (domain == null) { + throw new AwsException("BadRequestException", "Domain not found", 400); + } + if (patchOperations == null) { + domainStore.put(domainKey, domain); + return domain; + } + // The store hands back live objects, so every op is validated against pending values first and + // only applied once the whole patch is known to be good. + String newCertificateName = domain.getCertificateName(); + String newCertificateArn = domain.getCertificateArn(); + String newRegionalCertificateName = domain.getRegionalCertificateName(); + String newRegionalCertificateArn = domain.getRegionalCertificateArn(); + String newSecurityPolicy = domain.getSecurityPolicy(); + String newEndpointConfigurationType = domain.getEndpointConfigurationType(); + for (Map op : patchOperations) { + if (op == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + String operation = op.get("op"); + String path = op.get("path"); + String value = op.get("value"); + if (operation == null || path == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + if (!"add".equals(operation) && !"replace".equals(operation)) { + throw new AwsException("BadRequestException", "Unsupported operation: " + operation, 400); + } + if (value == null && ("add".equals(operation) || "replace".equals(operation))) { + // Check if value is required for the specific path + if ("/certificateName".equals(path) || "/certificateArn".equals(path) + || "/regionalCertificateName".equals(path) || "/regionalCertificateArn".equals(path) + || "/securityPolicy".equals(path) || "/endpointConfiguration/types/REGIONAL".equals(path)) { + throw new AwsException("BadRequestException", "Value is required for path: " + path, 400); + } + } + + if ("/certificateName".equals(path)) { + newCertificateName = value; + } else if ("/certificateArn".equals(path)) { + newCertificateArn = value; + } else if ("/regionalCertificateName".equals(path)) { + newRegionalCertificateName = value; + } else if ("/regionalCertificateArn".equals(path)) { + newRegionalCertificateArn = value; + } else if ("/securityPolicy".equals(path)) { + newSecurityPolicy = value; + } else if ("/endpointConfiguration/types/REGIONAL".equals(path)) { + if (!"REGIONAL".equals(value) && !"EDGE".equals(value)) { + throw new AwsException("BadRequestException", "Invalid value for endpoint type: " + value, 400); + } + newEndpointConfigurationType = value; + } else { + throw new AwsException("BadRequestException", "Unsupported path: " + path, 400); + } + } + domain.setCertificateName(newCertificateName); + domain.setCertificateArn(newCertificateArn); + domain.setRegionalCertificateName(newRegionalCertificateName); + domain.setRegionalCertificateArn(newRegionalCertificateArn); + domain.setSecurityPolicy(newSecurityPolicy); + domain.setEndpointConfigurationType(newEndpointConfigurationType); + domainStore.put(domainKey, domain); + return domain; + } + // ──────────────────────────── Base Path Mappings ──────────────────────────── /** @@ -1096,6 +1512,47 @@ public class ApiGatewayService { basePathMappingStore.delete(key); } + public BasePathMapping updateBasePathMapping(String region, String domainName, String basePath, List> patchOperations) { + String normalizedPath = (basePath == null || basePath.isEmpty() || "/".equals(basePath)) ? "(none)" : basePath; + + BasePathMapping mapping = getBasePathMapping(region, domainName, basePath); + + // The store hands back live objects, so every op is validated against pending values first and + // only applied once the whole patch is known to be good. + String newRestApiId = mapping.getRestApiId(); + String newStage = mapping.getStage(); + if (patchOperations != null) { + for (Map op : patchOperations) { + if (op == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + String path = op.get("path"); + String value = op.get("value"); + + if (path == null || value == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + + if (!"add".equals(op.get("op")) && !"replace".equals(op.get("op"))) { + throw new AwsException("BadRequestException", "Unsupported operation: " + op.get("op"), 400); + } + + if ("/restApiId".equals(path)) { + newRestApiId = value; + } else if ("/stage".equals(path)) { + newStage = value; + } else { + throw new AwsException("BadRequestException", "Unsupported path: " + path, 400); + } + } + } + + mapping.setRestApiId(newRestApiId); + mapping.setStage(newStage); + basePathMappingStore.put(mappingKey(region, domainName, normalizedPath), mapping); + return mapping; + } + // ──────────────────────────── Custom Domain Resolution ──────────────────────────── /** @@ -1199,12 +1656,138 @@ public class ApiGatewayService { } public ApiGatewayResource updateResource(String region, String apiId, String resourceId, List> patchOperations) { + if (patchOperations == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } ApiGatewayResource resource = getResource(region, apiId, resourceId); - // Minimal update support + // The store hands back live objects, so every op is validated against pending values first and + // only applied once the whole patch (including the sibling-collision check) is known to be good. + String newParentId = resource.getParentId(); + String newPathPart = resource.getPathPart(); + for (Map op : patchOperations) { + if (op == null || !op.containsKey("op") || !op.containsKey("path") || !op.containsKey("value")) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + String opStr = op.get("op"); + String path = op.get("path"); + String value = op.get("value"); + if (!"replace".equals(opStr)) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + if (path == null || path.isEmpty()) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + if ("/pathPart".equals(path)) { + if (value == null || value.isEmpty()) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + newPathPart = value; + } else if ("/parentId".equals(path)) { + if (value == null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + if (resourceId.equals(value)) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + if (value.isEmpty()) { + if (resource.getParentId() != null) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + } else { + try { + getResource(region, apiId, value); + } catch (AwsException e) { + // AWS reports an unknown target parent as a bad request on the patch, not as a + // 404 about the resource being patched. + throw new AwsException("BadRequestException", "Invalid parentId: " + value, 400); + } + if (isDescendant(region, apiId, resourceId, value)) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + newParentId = value; + } + } else { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + } + assertNoSiblingPathCollision(region, apiId, newParentId, newPathPart, resourceId); + resource.setParentId(newParentId); + resource.setPathPart(newPathPart); + recomputePaths(region, apiId); resourceStore.put(resourceKey(region, apiId, resourceId), resource); return resource; } + /** + * AWS rejects two children of the same parent sharing a pathPart, because the resulting resources + * would have identical paths and request routing would become order-dependent. + */ + private void assertNoSiblingPathCollision(String region, String apiId, String parentId, String pathPart, String selfId) { + if (parentId == null || pathPart == null || pathPart.isEmpty()) { + return; + } + for (ApiGatewayResource sibling : getResources(region, apiId)) { + if (selfId != null && selfId.equals(sibling.getId())) { + continue; + } + if (!parentId.equals(sibling.getParentId())) { + continue; + } + if (pathPart.equals(sibling.getPathPart())) { + throw new AwsException("ConflictException", + "Another resource with the same parent already has this name: " + pathPart, 409); + } + } + } + + private boolean isDescendant(String region, String apiId, String resourceId, String parentId) { + String currentId = parentId; + while (currentId != null) { + if (currentId.equals(resourceId)) { + return true; + } + ApiGatewayResource parent = getResource(region, apiId, currentId); + if (parent == null || parent.getParentId() == null) { + break; + } + currentId = parent.getParentId(); + } + return false; + } + + private void recomputePaths(String region, String apiId) { + List allResources = getResources(region, apiId); + Map resourceMap = new java.util.HashMap<>(); + for (ApiGatewayResource r : allResources) { + resourceMap.put(r.getId(), r); + } + boolean changed = true; + while (changed) { + changed = false; + for (ApiGatewayResource r : allResources) { + if (r.getParentId() == null) { + if (!"/".equals(r.getPath())) { + r.setPath("/"); + changed = true; + } + } else { + ApiGatewayResource parent = resourceMap.get(r.getParentId()); + if (parent != null) { + String newPath = parent.getPath().equals("/") ? "/" + r.getPathPart() + : parent.getPath() + "/" + r.getPathPart(); + if (!newPath.equals(r.getPath())) { + r.setPath(newPath); + changed = true; + } + } + } + } + } + for (ApiGatewayResource r : allResources) { + resourceStore.put(resourceKey(region, apiId, r.getId()), r); + } + } + public MethodConfig updateMethod(String region, String apiId, String resourceId, String httpMethod, List> patchOperations) { MethodConfig method = getMethod(region, apiId, resourceId, httpMethod); if (patchOperations != null) { @@ -1224,13 +1807,43 @@ public class ApiGatewayService { Integration integration = getIntegration(region, apiId, resourceId, httpMethod); if (patchOperations != null) { for (Map op : patchOperations) { - if (!"replace" .equals(op.get("op"))) continue; - String path = op.getOrDefault("path", ""); + String opType = op.get("op"); + if (!"add".equals(opType) && !"replace".equals(opType)) { + throw new AwsException("BadRequestException", "Invalid operation", 400); + } + String path = op.get("path"); + String value = op.get("value"); + if (path == null || value == null) { + throw new AwsException("BadRequestException", "Path and value must be non-null", 400); + } + switch (path) { + case "/type": + case "/httpMethod": + case "/uri": + case "/passthroughBehavior": + break; + default: + throw new AwsException("BadRequestException", "Unsupported path: " + path, 400); + } + } + for (Map op : patchOperations) { + String path = op.get("path"); String value = op.get("value"); switch (path) { - case "/type" -> integration.setType(value); - case "/httpMethod" -> integration.setHttpMethod(value); - case "/uri" -> integration.setUri(value); + case "/type": + integration.setType(value); + break; + case "/httpMethod": + integration.setHttpMethod(value); + break; + case "/uri": + integration.setUri(value); + break; + case "/passthroughBehavior": + integration.setPassthroughBehavior(value); + break; + default: + throw new IllegalStateException("Unreachable: validated above"); } } } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiKeyCsvParser.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiKeyCsvParser.java new file mode 100644 index 0000000000..912710906d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiKeyCsvParser.java @@ -0,0 +1,62 @@ +package io.github.hectorvent.floci.services.apigateway; + +import java.util.ArrayList; +import java.util.List; + +public final class ApiKeyCsvParser { + private ApiKeyCsvParser() {} + + public static List> parse(String csv) { + if (csv == null || csv.isEmpty()) { + return new ArrayList<>(); + } + List> rows = new ArrayList<>(); + List row = new ArrayList<>(); + StringBuilder field = new StringBuilder(); + boolean inQuote = false; + int len = csv.length(); + for (int i = 0; i < len; i++) { + char c = csv.charAt(i); + if (inQuote) { + if (c == '"') { + if (i + 1 < len && csv.charAt(i + 1) == '"') { + field.append('"'); + i++; + } else { + inQuote = false; + } + } else { + field.append(c); + } + } else { + if (c == '"') { + inQuote = true; + } else if (c == ',') { + row.add(field.toString()); + field.setLength(0); + } else if (c == '\r' && i + 1 < len && csv.charAt(i + 1) == '\n') { + row.add(field.toString()); + rows.add(row); + row = new ArrayList<>(); + field.setLength(0); + i++; + } else if (c == '\n') { + row.add(field.toString()); + rows.add(row); + row = new ArrayList<>(); + field.setLength(0); + } else { + field.append(c); + } + } + } + if (inQuote) { + throw new IllegalArgumentException("Unclosed quote"); + } + if (!field.isEmpty() || !row.isEmpty()) { + row.add(field.toString()); + rows.add(row); + } + return rows; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java index cf00436652..43eef52e73 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java @@ -230,6 +230,13 @@ public class ApiGatewayV2Service { return api; } + /** Removes the optional HTTP API CORS configuration. */ + public void deleteCorsConfiguration(String region, String apiId) { + Api api = getApi(region, apiId); + api.setCorsConfiguration(null); + apiStore.put(apiKey(region, apiId), api); + } + private static boolean booleanValue(Object value) { return value != null && Boolean.parseBoolean(String.valueOf(value)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyIntegrationTest.java index 0d474000b1..6b21f473b0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyIntegrationTest.java @@ -234,4 +234,12 @@ class ApiGatewayApiKeyIntegrationTest { .body("id", equalTo(keyId)) .body("value", not(equalTo(keyId))); } + @Test @Order(15) + void getDeletedApiKeyNotFound() { + given() + .when().get("/apikeys/" + apiKeyId) + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteAuthorizerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteAuthorizerIntegrationTest.java new file mode 100644 index 0000000000..1cc52c1864 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteAuthorizerIntegrationTest.java @@ -0,0 +1,63 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; + +@QuarkusTest +class ApiGatewayDeleteAuthorizerIntegrationTest { + + @Test + void testDeleteAuthorizerFlow() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"delete-authorizer-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String authorizerId = given() + .contentType("application/json") + .body("{\"name\":\"to-delete\",\"type\":\"TOKEN\",\"authorizerUri\":\"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:any/invocations\"}") + .when() + .post("/restapis/" + apiId + "/authorizers") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .when() + .get("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(200) + .body("id", equalTo(authorizerId)) + .body("name", equalTo("to-delete")); + + given() + .when() + .get("/restapis/" + apiId + "/authorizers") + .then() + .statusCode(200) + .body("item.id", hasItem(authorizerId)); + + given() + .when() + .delete("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(202); + + given() + .when() + .get("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteIntegrationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteIntegrationIntegrationTest.java new file mode 100644 index 0000000000..2ec85623bd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteIntegrationIntegrationTest.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +public class ApiGatewayDeleteIntegrationIntegrationTest { + + @Test + public void testDeleteIntegration() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"delete-integration-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String rootId = given() + .pathParam("apiId", apiId) + .when() + .get("/restapis/{apiId}/resources") + .then() + .statusCode(200) + .extract() + .path("item[0].id"); + + String resourceId = given() + .pathParam("apiId", apiId) + .pathParam("parentId", rootId) + .contentType("application/json") + .body("{\"pathPart\":\"work\"}") + .when() + .post("/restapis/{apiId}/resources/{parentId}") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", resourceId) + .contentType("application/json") + .body("{\"authorizationType\":\"NONE\"}") + .when() + .put("/restapis/{apiId}/resources/{resourceId}/methods/GET") + .then() + .statusCode(201); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", resourceId) + .contentType("application/json") + .body("{\"type\":\"MOCK\"}") + .when() + .put("/restapis/{apiId}/resources/{resourceId}/methods/GET/integration") + .then() + .statusCode(201); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", resourceId) + .when() + .delete("/restapis/{apiId}/resources/{resourceId}/methods/GET/integration") + .then() + .statusCode(204); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", resourceId) + .when() + .get("/restapis/{apiId}/resources/{resourceId}/methods/GET/integration") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteIntegrationResponseIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteIntegrationResponseIntegrationTest.java new file mode 100644 index 0000000000..afbf99f37c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteIntegrationResponseIntegrationTest.java @@ -0,0 +1,72 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +@TestHTTPEndpoint(ApiGatewayController.class) +class ApiGatewayDeleteIntegrationResponseIntegrationTest { + + @Test + void testDeleteIntegrationResponse() { + String apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"delete-integration-response-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String resourceId = given() + .when() + .get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + .extract() + .path("item[0].id"); + + given() + .contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when() + .put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"type\":\"MOCK\"}") + .when() + .put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"before\"}") + .when() + .put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200") + .then() + .statusCode(201); + + given() + .when() + .delete("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200") + .then() + .statusCode(204); + + given() + .when() + .get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteMethodIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteMethodIntegrationTest.java new file mode 100644 index 0000000000..c10d81b714 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteMethodIntegrationTest.java @@ -0,0 +1,57 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static io.restassured.http.ContentType.JSON; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +@TestHTTPEndpoint(ApiGatewayController.class) +class ApiGatewayDeleteMethodIntegrationTest { + + @Test + void testDeleteMethodWorkflow() { + String apiId = given() + .contentType(JSON) + .body("{\"name\":\"delete-method-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String resourceId = given() + .pathParam("apiId", apiId) + .when() + .get("/restapis/{apiId}/resources") + .then() + .statusCode(200) + .extract() + .path("item[0].id"); + + given() + .contentType(JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when() + .put("/restapis/{apiId}/resources/{resourceId}/methods/GET", apiId, resourceId) + .then() + .statusCode(201); + + given() + .when() + .delete("/restapis/{apiId}/resources/{resourceId}/methods/GET", apiId, resourceId) + .then() + .statusCode(202); + + given() + .when() + .get("/restapis/{apiId}/resources/{resourceId}/methods/GET", apiId, resourceId) + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteMethodResponseIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteMethodResponseIntegrationTest.java new file mode 100644 index 0000000000..51001b837d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteMethodResponseIntegrationTest.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +@TestHTTPEndpoint(ApiGatewayController.class) +class ApiGatewayDeleteMethodResponseIntegrationTest { + + @Test + void testDeleteMethodResponse() { + String apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"delete-method-response-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String resourceId = given() + .when() + .get("/restapis/{apiId}/resources", apiId) + .then() + .statusCode(200) + .extract() + .path("item[0].id"); + + given() + .contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when() + .put("/restapis/{apiId}/resources/{resourceId}/methods/GET", apiId, resourceId) + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{}") + .when() + .put("/restapis/{apiId}/resources/{resourceId}/methods/GET/responses/200", apiId, resourceId) + .then() + .statusCode(201); + + given() + .when() + .delete("/restapis/{apiId}/resources/{resourceId}/methods/GET/responses/200", apiId, resourceId) + .then() + .statusCode(204); + + given() + .when() + .get("/restapis/{apiId}/resources/{resourceId}/methods/GET/responses/200", apiId, resourceId) + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteModelIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteModelIntegrationTest.java new file mode 100644 index 0000000000..18c3a3d49b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteModelIntegrationTest.java @@ -0,0 +1,48 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +@TestHTTPEndpoint(ApiGatewayController.class) +class ApiGatewayDeleteModelIntegrationTest { + + @Test + void testDeleteModelFlow() { + String apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"delete-model-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"name\":\"DeleteMe\",\"schema\":\"{}\"}") + .when() + .post("/restapis/" + apiId + "/models") + .then() + .statusCode(201); + + given() + .when() + .delete("/restapis/" + apiId + "/models/DeleteMe") + .then() + .statusCode(202); + + given() + .when() + .get("/restapis/" + apiId + "/models/DeleteMe") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteRequestValidatorIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteRequestValidatorIntegrationTest.java new file mode 100644 index 0000000000..057bb778fb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteRequestValidatorIntegrationTest.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +@TestHTTPEndpoint(ApiGatewayController.class) +class ApiGatewayDeleteRequestValidatorIntegrationTest { + + @Test + void testDeleteRequestValidator() { + String apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"validator-delete-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String validatorId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"DeleteValidator\",\"validateRequestBody\":true,\"validateRequestParameters\":false}") + .when() + .post("/restapis/" + apiId + "/requestvalidators") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .when() + .delete("/restapis/" + apiId + "/requestvalidators/" + validatorId) + .then() + .statusCode(202); + + given() + .when() + .get("/restapis/" + apiId + "/requestvalidators/" + validatorId) + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteResourceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteResourceIntegrationTest.java new file mode 100644 index 0000000000..ad9d3f8ebe --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDeleteResourceIntegrationTest.java @@ -0,0 +1,61 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayDeleteResourceIntegrationTest { + + @Test + void testDeleteResource() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"delete-resource-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String rootId = given() + .when() + .get("/restapis/{apiId}/resources", apiId) + .then() + .statusCode(200) + .extract() + .path("item[0].id"); + + String resourceId = given() + .contentType("application/json") + .pathParam("apiId", apiId) + .pathParam("parentId", rootId) + .body("{\"pathPart\":\"gone\"}") + .when() + .post("/restapis/{apiId}/resources/{parentId}") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", resourceId) + .when() + .delete("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(202); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", resourceId) + .when() + .get("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGetTagsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGetTagsIntegrationTest.java new file mode 100644 index 0000000000..28ecd4292d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGetTagsIntegrationTest.java @@ -0,0 +1,43 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayGetTagsIntegrationTest { + + @Test + void testGetTags() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"get-tags-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String resourceArn = "arn:aws:apigateway:us-east-1::/restapis/" + apiId; + + given() + .pathParam("resourceArn", resourceArn) + .contentType("application/json") + .body("{\"tags\":{\"owner\":\"network\"}}") + .when() + .put("/tags/{resourceArn}") + .then() + .statusCode(204); + + given() + .pathParam("resourceArn", resourceArn) + .when() + .get("/tags/{resourceArn}") + .then() + .statusCode(200) + .body("tags.owner", equalTo("network")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayImportApiKeysIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayImportApiKeysIntegrationTest.java new file mode 100644 index 0000000000..8e5bb9039b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayImportApiKeysIntegrationTest.java @@ -0,0 +1,190 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class ApiGatewayImportApiKeysIntegrationTest { + + /** + * Botocore sends ImportApiKeys with no Content-Type header at all — only {@code Accept: + * application/json} — so the handler has to be reachable without one. RestAssured stamps a + * default Content-Type on any request carrying a body, so this case uses a raw client. + */ + @Test + void testImportApiKeysWithoutContentTypeHeader() throws Exception { + HttpResponse response = HttpClient.newHttpClient().send( + HttpRequest.newBuilder() + .uri(URI.create("http://localhost:" + RestAssured.port + + "/apikeys?mode=import&format=csv&failonwarnings=false")) + .header("Accept", "application/json") + .POST(HttpRequest.BodyPublishers.ofString("Name,Key\nno-content-type-key,no-content-type-secret\n")) + .build(), + HttpResponse.BodyHandlers.ofString()); + + assertEquals(201, response.statusCode(), "ImportApiKeys must dispatch without a Content-Type: " + response.body()); + assertTrue(response.body().contains("\"ids\""), response.body()); + } + + @Test + void testImportApiKeys() { + String importedId = given() + .contentType("text/csv") + .body("name,value,enabled\nimported-key,secret-value,true\n") + .when() + .post("/apikeys?mode=import&format=csv&failonwarnings=false") + .then() + .statusCode(201) + .body("ids", hasSize(1)) + .extract().path("ids[0]"); + + given() + .pathParam("importedId", importedId) + .when() + .get("/apikeys/{importedId}?includeValue=true") + .then() + .statusCode(200) + .body("name", org.hamcrest.Matchers.equalTo("imported-key")) + .body("value", org.hamcrest.Matchers.equalTo("secret-value")) + .body("enabled", org.hamcrest.Matchers.equalTo(true)); + } + + /** AWS ImportApiKeys uses the TitleCase header {@code Name,Key,Description,Enabled,UsagePlanIds}. */ + @Test + void testImportApiKeysAcceptsAwsNativeHeader() { + String importedId = given() + .contentType("text/csv") + .body("Name,Key,Description,Enabled,UsagePlanIds\n" + + "aws-format-key,aws-format-secret-value,a description,true,\n") + .when() + .post("/apikeys?mode=import&format=csv&failonwarnings=false") + .then() + .statusCode(201) + .body("ids", hasSize(1)) + .extract().path("ids[0]"); + + given() + .pathParam("importedId", importedId) + .when() + .get("/apikeys/{importedId}?includeValue=true") + .then() + .statusCode(200) + .body("name", equalTo("aws-format-key")) + .body("value", equalTo("aws-format-secret-value")) + .body("description", equalTo("a description")) + .body("enabled", equalTo(true)); + } + + /** Columns are addressed by name, not by position, and a missing Enabled column defaults to true. */ + @Test + void testImportApiKeysReadsColumnsByNameAndDefaultsEnabled() { + String importedId = given() + .contentType("text/csv") + .body("Key,UsagePlanIds,Name\nreordered-secret,,reordered-key\n") + .when() + .post("/apikeys?mode=import&format=csv&failonwarnings=false") + .then() + .statusCode(201) + .body("ids", hasSize(1)) + .extract().path("ids[0]"); + + given() + .pathParam("importedId", importedId) + .when() + .get("/apikeys/{importedId}?includeValue=true") + .then() + .statusCode(200) + .body("name", equalTo("reordered-key")) + .body("value", equalTo("reordered-secret")) + .body("enabled", equalTo(true)); + } + + /** The CSV Key column is the key VALUE; AWS generates a distinct id, so it must not be reused as the id. */ + @Test + void testImportedKeyIdIsDistinctFromKeyValue() { + String importedId = given() + .contentType("text/csv") + .body("Name,Key\ndistinct-id-key,distinct-id-secret-value\n") + .when() + .post("/apikeys?mode=import&format=csv&failonwarnings=false") + .then() + .statusCode(201) + .extract().path("ids[0]"); + + org.junit.jupiter.api.Assertions.assertNotEquals("distinct-id-secret-value", importedId); + + given() + .pathParam("importedId", importedId) + .when() + .get("/apikeys/{importedId}?includeValue=true") + .then() + .statusCode(200) + .body("id", not(equalTo("distinct-id-secret-value"))) + .body("value", equalTo("distinct-id-secret-value")); + } + + @Test + void testDuplicateKeyValueEmitsWarning() { + given() + .contentType("text/csv") + .body("Name,Key\nwarn-a,duplicate-secret\nwarn-b,duplicate-secret\n") + .when() + .post("/apikeys?mode=import&format=csv&failonwarnings=false") + .then() + .statusCode(201) + .body("ids", hasSize(2)) + .body("warnings", hasSize(1)); + } + + @Test + void testDuplicateKeyValueFailsWhenFailOnWarnings() { + given() + .contentType("text/csv") + .body("Name,Key\nfail-a,fail-duplicate-secret\nfail-b,fail-duplicate-secret\n") + .when() + .post("/apikeys?mode=import&format=csv&failonwarnings=true") + .then() + .statusCode(400); + } + + @Test + void testHeaderWithoutKeyColumnIsRejected() { + given() + .contentType("text/csv") + .body("Name,Description\nno-key,nope\n") + .when() + .post("/apikeys?mode=import&format=csv&failonwarnings=false") + .then() + .statusCode(400); + } + + /** + * A malformed CSV (unterminated quote) fails inside {@code ApiKeyCsvParser.parse} with an + * {@code IllegalArgumentException}, which no exception mapper handles — only {@code AwsException} + * is mapped. The request must still answer the modelled 400, not a 500 that escapes the AWS + * error boundary. + */ + @Test + void testMalformedCsvWithUnterminatedQuoteIsRejectedAsBadRequest() { + given() + .contentType("text/csv") + .body("Name,Key\n\"unterminated,secret-value\n") + .when() + .post("/apikeys?mode=import&format=csv&failonwarnings=false") + .then() + .statusCode(400); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationTest.java index 3e8ca90e57..979db070bf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationTest.java @@ -340,7 +340,7 @@ class ApiGatewayIntegrationTest { given() .when().delete("/restapis/" + apiId + "/deployments/" + deploymentId) .then() - .statusCode(204); + .statusCode(202); given() .when().get("/restapis/" + apiId + "/deployments/" + deploymentId) @@ -354,7 +354,7 @@ class ApiGatewayIntegrationTest { given() .when().delete("/restapis/" + apiId + "/resources/" + resourceId) .then() - .statusCode(204); + .statusCode(202); } @Test @Order(29) diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPatchOperationsBoundaryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPatchOperationsBoundaryIntegrationTest.java new file mode 100644 index 0000000000..00eced35a5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPatchOperationsBoundaryIntegrationTest.java @@ -0,0 +1,223 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * A malformed {@code patchOperations} envelope is a client error: AWS answers BadRequestException, + * never a server fault. Each case below is a distinct shape that fails at a different point of the + * shared boundary parse. + */ +@QuarkusTest +class ApiGatewayPatchOperationsBoundaryIntegrationTest { + + private String createApi(String name) { + return given() + .contentType(ContentType.JSON) + .body("{\"name\":\"" + name + "\"}") + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + } + + private String createModel(String apiId, String modelName) { + return given() + .contentType(ContentType.JSON) + .body("{\"name\":\"" + modelName + "\",\"description\":\"old\",\"contentType\":\"application/json\",\"schema\":\"{}\"}") + .post("/restapis/" + apiId + "/models") + .then() + .statusCode(201) + .extract() + .path("name"); + } + + private void patchModelExpecting(String bodyJson, int expectedStatus) { + String apiId = createApi("patch-boundary-" + Integer.toHexString(bodyJson.hashCode())); + String modelName = createModel(apiId, "BoundaryModel"); + given() + .contentType(ContentType.JSON) + .body(bodyJson) + .patch("/restapis/" + apiId + "/models/" + modelName) + .then() + .statusCode(expectedStatus); + } + + /** A scalar where an array belongs. */ + @Test + void testPatchOperationsAsStringIsRejected() { + patchModelExpecting("{\"patchOperations\":\"oops\"}", 400); + } + + /** A bare operation object rather than a one-element array. */ + @Test + void testPatchOperationsAsObjectIsRejected() { + patchModelExpecting("{\"patchOperations\":{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"new\"}}", 400); + } + + /** A structured {@code value} cannot be a PatchOperation value, which AWS models as a string. */ + @Test + void testStructuredPatchValueIsRejected() { + patchModelExpecting("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/description\",\"value\":{\"nested\":1}}]}", 400); + } + + /** Body that is not JSON at all still fails at the boundary, not in the service. */ + @Test + void testNonJsonBodyIsRejected() { + patchModelExpecting("not json at all", 400); + } + + /** A JSON scalar is coerced to the string PatchOperation values are modelled as. */ + @Test + void testNumericPatchValueIsCoercedToString() { + String apiId = createApi("patch-boundary-numeric"); + String modelName = createModel(apiId, "NumericModel"); + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/description\",\"value\":5}]}") + .patch("/restapis/" + apiId + "/models/" + modelName) + .then() + .statusCode(200) + .body("description", equalTo("5")); + } + + /** UpdateRestApi predates this branch and shares the same boundary parse. */ + @Test + void testMalformedEnvelopeOnRestApiIsRejected() { + String apiId = createApi("patch-boundary-restapi"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":\"oops\"}") + .patch("/restapis/" + apiId) + .then() + .statusCode(400); + } + + /** UpdateApiKey likewise, including the structured-value shape that used to reach the service. */ + @Test + void testStructuredPatchValueOnApiKeyIsRejected() { + String keyId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"patch-boundary-key\",\"enabled\":true}") + .post("/apikeys") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/description\",\"value\":{\"nested\":1}}]}") + .patch("/apikeys/" + keyId) + .then() + .statusCode(400); + } + + /** + * A {@code null} element inside the patchOperations array must be rejected at the boundary. Every + * downstream handler assumes each element is a map and calls {@code .get("op")} on it directly, so + * letting a null through turns a client error into a 500 instead of the modelled 400. + */ + @Test + void testNullElementInPatchOperationsArrayIsRejected() { + patchModelExpecting("{\"patchOperations\":[null]}", 400); + } + + /** + * UpdateRestApi has no per-handler null guard of its own, unlike some of the newer handlers — this + * is the case that would 500 (NPE on {@code op.get("op")}) without the shared boundary rejecting + * the null element before it ever reaches the service layer. + */ + @Test + void testNullElementInPatchOperationsArrayIsRejectedOnRestApi() { + String apiId = createApi("patch-boundary-restapi-null-op"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[null]}") + .patch("/restapis/" + apiId) + .then() + .statusCode(400); + } + + /** The same boundary contract holds on a second handler, proving the parse is shared. */ + @Test + void testMalformedEnvelopeOnRequestValidatorIsRejected() { + String apiId = createApi("patch-boundary-validator"); + String validatorId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"before\",\"validateRequestBody\":false,\"validateRequestParameters\":true}") + .post("/restapis/" + apiId + "/requestvalidators") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":\"oops\"}") + .patch("/restapis/" + apiId + "/requestvalidators/" + validatorId) + .then() + .statusCode(400); + } + + // ── op (botocore: enum add|remove|replace|move|copy|test) ── + + private String createApiKey(String name) { + return given() + .contentType(ContentType.JSON) + .body("{\"name\":\"" + name + "\",\"enabled\":true}") + .post("/apikeys") + .then() + .statusCode(201) + .extract() + .path("id"); + } + + /** + * UpdateApiKey skips any operation it does not recognise, so an unmodelled op used to answer + * 200 with the resource untouched — success for a request AWS rejects outright. + */ + @Test + void testUnmodelledOpOnApiKeyIsRejected() { + String keyId = createApiKey("patch-boundary-op-enum"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[{\"op\":\"frobnicate\",\"path\":\"/name\",\"value\":\"after\"}]}") + .patch("/apikeys/" + keyId) + .then() + .statusCode(400); + + given() + .get("/apikeys/" + keyId) + .then() + .statusCode(200) + .body("name", equalTo("patch-boundary-op-enum")); + } + + @Test + void testUnmodelledOpOnModelIsRejected() { + patchModelExpecting("{\"patchOperations\":[{\"op\":\"REPLACE\",\"path\":\"/description\",\"value\":\"new\"}]}", 400); + } + + /** A modelled op the handler does support must still go through. */ + @Test + void testModelledOpOnApiKeyIsAccepted() { + String keyId = createApiKey("patch-boundary-op-modelled"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"after\"}]}") + .patch("/apikeys/" + keyId) + .then() + .statusCode(200) + .body("name", equalTo("after")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagResourceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagResourceIntegrationTest.java new file mode 100644 index 0000000000..4493dff039 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagResourceIntegrationTest.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayTagResourceIntegrationTest { + + @Test + void testTagResource() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"taggable-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract().path("id"); + + String resourceArn = "arn:aws:apigateway:us-east-1::/restapis/" + apiId; + + given() + .pathParam("resourceArn", resourceArn) + .contentType("application/json") + .body("{\"tags\":{\"environment\":\"test\"}}") + .when() + .put("/tags/{resourceArn}") + .then() + .statusCode(204); + + given() + .pathParam("apiId", apiId) + .when() + .get("/restapis/{apiId}") + .then() + .statusCode(200) + .body("tags.environment", equalTo("test")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUntagResourceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUntagResourceIntegrationTest.java new file mode 100644 index 0000000000..a0b1149a5f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUntagResourceIntegrationTest.java @@ -0,0 +1,49 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.nullValue; + +@QuarkusTest +public class ApiGatewayUntagResourceIntegrationTest { + + @Test + public void testUntagResource() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"untaggable-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract().path("id"); + + String resourceArn = "arn:aws:apigateway:us-east-1::/restapis/" + apiId; + + given() + .pathParam("resourceArn", resourceArn) + .contentType("application/json") + .body("{\"tags\":{\"team\":\"platform\"}}") + .when() + .put("/tags/{resourceArn}") + .then() + .statusCode(204); + + given() + .pathParam("resourceArn", resourceArn) + .queryParam("tagKeys", "team") + .when() + .delete("/tags/{resourceArn}") + .then() + .statusCode(204); + + given() + .pathParam("apiId", apiId) + .when() + .get("/restapis/{apiId}") + .then() + .statusCode(200) + .body("tags.team", nullValue()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateAuthorizerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateAuthorizerIntegrationTest.java new file mode 100644 index 0000000000..1ff87bb209 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateAuthorizerIntegrationTest.java @@ -0,0 +1,213 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateAuthorizerIntegrationTest { + + @Test + void shouldUpdateAuthorizerAndPersistChanges() { + // Step 1: Create API + Map createApiBody = new HashMap<>(); + createApiBody.put("name", "update-authorizer-api"); + + String apiId = given() + .contentType("application/json") + .body(createApiBody) + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + // Step 2: Create Authorizer + Map createAuthorizerBody = new HashMap<>(); + createAuthorizerBody.put("name", "before-update"); + createAuthorizerBody.put("type", "TOKEN"); + createAuthorizerBody.put("authorizerUri", "arn:aws:lambda:us-east-1:123456789012:function:my-authorizer"); + createAuthorizerBody.put("identitySource", "method.request.header.Authorization"); + createAuthorizerBody.put("authorizerResultTtlInSeconds", 300); + + String authorizerId = given() + .contentType("application/json") + .body(createAuthorizerBody) + .when() + .post("/restapis/" + apiId + "/authorizers") + .then() + .statusCode(201) + .extract() + .path("id"); + + // Step 3: Update Authorizer via PATCH + Map patchOp1 = new HashMap<>(); + patchOp1.put("op", "replace"); + patchOp1.put("path", "/name"); + patchOp1.put("value", "after-update"); + + Map patchOp2 = new HashMap<>(); + patchOp2.put("op", "replace"); + patchOp2.put("path", "/identitySource"); + patchOp2.put("value", "method.request.header.X-Token"); + + Map patchBody = new HashMap<>(); + patchBody.put("patchOperations", new Object[]{patchOp1, patchOp2}); + + given() + .contentType("application/json") + .body(patchBody) + .when() + .patch("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(200) + .body("id", equalTo(authorizerId)) + .body("name", equalTo("after-update")) + .body("identitySource", equalTo("method.request.header.X-Token")); + + // Step 4: GET Authorizer to verify persistence + given() + .when() + .get("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(200) + .body("name", equalTo("after-update")) + .body("identitySource", equalTo("method.request.header.X-Token")); + } + + /** + * A non-numeric /authorizerResultTtlInSeconds must be rejected before any mutation, otherwise the + * stored value can no longer be serialised and every later GET/ListAuthorizers fails permanently. + */ + @Test + void shouldRejectNonNumericAuthorizerResultTtlAndLeaveAuthorizerReadable() { + Map createApiBody = new HashMap<>(); + createApiBody.put("name", "ttl-validation-api"); + + String apiId = given() + .contentType("application/json") + .body(createApiBody) + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + Map createAuthorizerBody = new HashMap<>(); + createAuthorizerBody.put("name", "ttl-authorizer"); + createAuthorizerBody.put("type", "TOKEN"); + createAuthorizerBody.put("authorizerUri", "arn:aws:lambda:us-east-1:123456789012:function:my-authorizer"); + createAuthorizerBody.put("identitySource", "method.request.header.Authorization"); + createAuthorizerBody.put("authorizerResultTtlInSeconds", 300); + + String authorizerId = given() + .contentType("application/json") + .body(createAuthorizerBody) + .when() + .post("/restapis/" + apiId + "/authorizers") + .then() + .statusCode(201) + .extract() + .path("id"); + + Map badOp = new HashMap<>(); + badOp.put("op", "replace"); + badOp.put("path", "/authorizerResultTtlInSeconds"); + badOp.put("value", "not-a-number"); + + Map patchBody = new HashMap<>(); + patchBody.put("patchOperations", new Object[]{badOp}); + + given() + .contentType("application/json") + .body(patchBody) + .when() + .patch("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(400); + + given() + .when() + .get("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(200) + .body("authorizerResultTtlInSeconds", equalTo(300)); + + given() + .when() + .get("/restapis/" + apiId + "/authorizers") + .then() + .statusCode(200); + } + + /** + * A PATCH is all-or-nothing: a valid op followed by an invalid one must reject the whole request + * without leaving the valid op's mutation visible. + */ + @Test + void shouldRejectWholePatchAndLeaveNameUnchangedWhenALaterOpIsInvalid() { + Map createApiBody = new HashMap<>(); + createApiBody.put("name", "partial-apply-api"); + + String apiId = given() + .contentType("application/json") + .body(createApiBody) + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + Map createAuthorizerBody = new HashMap<>(); + createAuthorizerBody.put("name", "original-name"); + createAuthorizerBody.put("type", "TOKEN"); + createAuthorizerBody.put("authorizerUri", "arn:aws:lambda:us-east-1:123456789012:function:my-authorizer"); + createAuthorizerBody.put("identitySource", "method.request.header.Authorization"); + + String authorizerId = given() + .contentType("application/json") + .body(createAuthorizerBody) + .when() + .post("/restapis/" + apiId + "/authorizers") + .then() + .statusCode(201) + .extract() + .path("id"); + + Map validOp = new HashMap<>(); + validOp.put("op", "replace"); + validOp.put("path", "/name"); + validOp.put("value", "renamed"); + + Map invalidOp = new HashMap<>(); + invalidOp.put("op", "replace"); + invalidOp.put("path", "/authorizerResultTtlInSeconds"); + invalidOp.put("value", "not-a-number"); + + Map patchBody = new HashMap<>(); + patchBody.put("patchOperations", new Object[]{validOp, invalidOp}); + + given() + .contentType("application/json") + .body(patchBody) + .when() + .patch("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(400); + + given() + .when() + .get("/restapis/" + apiId + "/authorizers/" + authorizerId) + .then() + .statusCode(200) + .body("name", equalTo("original-name")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateBasePathMappingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateBasePathMappingIntegrationTest.java new file mode 100644 index 0000000000..190d6a9913 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateBasePathMappingIntegrationTest.java @@ -0,0 +1,27 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateBasePathMappingIntegrationTest { + + @Test + void testCreateAndUpdateBasePathMapping() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"mapping-api\"}") + .when().post("/restapis").then().statusCode(201).extract().path("id"); + given().contentType("application/json").body("{\"domainName\":\"mapping.example.test\"}").when().post("/domainnames").then().statusCode(201); + String basePath = "v1"; + String stageBefore = "before"; + String createBody = "{\"basePath\":\"" + basePath + "\",\"restApiId\":\"" + apiId + "\",\"stage\":\"" + stageBefore + "\"}"; + given().contentType("application/json").body(createBody).when().post("/domainnames/mapping.example.test/basepathmappings").then().statusCode(201); + String patchBody = "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/stage\",\"value\":\"after\"}]}"; + given().contentType("application/json").body(patchBody).when().patch("/domainnames/mapping.example.test/basepathmappings/v1").then().statusCode(200).body("basePath", equalTo(basePath)).body("restApiId", equalTo(apiId)).body("stage", equalTo("after")); + given().when().get("/domainnames/mapping.example.test/basepathmappings/v1").then().statusCode(200).body("stage", equalTo("after")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateDeploymentIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateDeploymentIntegrationTest.java new file mode 100644 index 0000000000..7ef89c6243 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateDeploymentIntegrationTest.java @@ -0,0 +1,53 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateDeploymentIntegrationTest { + + @Test + void testUpdateDeployment() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"update-deployment-api\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String deploymentId = given() + .contentType("application/json") + .body("{\"description\":\"before-update\"}") + .when() + .post("/restapis/" + apiId + "/deployments") + .then() + .statusCode(201) + .extract() + .path("id"); + + String patchBody = "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"after-update\"}]}"; + + given() + .contentType("application/json") + .body(patchBody) + .when() + .patch("/restapis/" + apiId + "/deployments/" + deploymentId) + .then() + .statusCode(200) + .body("id", equalTo(deploymentId)) + .body("description", equalTo("after-update")); + + given() + .when() + .get("/restapis/" + apiId + "/deployments/" + deploymentId) + .then() + .statusCode(200) + .body("description", equalTo("after-update")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateDomainNameIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateDomainNameIntegrationTest.java new file mode 100644 index 0000000000..cd4ec087ef --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateDomainNameIntegrationTest.java @@ -0,0 +1,45 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateDomainNameIntegrationTest { + + @Test + void testUpdateDomainName() { + // POST /domainnames + given() + .contentType("application/json") + .body("{\"domainName\":\"update.example.test\",\"certificateName\":\"before\"}") + .when() + .post("/domainnames") + .then() + .statusCode(201); + + // PATCH /domainnames/update.example.test + given() + .contentType("application/json") + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/certificateName\",\"value\":\"after\"},{\"op\":\"replace\",\"path\":\"/securityPolicy\",\"value\":\"TLS_1_0\"}]}") + .when() + .patch("/domainnames/update.example.test") + .then() + .statusCode(200) + .body("domainName", equalTo("update.example.test")) + .body("certificateName", equalTo("after")) + .body("securityPolicy", equalTo("TLS_1_0")); + + // GET /domainnames/update.example.test + given() + .when() + .get("/domainnames/update.example.test") + .then() + .statusCode(200) + .body("domainName", equalTo("update.example.test")) + .body("certificateName", equalTo("after")) + .body("securityPolicy", equalTo("TLS_1_0")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateIntegrationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateIntegrationIntegrationTest.java new file mode 100644 index 0000000000..0db79fbc5f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateIntegrationIntegrationTest.java @@ -0,0 +1,60 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateIntegrationIntegrationTest { + + @Test + void testApiGatewayIntegrationUpdate() { + String apiId = given() + .contentType("application/json") + .body("{\"name\": \"integration-update\"}") + .when().post("/restapis").then().statusCode(201).extract().path("id"); + String rootId = given() + .when().get("/restapis/" + apiId + "/resources") + .then().statusCode(200).extract().path("item[0].id"); + String resourceId = given() + .contentType("application/json") + .body("{\"pathPart\": \"items\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId) + .then().statusCode(201).extract().path("id"); + given().contentType("application/json").body("{\"authorizationType\": \"NONE\"}").when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET").then().statusCode(201); + given().contentType("application/json").body("{\"type\": \"MOCK\", \"passthroughBehavior\": \"WHEN_NO_MATCH\"}").when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration").then().statusCode(201); + given().contentType("application/json").body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/passthroughBehavior\",\"value\":\"NEVER\"}]} ").when().patch("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration").then().statusCode(200).body("type", equalTo("MOCK")).body("passthroughBehavior", equalTo("NEVER")); + given().when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration").then().statusCode(200).body("passthroughBehavior", equalTo("NEVER")); + } + + @Test + void testRejectedPatchDoesNotPartiallyApply() { + String apiId = given() + .contentType("application/json") + .body("{\"name\": \"integration-update-reject\"}") + .when().post("/restapis").then().statusCode(201).extract().path("id"); + String rootId = given() + .when().get("/restapis/" + apiId + "/resources") + .then().statusCode(200).extract().path("item[0].id"); + String resourceId = given() + .contentType("application/json") + .body("{\"pathPart\": \"items\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId) + .then().statusCode(201).extract().path("id"); + given().contentType("application/json").body("{\"authorizationType\": \"NONE\"}").when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET").then().statusCode(201); + given().contentType("application/json").body("{\"type\": \"MOCK\", \"passthroughBehavior\": \"WHEN_NO_MATCH\"}").when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration").then().statusCode(201); + + given().contentType("application/json") + .body("{\"patchOperations\":[" + + "{\"op\":\"replace\",\"path\":\"/passthroughBehavior\",\"value\":\"NEVER\"}," + + "{\"op\":\"replace\",\"path\":\"/notASupportedPath\",\"value\":\"x\"}" + + "]}") + .when().patch("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration") + .then().statusCode(400); + + given().when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration") + .then().statusCode(200).body("passthroughBehavior", equalTo("WHEN_NO_MATCH")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateIntegrationResponseIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateIntegrationResponseIntegrationTest.java new file mode 100644 index 0000000000..3f2dc6cce6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateIntegrationResponseIntegrationTest.java @@ -0,0 +1,23 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateIntegrationResponseIntegrationTest { + + @Test + void testUpdateIntegrationResponse() { + String apiId = given().contentType("application/json").body("{\"name\":\"ir-update\"}").when().post("/restapis").then().statusCode(201).extract().path("id"); + String rootId = given().when().get("/restapis/" + apiId + "/resources").then().statusCode(200).extract().path("item[0].id"); + String resourceId = given().contentType("application/json").body("{\"pathPart\":\"items\"}").when().post("/restapis/" + apiId + "/resources/" + rootId).then().statusCode(201).extract().path("id"); + given().contentType("application/json").body("{\"authorizationType\":\"NONE\"}").when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET").then().statusCode(201); + given().contentType("application/json").body("{\"type\":\"MOCK\"}").when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration").then().statusCode(201); + given().contentType("application/json").body("{\"selectionPattern\":\"before\",\"responseTemplates\":{\"application/json\":\"before\"}}").when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200").then().statusCode(201); + given().contentType("application/json").body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/selectionPattern\",\"value\":\"after\"}]}").when().patch("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200").then().statusCode(200).body("statusCode", equalTo("200")).body("selectionPattern", equalTo("after")); + given().when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200").then().statusCode(200).body("selectionPattern", equalTo("after")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateMethodIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateMethodIntegrationTest.java new file mode 100644 index 0000000000..9df317fad6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateMethodIntegrationTest.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateMethodIntegrationTest { + + @Test + void testUpdateMethodAuthorizationType() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"method-update\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String rootId = given() + .when() + .get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + .extract() + .path("item[0].id"); + + String childId = given() + .contentType("application/json") + .body("{\"pathPart\":\"items\"}") + .when() + .post("/restapis/" + apiId + "/resources/" + rootId) + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .contentType("application/json") + .body("{\"httpMethod\":\"GET\",\"authorizationType\":\"NONE\"}") + .when() + .put("/restapis/" + apiId + "/resources/" + childId + "/methods/GET") + .then() + .statusCode(201); + + String patchBody = "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/authorizationType\",\"value\":\"AWS_IAM\"}]}"; + given() + .contentType("application/json") + .body(patchBody) + .when() + .patch("/restapis/" + apiId + "/resources/" + childId + "/methods/GET") + .then() + .statusCode(200).body("httpMethod", equalTo("GET")).body("authorizationType", equalTo("AWS_IAM")); + + given() + .when() + .get("/restapis/" + apiId + "/resources/" + childId + "/methods/GET") + .then() + .statusCode(200) + .body("authorizationType", equalTo("AWS_IAM")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateModelIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateModelIntegrationTest.java new file mode 100644 index 0000000000..fe5eb904bb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateModelIntegrationTest.java @@ -0,0 +1,132 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +@TestHTTPEndpoint(ApiGatewayController.class) +class ApiGatewayUpdateModelIntegrationTest { + + private String createApi(String name) { + return given() + .contentType(ContentType.JSON) + .body("{\"name\":\"" + name + "\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + } + + private String createModel(String apiId, String modelName) { + return given() + .contentType(ContentType.JSON) + .body("{\"name\":\"" + modelName + "\",\"description\":\"old\",\"contentType\":\"application/json\",\"schema\":\"{}\"}") + .pathParam("apiId", apiId) + .when() + .post("/restapis/{apiId}/models") + .then() + .statusCode(201) + .extract() + .path("name"); + } + + @Test + void testCreateApiAndModelWorkflow() { + String apiId = createApi("model-test-api"); + String modelName = createModel(apiId, "TestModel"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"new\"}]}") + .pathParam("apiId", apiId) + .pathParam("modelName", modelName) + .when() + .patch("/restapis/{apiId}/models/{modelName}") + .then() + .statusCode(200) + .body("description", equalTo("new")); + + given() + .pathParam("apiId", apiId) + .pathParam("modelName", modelName) + .when() + .get("/restapis/{apiId}/models/{modelName}") + .then() + .statusCode(200) + .body("name", equalTo("TestModel")) + .body("description", equalTo("new")); + } + + @Test + void testUpdateModelSchemaAndContentTypeViaPatchOperations() { + String apiId = createApi("model-patch-api"); + String modelName = createModel(apiId, "PatchModel"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[" + + "{\"op\":\"replace\",\"path\":\"/schema\",\"value\":\"{\\\"type\\\":\\\"object\\\"}\"}," + + "{\"op\":\"replace\",\"path\":\"/contentType\",\"value\":\"application/xml\"}]}") + .pathParam("apiId", apiId) + .pathParam("modelName", modelName) + .when() + .patch("/restapis/{apiId}/models/{modelName}") + .then() + .statusCode(200) + .body("contentType", equalTo("application/xml")) + .body("schema", equalTo("{\"type\":\"object\"}")); + + given() + .pathParam("apiId", apiId) + .pathParam("modelName", modelName) + .when() + .get("/restapis/{apiId}/models/{modelName}") + .then() + .statusCode(200) + .body("contentType", equalTo("application/xml")); + } + + /** AWS treats model names as immutable; a rename must be rejected rather than clobber a sibling. */ + @Test + void testRenameIsRejectedAndDoesNotDestroyAnotherModel() { + String apiId = createApi("model-rename-api"); + createModel(apiId, "SourceModel"); + createModel(apiId, "TargetModel"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"TargetModel\"}]}") + .pathParam("apiId", apiId) + .pathParam("modelName", "SourceModel") + .when() + .patch("/restapis/{apiId}/models/{modelName}") + .then() + .statusCode(400); + + given() + .pathParam("apiId", apiId) + .pathParam("modelName", "SourceModel") + .when() + .get("/restapis/{apiId}/models/{modelName}") + .then() + .statusCode(200) + .body("name", equalTo("SourceModel")); + + given() + .pathParam("apiId", apiId) + .pathParam("modelName", "TargetModel") + .when() + .get("/restapis/{apiId}/models/{modelName}") + .then() + .statusCode(200) + .body("name", equalTo("TargetModel")) + .body("description", equalTo("old")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRequestValidatorIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRequestValidatorIntegrationTest.java new file mode 100644 index 0000000000..7fdd3f2dae --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRequestValidatorIntegrationTest.java @@ -0,0 +1,53 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateRequestValidatorIntegrationTest { + + @Test + void testUpdateRequestValidator() { + String apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"validator-update\"}") + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String validatorId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"before\",\"validateRequestBody\":false,\"validateRequestParameters\":true}") + .post("/restapis/" + apiId + "/requestvalidators") + .then() + .statusCode(201) + .extract() + .path("id"); + + String patchBody = "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"updated-validator\"},{\"op\":\"replace\",\"path\":\"/validateRequestBody\",\"value\":\"true\"},{\"op\":\"replace\",\"path\":\"/validateRequestParameters\",\"value\":\"false\"}]}"; + + given() + .contentType(ContentType.JSON) + .body(patchBody) + .patch("/restapis/" + apiId + "/requestvalidators/" + validatorId) + .then() + .statusCode(200) + .body("name", equalTo("updated-validator")) + .body("validateRequestBody", equalTo(true)) + .body("validateRequestParameters", equalTo(false)); + + given() + .get("/restapis/" + apiId + "/requestvalidators/" + validatorId) + .then() + .statusCode(200) + .body("name", equalTo("updated-validator")) + .body("validateRequestBody", equalTo(true)) + .body("validateRequestParameters", equalTo(false)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateResourceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateResourceIntegrationTest.java new file mode 100644 index 0000000000..99404109a0 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateResourceIntegrationTest.java @@ -0,0 +1,251 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateResourceIntegrationTest { + + @Test + void testUpdateResourcePathAndParent() { + // 1. Create API + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"resource-update\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + // 2. Get root resource ID + String rootId = given() + .pathParam("apiId", apiId) + .when() + .get("/restapis/{apiId}/resources") + .then() + .statusCode(200) + .extract() + .path("item[0].id"); + + // 3. Create root children: "left" and "right" + String leftId = given() + .pathParam("apiId", apiId) + .pathParam("parentId", rootId) + .contentType("application/json") + .body("{\"pathPart\":\"left\"}") + .when() + .post("/restapis/{apiId}/resources/{parentId}") + .then() + .statusCode(201) + .extract() + .path("id"); + + String rightId = given() + .pathParam("apiId", apiId) + .pathParam("parentId", rootId) + .contentType("application/json") + .body("{\"pathPart\":\"right\"}") + .when() + .post("/restapis/{apiId}/resources/{parentId}") + .then() + .statusCode(201) + .extract() + .path("id"); + + // 4. Create child under left + String childId = given() + .pathParam("apiId", apiId) + .pathParam("parentId", leftId) + .contentType("application/json") + .body("{\"pathPart\":\"child\"}") + .when() + .post("/restapis/{apiId}/resources/{parentId}") + .then() + .statusCode(201) + .extract() + .path("id"); + + // 5. Create grand under child + String grandId = given() + .pathParam("apiId", apiId) + .pathParam("parentId", childId) + .contentType("application/json") + .body("{\"pathPart\":\"grand\"}") + .when() + .post("/restapis/{apiId}/resources/{parentId}") + .then() + .statusCode(201) + .extract() + .path("id"); + + // 6. PATCH child: move to right, rename to "moved" + String patchBody = String.format( + "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/pathPart\",\"value\":\"moved\"},{\"op\":\"replace\",\"path\":\"/parentId\",\"value\":\"%s\"}]}", + rightId + ); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", childId) + .contentType("application/json") + .body(patchBody) + .when() + .patch("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(200) + .body("parentId", equalTo(rightId)) + .body("pathPart", equalTo("moved")) + .body("path", equalTo("/right/moved")); + + // 7. GET grand: should now be under moved (which is under right) + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", grandId) + .when() + .get("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(200) + .body("parentId", equalTo(childId)) + .body("path", equalTo("/right/moved/grand")); + + // 8. GET child: verify updated state + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", childId) + .when() + .get("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(200) + .body("parentId", equalTo(rightId)) + .body("pathPart", equalTo("moved")) + .body("path", equalTo("/right/moved")); + } + + private String createApi(String name) { + return given() + .contentType("application/json") + .body("{\"name\":\"" + name + "\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + } + + private String rootResourceId(String apiId) { + return given() + .pathParam("apiId", apiId) + .when() + .get("/restapis/{apiId}/resources") + .then() + .statusCode(200) + .extract() + .path("item[0].id"); + } + + private String createChild(String apiId, String parentId, String pathPart) { + return given() + .pathParam("apiId", apiId) + .pathParam("parentId", parentId) + .contentType("application/json") + .body("{\"pathPart\":\"" + pathPart + "\"}") + .when() + .post("/restapis/{apiId}/resources/{parentId}") + .then() + .statusCode(201) + .extract() + .path("id"); + } + + /** AWS returns 400 when /parentId names an id that does not exist, not a 404 about the patched resource. */ + @Test + void testUpdateResourceWithUnknownParentIdReturnsBadRequest() { + String apiId = createApi("resource-bad-parent"); + String rootId = rootResourceId(apiId); + String childId = createChild(apiId, rootId, "thing"); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", childId) + .contentType("application/json") + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/parentId\",\"value\":\"nosuchid\"}]}") + .when() + .patch("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(400); + } + + /** Two siblings may not share a pathPart; AWS returns ConflictException. */ + @Test + void testUpdateResourceRejectsSiblingPathCollision() { + String apiId = createApi("resource-collision-patch"); + String rootId = rootResourceId(apiId); + createChild(apiId, rootId, "alpha"); + String betaId = createChild(apiId, rootId, "beta"); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", betaId) + .contentType("application/json") + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/pathPart\",\"value\":\"alpha\"}]}") + .when() + .patch("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(409); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", betaId) + .when() + .get("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(200) + .body("pathPart", equalTo("beta")) + .body("path", equalTo("/beta")); + } + + @Test + void testUpdateResourceRejectsCollisionAfterReparenting() { + String apiId = createApi("resource-collision-reparent"); + String rootId = rootResourceId(apiId); + String leftId = createChild(apiId, rootId, "left"); + String rightId = createChild(apiId, rootId, "right"); + createChild(apiId, rightId, "shared"); + String movingId = createChild(apiId, leftId, "shared"); + + given() + .pathParam("apiId", apiId) + .pathParam("resourceId", movingId) + .contentType("application/json") + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/parentId\",\"value\":\"" + rightId + "\"}]}") + .when() + .patch("/restapis/{apiId}/resources/{resourceId}") + .then() + .statusCode(409); + } + + @Test + void testCreateResourceRejectsDuplicateSiblingPathPart() { + String apiId = createApi("resource-collision-create"); + String rootId = rootResourceId(apiId); + createChild(apiId, rootId, "dup"); + + given() + .pathParam("apiId", apiId) + .pathParam("parentId", rootId) + .contentType("application/json") + .body("{\"pathPart\":\"dup\"}") + .when() + .post("/restapis/{apiId}/resources/{parentId}") + .then() + .statusCode(409); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRestApiIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRestApiIntegrationTest.java new file mode 100644 index 0000000000..9e032baa4a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateRestApiIntegrationTest.java @@ -0,0 +1,40 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +public class ApiGatewayUpdateRestApiIntegrationTest { + + @Test + public void testUpdateRestApi() { + String id = given() + .contentType("application/json") + .body("{\"name\":\"rest-api-update\",\"description\":\"before\"}") + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + + String patchBody = "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"updated description\"}]}"; + + given() + .contentType("application/json") + .body(patchBody) + .patch("/restapis/" + id) + .then() + .statusCode(200) + .body("name", equalTo("rest-api-update")) + .body("description", equalTo("updated description")); + + given() + .get("/restapis/" + id) + .then() + .statusCode(200) + .body("description", equalTo("updated description")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateStageIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateStageIntegrationTest.java new file mode 100644 index 0000000000..9b7dee5384 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUpdateStageIntegrationTest.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class ApiGatewayUpdateStageIntegrationTest { + @Test + void testUpdateStageDescription() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"stage-update\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract() + .path("id"); + String rootId = given().when().get("/restapis/" + apiId + "/resources") + .then().statusCode(200).extract().path("item[0].id"); + String deploymentId = given().contentType("application/json") + .body("{\"description\":\"v1\"}") + .when() + .post("/restapis/" + apiId + "/deployments") + .then() + .statusCode(201) + .extract() + .path("id"); + given().contentType("application/json") + .body("{\"stageName\":\"dev\",\"deploymentId\":\"" + deploymentId + "\",\"description\":\"before\"}") + .when() + .post("/restapis/" + apiId + "/stages") + .then() + .statusCode(201); + String patchBody = "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"updated\"}]}"; + given().contentType("application/json").body(patchBody) + .when() + .patch("/restapis/" + apiId + "/stages/dev") + .then() + .statusCode(200) + .body("description", equalTo("updated")); + given().when().get("/restapis/" + apiId + "/stages/dev") + .then() + .statusCode(200) + .body("description", equalTo("updated")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUsagePlanCrudIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUsagePlanCrudIntegrationTest.java new file mode 100644 index 0000000000..c23804046e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUsagePlanCrudIntegrationTest.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +@TestHTTPEndpoint(ApiGatewayController.class) +class ApiGatewayUsagePlanCrudIntegrationTest { + + @Test + void testCreateAndRetrieveUsagePlan() { + String usagePlanId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"before\",\"description\":\"old\"}") + .post("/usageplans") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[" + + "{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"after\"}," + + "{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"new\"}]}") + .patch("/usageplans/{usagePlanId}", usagePlanId) + .then() + .statusCode(200) + .body("name", equalTo("after")) + .body("description", equalTo("new")); + + given() + .get("/usageplans/{usagePlanId}", usagePlanId) + .then() + .statusCode(200) + .body("id", equalTo(usagePlanId)) + .body("name", equalTo("after")) + .body("description", equalTo("new")); + } + + @Test + void testUnsupportedPatchPathIsRejected() { + String usagePlanId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"reject-path\",\"description\":\"old\"}") + .post("/usageplans") + .then() + .statusCode(201) + .extract() + .path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/nope\",\"value\":\"x\"}]}") + .patch("/usageplans/{usagePlanId}", usagePlanId) + .then() + .statusCode(400); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUsagePlanKeyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUsagePlanKeyIntegrationTest.java new file mode 100644 index 0000000000..992cf66bf8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUsagePlanKeyIntegrationTest.java @@ -0,0 +1,69 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; + +@QuarkusTest +@TestHTTPEndpoint(ApiGatewayController.class) +public class ApiGatewayUsagePlanKeyIntegrationTest { + + @Test + public void testUsagePlanKeyLifecycle() { + String apiKeyId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"usage-key\",\"enabled\":true}") + .when() + .post("/apikeys") + .then() + .statusCode(201) + .body("id", notNullValue()) + .extract() + .path("id"); + + String usagePlanId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"key-plan\"}") + .when() + .post("/usageplans") + .then() + .statusCode(201) + .body("id", notNullValue()) + .extract() + .path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"keyId\":\"" + apiKeyId + "\",\"keyType\":\"API_KEY\"}") + .when() + .post("/usageplans/" + usagePlanId + "/keys") + .then() + .statusCode(201) + .body("id", equalTo(apiKeyId)); + + given() + .when() + .get("/usageplans/" + usagePlanId + "/keys") + .then() + .statusCode(200) + .body("item[0].id", equalTo(apiKeyId)); + + given() + .when() + .get("/usageplans/" + usagePlanId + "/keys/" + apiKeyId) + .then() + .statusCode(200) + .body("id", equalTo(apiKeyId)); + + given() + .when() + .delete("/usageplans/" + usagePlanId + "/keys/" + apiKeyId) + .then() + .statusCode(202); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiKeyCsvParserTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiKeyCsvParserTest.java new file mode 100644 index 0000000000..2363d1096e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiKeyCsvParserTest.java @@ -0,0 +1,48 @@ +package io.github.hectorvent.floci.services.apigateway; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ApiKeyCsvParserTest { + + @Test + void parsesStandardCsvWithCommaInField() { + String csv = "Name,Key,UsagePlanIds\nMyKey,abcdefghijklmnopqrst,\"up-1,up-2\"\n"; + List> result = ApiKeyCsvParser.parse(csv); + + assertEquals(2, result.size()); + assertEquals(List.of("Name", "Key", "UsagePlanIds"), result.get(0)); + assertEquals(List.of("MyKey", "abcdefghijklmnopqrst", "up-1,up-2"), result.get(1)); + } + + @Test + void parsesEscapedQuotes() { + String csv = "Name,Key\n\"A \"\"quoted\"\" key\",abcdefghijklmnopqrst\n"; + List> result = ApiKeyCsvParser.parse(csv); + + assertEquals(2, result.size()); + assertEquals(List.of("Name", "Key"), result.get(0)); + assertEquals(List.of("A \"quoted\" key", "abcdefghijklmnopqrst"), result.get(1)); + } + + @Test + void parsesCRLFAndIgnoresFinalEmptyRow() { + String csv = "Name,Key\r\nMyKey,abcdefghijklmnopqrst\r\n"; + List> result = ApiKeyCsvParser.parse(csv); + + assertEquals(2, result.size()); + assertEquals(List.of("Name", "Key"), result.get(0)); + assertEquals(List.of("MyKey", "abcdefghijklmnopqrst"), result.get(1)); + } + + @Test + void throwsOnUnterminatedQuote() { + String csv = "Name,Key\n\"Unfinished,Value\n"; + + assertThrows(IllegalArgumentException.class, () -> ApiKeyCsvParser.parse(csv)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiCorsConfigurationResponseTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiCorsConfigurationResponseTest.java index da64b82548..ad984b6b50 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiCorsConfigurationResponseTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiCorsConfigurationResponseTest.java @@ -158,6 +158,28 @@ class ApiCorsConfigurationResponseTest { .body("corsConfiguration", nullValue()); } + @Test + void deleteCorsConfigurationRemovesConfiguration() { + String apiId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"cors-delete","protocolType":"HTTP", + "corsConfiguration":{"allowOrigins":["https://example.com"]}} + """) + .when().post("/v2/apis") + .then().statusCode(201) + .extract().path("apiId"); + + given() + .when().delete("/v2/apis/" + apiId + "/cors") + .then().statusCode(204); + + given() + .when().get("/v2/apis/" + apiId) + .then().statusCode(200) + .body("$", not(hasKey("corsConfiguration"))); + } + // ──────────────────────────── JSON 1.1 path ──────────────────────────── @Test