From 15720e2ee6c742c082ca6b64accef5de55301d79 Mon Sep 17 00:00:00 2001 From: Prakhar Kapoor <59886854+kapoorp99@users.noreply.github.com> Date: Mon, 18 May 2026 10:12:09 +0530 Subject: [PATCH] feat(apigateway): implement account management endpoints and models (#867) * feat(apigateway): implement account management endpoints and models * feat(apigateway): enhance patch operation validation and update throttle settings defaults * feat(api-gateway): add account management operations to API Gateway v1 * feat(api-gateway): add compatibility tests for account management and update logic * feat(api-gateway): add missing import for assertions in account compatibility test --- .../ApiGatewayAccountCompatibilityTest.java | 38 ++++ docs/services/api-gateway.md | 2 +- docs/services/index.md | 2 +- .../apigateway/ApiGatewayController.java | 112 +++++++++-- .../apigateway/ApiGatewayService.java | 107 ++++++++-- .../services/apigateway/model/Account.java | 47 +++++ .../apigateway/model/ThrottleSettings.java | 26 +++ .../floci/services/iam/IamActionRegistry.java | 13 +- .../ApiGatewayAccountIntegrationTest.java | 188 ++++++++++++++++++ 9 files changed, 504 insertions(+), 31 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAccountCompatibilityTest.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/apigateway/model/Account.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/apigateway/model/ThrottleSettings.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAccountIntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAccountCompatibilityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAccountCompatibilityTest.java new file mode 100644 index 0000000000..dfaf92215b --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAccountCompatibilityTest.java @@ -0,0 +1,38 @@ +package com.floci.test; + +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; +import software.amazon.awssdk.services.apigateway.ApiGatewayClient; +import software.amazon.awssdk.services.apigateway.model.GetAccountRequest; +import software.amazon.awssdk.services.apigateway.model.GetAccountResponse; +import software.amazon.awssdk.services.apigateway.model.UpdateAccountRequest; +import software.amazon.awssdk.services.apigateway.model.PatchOperation; + +class ApiGatewayAccountCompatibilityTest { + + @Test + void getAndUpdateAccount_viaSdk() { + ApiGatewayClient apigw = TestFixtures.apiGatewayClient(); + + GetAccountResponse before = apigw.getAccount(GetAccountRequest.builder().build()); + assertThat(before.apiKeyVersion()).isNotBlank(); + assertThat(before.features()).contains("UsagePlans"); + assertThat(before.throttleSettings()).isNotNull(); + + String arn = "arn:aws:iam::123456789012:role/apigAwsProxyRole"; + PatchOperation op = PatchOperation.builder() + .op("replace") + .path("/cloudwatchRoleArn") + .value(arn) + .build(); + + apigw.updateAccount(UpdateAccountRequest.builder().patchOperations(op).build()); + + GetAccountResponse after = apigw.getAccount(GetAccountRequest.builder().build()); + assertThat(after.cloudwatchRoleArn()).isEqualTo(arn); + + // cleanup + PatchOperation remove = PatchOperation.builder().op("remove").path("/cloudwatchRoleArn").build(); + apigw.updateAccount(UpdateAccountRequest.builder().patchOperations(remove).build()); + } +} diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 180d6c1ee8..5cf69d6900 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -27,6 +27,7 @@ Floci supports both API Gateway v1 (REST APIs) and API Gateway v2 (HTTP APIs). | **Models** | CreateModel, GetModel, GetModels, DeleteModel | | **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName | | **Base Path Mappings** | CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping | +| **Account** | GetAccount, UpdateAccount | | **Tags** | TagResource, UntagResource, GetTags (ListTagsForResource) | ### Not Implemented @@ -42,7 +43,6 @@ These management-plane operations have no handler in v1. Calls will return `404` - Documentation parts and versions (the entire family, 10 operations) - VPC Links (5 operations) - Client Certificates (5 operations) -- Account: `GetAccount`, `UpdateAccount` - `GetExport` / `ImportDocumentationParts` The execute plane (actual proxied HTTP traffic via `/restapis/{id}/{stage}/_user_request_/…`) is implemented separately and is not counted as management-plane operations. diff --git a/docs/services/index.md b/docs/services/index.md index 6f91ced3e1..9833f63aca 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -17,7 +17,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 28 | | [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 | -| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 62 | +| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 64 | | [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 48 + data-plane | | [IAM](iam.md) | `POST /` with `Action=` param | Query | 68 | | [STS](sts.md) | `POST /` with `Action=` param | Query | 7 | 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 0ec610fe5d..8b3ad8222b 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 @@ -1,12 +1,28 @@ package io.github.hectorvent.floci.services.apigateway; -import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.core.common.RegionResolver; -import io.github.hectorvent.floci.services.apigateway.model.*; -import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource; +import io.github.hectorvent.floci.services.apigateway.model.ApiKey; +import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping; +import io.github.hectorvent.floci.services.apigateway.model.CustomDomain; +import io.github.hectorvent.floci.services.apigateway.model.MethodConfig; +import io.github.hectorvent.floci.services.apigateway.model.MethodResponse; +import io.github.hectorvent.floci.services.apigateway.model.RequestValidator; +import io.github.hectorvent.floci.services.apigateway.model.RestApi; +import io.github.hectorvent.floci.services.apigateway.model.UsagePlan; +import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey; +import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; import io.github.hectorvent.floci.services.apigatewayv2.model.Api; import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer; import io.github.hectorvent.floci.services.apigatewayv2.model.Deployment; @@ -17,16 +33,20 @@ import io.github.hectorvent.floci.services.apigatewayv2.model.Route; import io.github.hectorvent.floci.services.apigatewayv2.model.RouteResponse; import io.github.hectorvent.floci.services.apigatewayv2.model.Stage; import jakarta.inject.Inject; -import jakarta.ws.rs.*; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; -import org.jboss.logging.Logger; - -import java.io.IOException; -import java.util.List; -import java.util.Map; /** * Unified AWS API Gateway management endpoints (v1 REST and v2 HTTP). @@ -36,8 +56,6 @@ import java.util.Map; @Consumes({MediaType.APPLICATION_JSON, "application/json-patch+json"}) public class ApiGatewayController { - private static final Logger LOG = Logger.getLogger(ApiGatewayController.class); - private final ApiGatewayService service; private final ApiGatewayV2Service v2Service; private final RegionResolver regionResolver; @@ -156,6 +174,52 @@ public class ApiGatewayController { // ──────────────────────────── General REST APIs (v1) ──────────────────────────── + @GET + @Path("/account") + public Response getAccount(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(toAccountNode(service.getAccount(region)).toString()).type(MediaType.APPLICATION_JSON).build(); + } + + @PATCH + @Path("/account") + public Response updateAccount(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + if (body == null || body.isBlank()) { + throw new AwsException("BadRequestException", "Request body is required", 400); + } + com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations"); + if (!node.isArray()) { + throw new AwsException("BadRequestException", "patchOperations must be an array", 400); + } + + List> patchOperations = new ArrayList<>(); + for (com.fasterxml.jackson.databind.JsonNode operationNode : node) { + if (operationNode == null || operationNode.isNull() || !operationNode.isObject()) { + throw new AwsException("BadRequestException", "Each patch operation must be an object", 400); + } + try { + Map operation = objectMapper.convertValue(operationNode, + new TypeReference>() { + }); + if (operation == null) { + throw new AwsException("BadRequestException", "Each patch operation must be an object", 400); + } + patchOperations.add(operation); + } catch (IllegalArgumentException e) { + throw new AwsException("BadRequestException", "Invalid patch operation", 400); + } + } + + return Response.ok(toAccountNode(service.updateAccount(region, patchOperations)).toString()) + .type(MediaType.APPLICATION_JSON) + .build(); + } catch (IOException | IllegalArgumentException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + @POST @Path("/restapis") public Response createRestApi(@Context HttpHeaders headers, @@ -1544,6 +1608,30 @@ public class ApiGatewayController { return node; } + private ObjectNode toAccountNode(io.github.hectorvent.floci.services.apigateway.model.Account account) { + ObjectNode node = objectMapper.createObjectNode(); + if (account.getApiKeyVersion() != null) { + node.put("apiKeyVersion", account.getApiKeyVersion()); + } + if (account.getCloudwatchRoleArn() != null) { + node.put("cloudwatchRoleArn", account.getCloudwatchRoleArn()); + } + if (account.getFeatures() != null) { + ArrayNode features = node.putArray("features"); + account.getFeatures().forEach(features::add); + } + if (account.getThrottleSettings() != null) { + ObjectNode throttle = node.putObject("throttleSettings"); + if (account.getThrottleSettings().getBurstLimit() != null) { + throttle.put("burstLimit", account.getThrottleSettings().getBurstLimit()); + } + if (account.getThrottleSettings().getRateLimit() != null) { + throttle.put("rateLimit", account.getThrottleSettings().getRateLimit()); + } + } + return node; + } + private ObjectNode toV2ApiNode(Api api) { ObjectNode node = objectMapper.createObjectNode(); node.put("apiId", api.getApiId()); 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 4769bfefe7..078fef83f6 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 @@ -1,20 +1,40 @@ package io.github.hectorvent.floci.services.apigateway; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.jboss.logging.Logger; + import com.fasterxml.jackson.core.type.TypeReference; + import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; -import io.github.hectorvent.floci.services.apigateway.model.*; +import io.github.hectorvent.floci.services.apigateway.model.Account; +import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource; +import io.github.hectorvent.floci.services.apigateway.model.ApiKey; +import io.github.hectorvent.floci.services.apigateway.model.Authorizer; +import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping; +import io.github.hectorvent.floci.services.apigateway.model.CustomDomain; +import io.github.hectorvent.floci.services.apigateway.model.Deployment; +import io.github.hectorvent.floci.services.apigateway.model.Integration; +import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse; +import io.github.hectorvent.floci.services.apigateway.model.MethodConfig; +import io.github.hectorvent.floci.services.apigateway.model.MethodResponse; +import io.github.hectorvent.floci.services.apigateway.model.Model; +import io.github.hectorvent.floci.services.apigateway.model.RequestValidator; +import io.github.hectorvent.floci.services.apigateway.model.RestApi; +import io.github.hectorvent.floci.services.apigateway.model.Stage; +import io.github.hectorvent.floci.services.apigateway.model.UsagePlan; +import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.parser.core.models.SwaggerParseResult; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import org.jboss.logging.Logger; - -import java.util.*; @ApplicationScoped public class ApiGatewayService { @@ -31,12 +51,12 @@ public class ApiGatewayService { private final StorageBackend usagePlanKeyStore; private final StorageBackend requestValidatorStore; private final StorageBackend modelStore; + private final StorageBackend accountStore; private final StorageBackend domainStore; private final StorageBackend basePathMappingStore; - private final RegionResolver regionResolver; @Inject - public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) { + public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config) { this.apiStore = storageFactory.create("apigateway", "apigateway-apis.json", new TypeReference<>() { }); @@ -67,13 +87,70 @@ public class ApiGatewayService { this.modelStore = storageFactory.create("apigateway", "apigateway-models.json", new TypeReference<>() { }); + this.accountStore = storageFactory.create("apigateway", "apigateway-account.json", + new TypeReference<>() { + }); this.domainStore = storageFactory.create("apigateway", "apigateway-domains.json", new TypeReference<>() { }); this.basePathMappingStore = storageFactory.create("apigateway", "apigateway-mappings.json", new TypeReference<>() { }); - this.regionResolver = regionResolver; + } + + // ──────────────────────────── Account ──────────────────────────── + + public Account getAccount(String region) { + String key = accountKey(region); + // GET must be read-only: return default account without persisting. + return accountStore.get(key).orElse(new Account()); + } + + public Account updateAccount(String region, List> patchOperations) { + Account existing = getAccount(region); + + // Work on a defensive copy so updates are atomic: validate/apply all + // operations first and only persist after success. + Account copy = new Account(); + copy.setApiKeyVersion(existing.getApiKeyVersion()); + copy.setCloudwatchRoleArn(existing.getCloudwatchRoleArn()); + copy.setFeatures(existing.getFeatures() == null ? null : List.copyOf(existing.getFeatures())); + // ThrottleSettings are immutable for our purposes here — reuse existing instance. + copy.setThrottleSettings(existing.getThrottleSettings()); + + if (patchOperations != null) { + for (Map op : patchOperations) { + String opType = op.get("op"); + String path = op.getOrDefault("path", ""); + String value = op.get("value"); + + if (!"replace".equals(opType) && !"add".equals(opType) && !"remove".equals(opType)) { + throw new AwsException("BadRequestException", + "Unsupported patch operation: " + opType, 400); + } + + switch (path) { + case "/cloudwatchRoleArn" -> { + if ("remove".equals(opType)) { + copy.setCloudwatchRoleArn(null); + } else { + copy.setCloudwatchRoleArn(value); + } + } + default -> { + if (path.startsWith("/throttleSettings")) { + throw new AwsException("BadRequestException", + "/throttleSettings value cannot be changed this way", 400); + } + throw new AwsException("BadRequestException", + "Unsupported patch path: " + path, 400); + } + } + } + } + + accountStore.put(accountKey(region), copy); + return copy; } // ──────────────────────────── REST API CRUD ──────────────────────────── @@ -717,9 +794,11 @@ public class ApiGatewayService { if (!"replace" .equals(op.get("op"))) continue; String path = op.getOrDefault("path", ""); String value = op.get("value"); - if ("/type" .equals(path)) integration.setType(value); - else if ("/httpMethod" .equals(path)) integration.setHttpMethod(value); - else if ("/uri" .equals(path)) integration.setUri(value); + switch (path) { + case "/type" -> integration.setType(value); + case "/httpMethod" -> integration.setHttpMethod(value); + case "/uri" -> integration.setUri(value); + } } } resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId)); @@ -821,7 +900,7 @@ public class ApiGatewayService { try { // Use swagger's own JSON serializer to produce clean JSON Schema modelReq.put("schema", io.swagger.v3.core.util.Json.mapper().writeValueAsString(schema)); - } catch (Exception e) { + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { modelReq.put("schema", "{}"); } createModel(region, apiId, modelReq); @@ -1051,6 +1130,10 @@ public class ApiGatewayService { return region + "::" + apiId + "::" + modelName; } + private String accountKey(String region) { + return region + "::account"; + } + private String apiKeyGlobalKey(String region, String apiKeyId) { return region + "::" + apiKeyId; } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Account.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Account.java new file mode 100644 index 0000000000..811733c94f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Account.java @@ -0,0 +1,47 @@ +package io.github.hectorvent.floci.services.apigateway.model; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Account { + + private String apiKeyVersion = "4"; + private String cloudwatchRoleArn; + private List features = new ArrayList<>(List.of("UsagePlans")); + private ThrottleSettings throttleSettings = new ThrottleSettings(); + + public String getApiKeyVersion() { + return apiKeyVersion; + } + + public void setApiKeyVersion(String apiKeyVersion) { + this.apiKeyVersion = apiKeyVersion; + } + + public String getCloudwatchRoleArn() { + return cloudwatchRoleArn; + } + + public void setCloudwatchRoleArn(String cloudwatchRoleArn) { + this.cloudwatchRoleArn = cloudwatchRoleArn; + } + + public List getFeatures() { + return features; + } + + public void setFeatures(List features) { + this.features = features != null ? features : new ArrayList<>(); + } + + public ThrottleSettings getThrottleSettings() { + return throttleSettings; + } + + public void setThrottleSettings(ThrottleSettings throttleSettings) { + this.throttleSettings = throttleSettings != null ? throttleSettings : new ThrottleSettings(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/ThrottleSettings.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/ThrottleSettings.java new file mode 100644 index 0000000000..790d7add70 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/ThrottleSettings.java @@ -0,0 +1,26 @@ +package io.github.hectorvent.floci.services.apigateway.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class ThrottleSettings { + + private Integer burstLimit = 5000; + private Double rateLimit = 10000.0; + + public Integer getBurstLimit() { + return burstLimit; + } + + public void setBurstLimit(Integer burstLimit) { + this.burstLimit = burstLimit; + } + + public Double getRateLimit() { + return rateLimit; + } + + public void setRateLimit(Double rateLimit) { + this.rateLimit = rateLimit; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java index bd65ea55bb..502a68c9a5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java @@ -1,10 +1,5 @@ package io.github.hectorvent.floci.services.iam; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.ws.rs.container.ContainerRequestContext; -import jakarta.ws.rs.core.MediaType; -import org.jboss.logging.Logger; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -14,6 +9,12 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.regex.Pattern; +import org.jboss.logging.Logger; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.MediaType; + /** * Maps (credentialScope, httpMethod, requestPath) → IAM action string. * @@ -69,6 +70,8 @@ public class IamActionRegistry { // Handled via Query-style action extraction in the filter // ── API Gateway ──────────────────────────────────────────────────────── + rule("apigateway", "GET", ".*/account$", "apigateway:GET"), + rule("apigateway", "PATCH", ".*/account$", "apigateway:PATCH"), rule("apigateway", "GET", ".*/restapis$", "apigateway:GET"), rule("apigateway", "POST", ".*/restapis$", "apigateway:POST"), rule("apigateway", "GET", ".*/restapis/.+", "apigateway:GET"), diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAccountIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAccountIntegrationTest.java new file mode 100644 index 0000000000..92d332e0d6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAccountIntegrationTest.java @@ -0,0 +1,188 @@ +package io.github.hectorvent.floci.services.apigateway; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import io.quarkus.test.junit.QuarkusTest; +import static io.restassured.RestAssured.given; +import io.restassured.http.ContentType; + +@QuarkusTest +class ApiGatewayAccountIntegrationTest { + + @BeforeEach + void resetAccount() { + String removePatch = "{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/cloudwatchRoleArn\"}]}"; + try { + given().contentType(ContentType.JSON).body(removePatch).when().patch("/account"); + } catch (Exception ignored) { + } + } + + @Test + void getAccount_returnsDefaultShape() { + given() + .when().get("/account") + .then() + .statusCode(200) + .body("apiKeyVersion", notNullValue()) + .body("features", hasItem("UsagePlans")) + .body("throttleSettings.burstLimit", equalTo(5000)) + .body("throttleSettings.rateLimit", equalTo(10000.0f)); + } + + @Test + void updateAccount_updatesCloudwatchRoleArn() { + String arn = "arn:aws:iam::123456789012:role/apigAwsProxyRole"; + String patch = """ + { + "patchOperations": [ + { + "op": "replace", + "path": "/cloudwatchRoleArn", + "value": "%s" + } + ] + } + """.formatted(arn); + + given() + .contentType(ContentType.JSON) + .body(patch) + .when().patch("/account") + .then() + .statusCode(200) + .body("cloudwatchRoleArn", equalTo(arn)); + + given() + .when().get("/account") + .then() + .statusCode(200) + .body("cloudwatchRoleArn", equalTo(arn)); + } + + @Test + void updateAccount_rejectsThrottleSettingsPatch() { + String patch = """ + { + "patchOperations": [ + { + "op": "replace", + "path": "/throttleSettings/rateLimit", + "value": "100" + } + ] + } + """; + + given() + .contentType(ContentType.JSON) + .body(patch) + .when().patch("/account") + .then() + .statusCode(400); + } + + @Test + void updateAccount_removesCloudwatchRoleArn() { + String arn = "arn:aws:iam::123456789012:role/apigAwsProxyRole"; + String setPatch = """ + { + "patchOperations": [ + { + "op": "replace", + "path": "/cloudwatchRoleArn", + "value": "%s" + } + ] + } + """.formatted(arn); + + String removePatch = """ + { + "patchOperations": [ + { + "op": "remove", + "path": "/cloudwatchRoleArn" + } + ] + } + """; + + given().contentType(ContentType.JSON).body(setPatch) + .when().patch("/account") + .then().statusCode(200).body("cloudwatchRoleArn", equalTo(arn)); + + given().contentType(ContentType.JSON).body(removePatch) + .when().patch("/account") + .then().statusCode(200).body("cloudwatchRoleArn", nullValue()); + } + + @Test + void updateAccount_rejectsUnsupportedPatchPath() { + String patch = """ + { + "patchOperations": [ + { + "op": "replace", + "path": "/apiKeyVersion", + "value": "5" + } + ] + } + """; + + given() + .contentType(ContentType.JSON) + .body(patch) + .when().patch("/account") + .then() + .statusCode(400); + } + + @Test + void updateAccount_rejectsNullPatchOperation() { + String patch = """ + { + "patchOperations": [null] + } + """; + + given() + .contentType(ContentType.JSON) + .body(patch) + .when().patch("/account") + .then() + .statusCode(400); + } + + @Test + void updateAccount_rejectsNonObjectPatchOperation() { + String patch = """ + { + "patchOperations": ["invalid"] + } + """; + + given() + .contentType(ContentType.JSON) + .body(patch) + .when().patch("/account") + .then() + .statusCode(400); + } + + @Test + void updateAccount_rejectsEmptyBody() { + given() + .contentType(ContentType.JSON) + .body("") + .when().patch("/account") + .then() + .statusCode(400); + } +}