feat(apigateway): API key import/usage-plan fidelity and update-operation fixes (#2631)

* feat(apigateway): complete the REST API resource lifecycle

Adds the missing delete and update operations across authorizers,
integrations, integration responses, methods, method responses, models,
request validators, resources, rest APIs, stages, deployments, domain names
and base path mappings, plus tag/untag, usage plan and usage plan key CRUD,
and ImportApiKeys backed by a new ApiKeyCsvParser.

Each operation has a wire-level integration test.

* feat(apigatewayv2): allow clearing an HTTP API CORS configuration

deleteCorsConfiguration unsets the optional CORS block on a stored API so
the response omits it rather than echoing a stale configuration.

* fix(apigateway): accept the AWS-native ImportApiKeys CSV format

The header validator required exactly `name,value,enabled` in lowercase and
read every row by fixed position. Real AWS ships `Name,Key,Description,
Enabled,UsagePlanIds`, so the CLI, SDKs and Terraform all took a 400 on their
first call. Columns are now resolved case-insensitively by name into an index
map, `value` is kept as an alias for `Key`, a missing or blank `Enabled`
defaults to true as AWS does, and rows shorter than the header no longer throw.

Imported keys are also created with generateDistinctId, because the CSV `Key`
column is the key VALUE and AWS generates the id separately — reusing the value
as the id let one row silently clobber an existing key and detach its usage
plan associations.

ImportApiKeys now reports warnings for real: a row whose key value duplicates an
earlier row in the same import raises one, and `failonwarnings=true` turns those
warnings into a BadRequestException instead of being ignored.

* fix(apigateway): honour the patchOperations envelope on UpdateModel and UpdateUsagePlan

Both handlers parsed the PATCH body as a flat map. Real AWS sends
`{"patchOperations":[{"op":"replace","path":"/description","value":"x"}]}`, so
the flat parse succeeded, matched nothing, and returned the untouched resource
with a 200 — a silent no-op. Both now walk the ops list the way the six sibling
endpoints in this controller already do.

UpdateModel supports /description, /schema and /contentType, and rejects /name
with a BadRequestException: AWS treats a model name as an immutable identifier.
That also removes the delete-then-put rename, which had no existence check on
the target key and so destroyed any model already using the new name.

UpdateUsagePlan supports /name, /description and add/remove of /apiStages as
"apiId:stage", covering what the flat handler could do. UsagePlan carries no
throttle or quota state, so those paths are left unsupported rather than faked.

UpdateAuthorizer now parses /authorizerResultTtlInSeconds before mutating
anything. A non-numeric value used to be written straight to the store, after
which serialisation threw on the PATCH and on every later GetAuthorizer and
GetAuthorizers for that resource — unrecoverable short of delete and recreate.

* fix(apigateway): reject duplicate sibling paths and bad parentId on resources

UpdateResource pointed at an unknown /parentId surfaced getResource's 404
"Invalid resource id specified", which reads as though the resource being
patched is missing; the `parent == null` guard beneath it was unreachable for
the same reason. AWS answers 400, so the lookup failure is now rethrown as a
BadRequestException naming the offending value.

Neither CreateResource nor UpdateResource checked for a sibling collision, so
two children of one parent could end up with the same path and request routing
became order-dependent. Both now go through a shared guard that raises
ConflictException (409) when another child of the effective parent already uses
that pathPart.

UpdateResource also stopped mutating as it goes. The store hands back live
objects, so applying ops in-place meant a later rejected op left the earlier
ones visible in memory; the patch is now resolved into pending parentId and
pathPart values, validated, and only then applied.

* style(apigateway): put HttpHeaders first in deleteAuthorizer

Every other handler in the controller takes @Context HttpHeaders as its first
parameter. No behaviour change.

* fix(apigateway): answer BadRequestException for a malformed patchOperations envelope

The PATCH handlers parsed the envelope with convertValue(node, List.class)
inside a catch that only covered IOException. convertValue throws
IllegalArgumentException, which no mapper handles, so a non-array
patchOperations returned 500 instead of the modelled BadRequestException.
The raw List.class conversion also deferred a structured operation value
into the service layer as a ClassCastException, a second 500.

Extract one parsePatchOperations helper that converts through a
TypeReference<List<Map<String, String>>> and widens the catch, so scalar
values coerce and structured ones are rejected at the boundary.

* fix(apigateway): dispatch ImportApiKeys on mode, not on media type

ImportApiKeys was annotated @Consumes("text/csv"), but botocore sends the
operation with no Content-Type header at all — only Accept: application/json.
A request with no Content-Type is application/octet-stream to JAX-RS, so it
never matched, and fell through to the sibling CreateApiKey handler, which
fed the CSV body to the JSON parser and answered a spurious
BadRequestException. Every existing test hid this by setting text/csv
explicitly, a header no client sends.

Fold both operations into one POST /apikeys handler that consumes any media
type and tells them apart by the mode query parameter, the way AWS does, and
cover it with a raw-client case that sends no Content-Type.

* docs(apigateway): document the operations this branch added

The branch added 13 v1 management operations and DeleteCorsConfiguration on
v2 without touching docs, and the Not Implemented list still named
UpdateAuthorizer, DeleteAuthorizer, ImportApiKeys, GetUsagePlan,
UpdateUsagePlan and UpdateModel as absent. GetDeployment and DeleteDeployment
were already implemented but had never been listed either.

api-gateway.md is hand-maintained — ApiGatewayController is a REST controller
and is not registered in tools/docs/services.yaml — so the tables are updated
by hand and the index counts follow the tables: v1 64 -> 79, v2 48 -> 49.
Also record how CreateApiKey and ImportApiKeys share POST /apikeys.

* fix(apigateway): extend the patchOperations boundary parse to the inherited handlers

Six PATCH handlers predate this branch and still parsed the envelope with
convertValue(node, List.class) inside an IOException-only catch, so
updateRestApi, updateResource, updateMethod, updateIntegration, updateStage
and updateApiKey kept answering 500 for a malformed envelope while the eight
handlers this branch added answered 400. A reviewer would rightly ask why
only some of the surface agrees with AWS.

This is a deliberate scope extension beyond the audit's finding: point all
six at the existing parsePatchOperations helper so every PATCH operation on
the service shares one boundary contract. updateAccount stays as it is — it
validates each operation itself and already raises a modelled 400.

* docs(apigatewayv2): correct the VPC Link operations, which are implemented

The v2 Not Implemented list named all five VPC Link operations as absent, but
CreateVpcLink, GetVpcLink, GetVpcLinks and DeleteVpcLink have been routed on
/v2/vpclinks and backed by ApiGatewayV2Service since before this branch. Only
UpdateVpcLink is genuinely missing — there is no PATCH route for it.

Verified each claimed route against ApiGatewayController before editing. Adds
the VPC Links row the v2 table never had and carries the four operations into
the index count: 49 -> 53.

* fix(apigateway): enforce the modelled op enum on patchOperations

Botocore models PatchOperation.op as an enum of add, remove, replace,
move, copy and test. The boundary parse read the envelope's shape but
never the op value, and the handlers behind it disagree about what to do
with an unrecognised one: UpdateModel throws, UpdateApiKey and UpdateStage
skip it. On the skipping handlers an unmodelled op was answered 200 with
the resource untouched, which reads to the caller as an applied patch.

Check op against the enum in parsePatchOperations, the boundary this
branch already made responsible for the envelope on every PATCH handler.
The set is the model's, not the intersection of what the handlers
implement: whether a handler supports move is its own business, but a
value outside the enum should never reach one.

* fix(apigateway): reject a null element in the patchOperations envelope

parsePatchOperations silently skipped a null element in the patchOperations
array instead of rejecting it. Several handlers that predate the shared
boundary parse (updateRestApi, updateStage, updateApiKey, updateMethod) have
no null guard of their own and call op.get("op") directly, so a null element
reached them as an unhandled NullPointerException -- a 500 instead of AWS's
modelled BadRequestException.

Reject the null at the boundary all handlers already share, the same place
that already validates the op enum.

* fix(apigateway): apply patchOperations atomically instead of partially

updateAuthorizer, updateUsagePlan, updateRequestValidator, updateModel,
updateDomainName and updateBasePathMapping mutated the live stored object as
each op was validated. The store hands back live objects (no defensive
copy), so a valid op followed by an invalid one left the valid op's change
visible even though the request answered 400 -- the same partial-apply bug
already fixed for updateResource in an earlier commit on this branch, which
established the fix: resolve every op into pending local values, validate
the whole list, and only mutate the stored object once the patch is known
to be entirely good.

Each handler also now rejects a null patchOperations element explicitly, on
top of the shared boundary's own rejection, matching the defensive style
already used by updateRequestValidator and updateModel before this change.

* fix(apigateway): translate a malformed ImportApiKeys CSV into BadRequestException

ApiKeyCsvParser.parse throws IllegalArgumentException on an unterminated
quoted field, but only AwsException is registered with an ExceptionMapper.
The unmapped exception escaped as a 500 instead of AWS's modelled 400,
letting a malformed import request past the error boundary entirely.

Catch the parser's IllegalArgumentException at the one call site and
translate it into the same BadRequestException every other CSV validation
failure in this method already raises.

* style(apigateway): brace the new conditionals this branch added

New single-line if statements in the domain-name serialization, CSV import
column/cell handling, and resource sibling-collision check violated the
repository's mandatory conditional-brace convention. No behaviour change.

* fix(apigateway): validate all UpdateIntegration patch ops before applying any

updateIntegration mutated the live stored integration inside the same loop that validated later operations, so a PATCH with a valid op followed by an unsupported path left the earlier op applied even though the request as a whole was rejected with 400.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-27 16:59:59 -04:00
1 parent 75f8f42d5f
commit 9b9e7f56a2
37 files changed
+3232 -84

No files matched your search

@@ -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<List<Map<String, String>>> 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<String> 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.
*
* <p>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<Map<String, String>> parsePatchOperations(String body) {
List<Map<String, String>> 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<String, String> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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<Map<String, String>> 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;
}
@@ -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<String, Object> 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<Map<String, String>> patchOperations) {
IntegrationResponse response = getIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode);
String selectionPattern = response.selectionPattern();
if (patchOperations != null) {
for (Map<String, String> 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<String, Object> request) {
@@ -525,6 +566,32 @@ public class ApiGatewayService {
deploymentStore.delete(deploymentKey(region, apiId, deploymentId));
}
public Deployment updateDeployment(String region, String apiId, String deploymentId, List<Map<String, String>> patchOperations) {
Deployment existing = getDeployment(region, apiId, deploymentId);
if (patchOperations != null) {
String newDescription = existing.description();
for (Map<String, String> 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<String, Object> request) {
@@ -704,6 +771,58 @@ public class ApiGatewayService {
authorizerStore.delete(authorizerKey(region, apiId, authorizerId));
}
public Authorizer updateAuthorizer(String region, String apiId, String authorizerId, List<Map<String, String>> 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<String, String> 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<String, Object> 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<String> ids, List<String> 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<List<String>> 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<String> header = rows.get(0);
Map<String, Integer> 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<String> ids = new ArrayList<>();
List<String> warnings = new ArrayList<>();
Set<String> seenValues = new HashSet<>();
for (int i = 1; i < rows.size(); i++) {
List<String> 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<String, Object> 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<String> 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<Map<String, String>> 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<UsagePlan.ApiStage> newApiStages = new ArrayList<>(plan.getApiStages());
if (patchOperations != null) {
for (Map<String, String> 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<UsagePlan> 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<Map<String, String>> 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<String, String> 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<String, Object> 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<Map<String, String>> 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<String, String> 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<Model> 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<Map<String, String>> 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<String, String> 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<Map<String, String>> 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<String, String> 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<Map<String, String>> 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<String, String> 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<ApiGatewayResource> allResources = getResources(region, apiId);
Map<String, ApiGatewayResource> 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<Map<String, String>> 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<String, String> 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<String, String> 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");
}
}
}
@@ -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<List<String>> parse(String csv) {
if (csv == null || csv.isEmpty()) {
return new ArrayList<>();
}
List<List<String>> rows = new ArrayList<>();
List<String> 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;
}
}
@@ -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));
}