mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): expand SAM AWS::Serverless::HttpApi to ApiGatew… (#1956)
* fix(cloudformation): preserve HttpApi routes and avoid stage-id collisions expandServerlessHttpApi dropped the SAM DefinitionBody, so route-bearing AWS::Serverless::HttpApi templates expanded into an ApiGatewayV2 API with no routes. Carry DefinitionBody over as the ApiGatewayV2::Api Body. It also synthesized a '<id>Stage' resource with resources.set(...), silently overwriting any resource the user already declared under that logical id. Skip synthesis (and warn) when the id is taken instead of clobbering the user's resource. Tests cover both: DefinitionBody preserved as Body, and a user-declared <id>Stage left intact. * fix(cloudformation): provision SAM HttpApi routes * fix(cloudformation): reconcile SAM HttpApi routes * fix(cloudformation): stage HttpApi route replacements * fix(cloudformation): roll back failed HttpApi replacements * fix(cloudformation): resolve intrinsic HttpApi definitions * fix(cloudformation): roll back HttpApi definition removal * fix(cloudformation): retain failed HttpApi route cleanup * test(cloudformation): align HttpApi fixture with main * chore(ci): retrigger flaky Neptune test * fix(apigatewayv2): prevent duplicate routes on rollback * fix(cloudformation): persist failed cleanup ownership * fix(cloudformation): preserve OpenAPI route authorization * fix(cloudformation): reject unsupported auth conjunctions * fix(apigatewayv2): preserve rollback and auth semantics * fix(cloudformation): surface incomplete update rollback * fix(cloudformation): merge overlapping SAM HTTP API routes * fix(cloudformation): preserve merged route authorization * test(cloudformation): document SAM auth defaults
This commit is contained in:
1 parent
0e3391cac2
commit
6fa53abd7c
9 files changed
+2190
-8
No files matched your search
+80
@@ -1,5 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import jakarta.inject.Inject;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
@@ -7,13 +11,22 @@ import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class ApiGatewayV2IntegrationTest {
|
||||
|
||||
@Inject
|
||||
ApiGatewayV2Service apiGatewayV2Service;
|
||||
|
||||
private static String apiId;
|
||||
private static String routeId;
|
||||
private static String integrationId;
|
||||
@@ -154,6 +167,60 @@ class ApiGatewayV2IntegrationTest {
|
||||
.body("items.routeId", hasItem(routeId));
|
||||
}
|
||||
|
||||
@Test @Order(23)
|
||||
void duplicateRouteKeyIsRejected() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"routeKey":"GET /users","target":"integrations/%s"}
|
||||
""".formatted(integrationId))
|
||||
.when().post("/v2/apis/" + apiId + "/routes")
|
||||
.then()
|
||||
.statusCode(409);
|
||||
}
|
||||
|
||||
@Test @Order(24)
|
||||
void restoringRouteRemovesAConflictingReplacement() {
|
||||
Route oldRoute = new Route();
|
||||
oldRoute.setRouteId("restored-route");
|
||||
oldRoute.setRouteKey("GET /users");
|
||||
oldRoute.setAuthorizationType("NONE");
|
||||
oldRoute.setAuthorizationScopes(List.of("read:users"));
|
||||
oldRoute.setTarget("integrations/" + integrationId);
|
||||
|
||||
String replacementRouteId = routeId;
|
||||
apiGatewayV2Service.restoreRoute("us-east-1", apiId, oldRoute, Set.of(replacementRouteId));
|
||||
|
||||
assertEquals(1, apiGatewayV2Service.getRoutes("us-east-1", apiId).stream()
|
||||
.filter(route -> "GET /users".equals(route.getRouteKey()))
|
||||
.count());
|
||||
assertEquals("restored-route",
|
||||
apiGatewayV2Service.findRouteByKey("us-east-1", apiId, "GET /users").getRouteId());
|
||||
assertEquals(List.of("read:users"),
|
||||
apiGatewayV2Service.getRoute("us-east-1", apiId, "restored-route").getAuthorizationScopes());
|
||||
assertThrows(AwsException.class,
|
||||
() -> apiGatewayV2Service.getRoute("us-east-1", apiId, replacementRouteId));
|
||||
routeId = oldRoute.getRouteId();
|
||||
}
|
||||
|
||||
@Test @Order(25)
|
||||
void restoringRouteDoesNotDeleteAnIndependentConflict() {
|
||||
Route independent = apiGatewayV2Service.createRoute("us-east-1", apiId,
|
||||
Map.of("routeKey", "GET /independent"));
|
||||
Route snapshot = new Route();
|
||||
snapshot.setRouteId("rollback-snapshot");
|
||||
snapshot.setRouteKey("GET /independent");
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> apiGatewayV2Service.restoreRoute("us-east-1", apiId, snapshot, Set.of("other-route")));
|
||||
assertEquals(independent.getRouteId(), apiGatewayV2Service
|
||||
.findRouteByKey("us-east-1", apiId, "GET /independent").getRouteId());
|
||||
assertThrows(AwsException.class,
|
||||
() -> apiGatewayV2Service.getRoute("us-east-1", apiId, snapshot.getRouteId()));
|
||||
|
||||
apiGatewayV2Service.deleteRoute("us-east-1", apiId, independent.getRouteId());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Authorizers ────────────────────────────
|
||||
|
||||
@Test @Order(30)
|
||||
@@ -198,6 +265,19 @@ class ApiGatewayV2IntegrationTest {
|
||||
.body("items.authorizerId", hasItem(authorizerId));
|
||||
}
|
||||
|
||||
@Test @Order(33)
|
||||
void restoreAuthorizerPreservesEnforcementConfiguration() {
|
||||
Authorizer snapshot = apiGatewayV2Service.getAuthorizer("us-east-1", apiId, authorizerId);
|
||||
apiGatewayV2Service.deleteAuthorizer("us-east-1", apiId, authorizerId);
|
||||
apiGatewayV2Service.restoreAuthorizer("us-east-1", apiId, snapshot);
|
||||
|
||||
Authorizer restored = apiGatewayV2Service.getAuthorizer("us-east-1", apiId, authorizerId);
|
||||
assertEquals("JWT", restored.getAuthorizerType());
|
||||
assertEquals(List.of("$request.header.Authorization"), restored.getIdentitySource());
|
||||
assertEquals("https://example.com", restored.getJwtConfiguration().issuer());
|
||||
assertEquals(List.of("api"), restored.getJwtConfiguration().audience());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Deployments ────────────────────────────
|
||||
|
||||
@Test @Order(40)
|
||||
|
||||
+511
@@ -0,0 +1,511 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.Route;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ApiGatewayV2CfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String API_ID = "api-123";
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private ApiGatewayV2Service apiGatewayV2Service;
|
||||
private CloudFormationResourceProvisioner provisioner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
apiGatewayV2Service = mock(ApiGatewayV2Service.class);
|
||||
provisioner = new CloudFormationResourceProvisioner(
|
||||
null, null, null, null, null, null, null, null, null, null,
|
||||
null, apiGatewayV2Service, null, null, null, null, mapper,
|
||||
null, null, null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null,
|
||||
new CloudFormationResourceRegistry(java.util.List.of()));
|
||||
|
||||
Api api = new Api();
|
||||
api.setApiId(API_ID);
|
||||
api.setApiEndpoint("https://" + API_ID + ".execute-api.localhost");
|
||||
when(apiGatewayV2Service.createApi(eq(REGION), anyMap())).thenReturn(api);
|
||||
when(apiGatewayV2Service.updateApi(eq(REGION), eq(API_ID), anyMap())).thenReturn(api);
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresExistingRoutesAndCleansPartialReplacementWhenRouteCreationFails() throws Exception {
|
||||
Route oldRoute = route("old-route", "GET /before");
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = invocation.getArgument(2);
|
||||
return switch ((String) request.get("routeKey")) {
|
||||
case "GET /before" -> oldRoute;
|
||||
case "GET /first" -> route("partial-route", "GET /first");
|
||||
case "GET /second" -> throw new AwsException("InternalFailure", "simulated route failure", 500);
|
||||
default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey"));
|
||||
};
|
||||
});
|
||||
when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-route")).thenReturn(oldRoute);
|
||||
|
||||
StackResource original = provision(body("""
|
||||
{"paths":{"/before":{"get":{}}}}
|
||||
"""), null, Map.of());
|
||||
|
||||
StackResource replacement = provision(body("""
|
||||
{"paths":{"/first":{"get":{}},"/second":{"get":{}}}}
|
||||
"""), original.getPhysicalId(), original.getAttributes());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", original.getStatus());
|
||||
assertEquals("CREATE_FAILED", replacement.getStatus());
|
||||
assertEquals("old-route", replacement.getAttributes().get("__FlociApiGatewayV2BodyRouteIds"));
|
||||
verify(apiGatewayV2Service).deleteRoute(REGION, API_ID, "old-route");
|
||||
verify(apiGatewayV2Service).deleteRoute(REGION, API_ID, "partial-route");
|
||||
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldRoute, java.util.List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainsPartialRoutesWhenMaterializationCleanupFails() throws Exception {
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = invocation.getArgument(2);
|
||||
return switch ((String) request.get("routeKey")) {
|
||||
case "GET /first" -> route("partial-route", "GET /first");
|
||||
case "GET /second" -> throw new AwsException("InternalFailure", "simulated route failure", 500);
|
||||
default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey"));
|
||||
};
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
throw new AwsException("InternalFailure", "simulated cleanup failure", 500);
|
||||
}).when(apiGatewayV2Service).deleteRoute(REGION, API_ID, "partial-route");
|
||||
|
||||
StackResource failed = provision(body("""
|
||||
{"paths":{"/first":{"get":{}},"/second":{"get":{}}}}
|
||||
"""), null, Map.of());
|
||||
|
||||
assertEquals("CREATE_FAILED", failed.getStatus());
|
||||
assertEquals("partial-route", failed.getAttributes().get("__FlociApiGatewayV2BodyRouteIds"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresExistingRouteWhenReplacementCleanupKeepsAConflictingRoute() throws Exception {
|
||||
Route oldRoute = route("old-route", "GET /same");
|
||||
Route replacementRoute = route("replacement-route", "GET /same");
|
||||
AtomicInteger sameRouteCreations = new AtomicInteger();
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = invocation.getArgument(2);
|
||||
return switch ((String) request.get("routeKey")) {
|
||||
case "GET /same" -> sameRouteCreations.getAndIncrement() == 0 ? oldRoute : replacementRoute;
|
||||
case "GET /second" -> throw new AwsException("InternalFailure", "simulated route failure", 500);
|
||||
default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey"));
|
||||
};
|
||||
});
|
||||
when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-route")).thenReturn(oldRoute);
|
||||
doAnswer(invocation -> {
|
||||
if ("replacement-route".equals(invocation.getArgument(2))) {
|
||||
throw new AwsException("InternalFailure", "simulated cleanup failure", 500);
|
||||
}
|
||||
return null;
|
||||
}).when(apiGatewayV2Service).deleteRoute(eq(REGION), eq(API_ID), anyString());
|
||||
|
||||
StackResource original = provision(body("""
|
||||
{"paths":{"/same":{"get":{}}}}
|
||||
"""), null, Map.of());
|
||||
StackResource replacement = provision(body("""
|
||||
{"paths":{"/same":{"get":{}},"/second":{"get":{}}}}
|
||||
"""), original.getPhysicalId(), original.getAttributes());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", original.getStatus());
|
||||
assertEquals("CREATE_FAILED", replacement.getStatus());
|
||||
assertEquals("old-route,replacement-route",
|
||||
replacement.getAttributes().get("__FlociApiGatewayV2BodyRouteIds"));
|
||||
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldRoute,
|
||||
java.util.List.of("replacement-route"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergesFailedUpdateRouteAndIntegrationOwnershipIntoCommittedMetadata() {
|
||||
StackResource previous = new StackResource();
|
||||
previous.setResourceType("AWS::ApiGatewayV2::Api");
|
||||
previous.getAttributes().put("__FlociApiGatewayV2BodyRouteIds", "old-route");
|
||||
previous.getAttributes().put("__FlociApiGatewayV2BodyIntegrationIds", "old-integration");
|
||||
previous.getAttributes().put("__FlociApiGatewayV2BodyAuthorizerIds", "old-authorizer");
|
||||
|
||||
StackResource attempted = new StackResource();
|
||||
attempted.setResourceType("AWS::ApiGatewayV2::Api");
|
||||
attempted.getAttributes().put("__FlociApiGatewayV2BodyRouteIds",
|
||||
"old-route,surviving-route");
|
||||
attempted.getAttributes().put("__FlociApiGatewayV2BodyIntegrationIds",
|
||||
"old-integration,surviving-integration");
|
||||
attempted.getAttributes().put("__FlociApiGatewayV2BodyAuthorizerIds",
|
||||
"old-authorizer,surviving-authorizer");
|
||||
|
||||
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
|
||||
|
||||
assertEquals("old-route,surviving-route",
|
||||
previous.getAttributes().get("__FlociApiGatewayV2BodyRouteIds"));
|
||||
assertEquals("old-integration,surviving-integration",
|
||||
previous.getAttributes().get("__FlociApiGatewayV2BodyIntegrationIds"));
|
||||
assertEquals("old-authorizer,surviving-authorizer",
|
||||
previous.getAttributes().get("__FlociApiGatewayV2BodyAuthorizerIds"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void materializesInheritedJwtSecurityAndHonorsOperationOptOut() throws Exception {
|
||||
Authorizer authorizer = new Authorizer();
|
||||
authorizer.setAuthorizerId("body-authorizer");
|
||||
when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap()))
|
||||
.thenReturn(authorizer);
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = invocation.getArgument(2);
|
||||
return route("route-" + request.get("routeKey"), (String) request.get("routeKey"));
|
||||
});
|
||||
|
||||
StackResource resource = provision(body("""
|
||||
{
|
||||
"components":{"securitySchemes":{"JwtAuth":{
|
||||
"type":"oauth2",
|
||||
"x-amazon-apigateway-authorizer":{
|
||||
"type":"jwt",
|
||||
"identitySource":"$request.header.Authorization",
|
||||
"jwtConfiguration":{
|
||||
"issuer":"https://issuer.example.com",
|
||||
"audience":["client-id"]
|
||||
}
|
||||
}
|
||||
}}},
|
||||
"security":[{"JwtAuth":["orders/read"]}],
|
||||
"paths":{
|
||||
"/protected":{"get":{}},
|
||||
"/public":{"get":{"security":[]}}
|
||||
}
|
||||
}
|
||||
"""), null, Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
assertEquals("body-authorizer",
|
||||
resource.getAttributes().get("__FlociApiGatewayV2BodyAuthorizerIds"));
|
||||
verify(apiGatewayV2Service).createAuthorizer(eq(REGION), eq(API_ID), argThat(request ->
|
||||
"JwtAuth".equals(request.get("name"))
|
||||
&& "JWT".equals(request.get("authorizerType"))
|
||||
&& "$request.header.Authorization".equals(request.get("identitySource"))));
|
||||
verify(apiGatewayV2Service).createRoute(eq(REGION), eq(API_ID), argThat(request ->
|
||||
"GET /protected".equals(request.get("routeKey"))
|
||||
&& "JWT".equals(request.get("authorizationType"))
|
||||
&& "body-authorizer".equals(request.get("authorizerId"))
|
||||
&& java.util.List.of("orders/read").equals(request.get("authorizationScopes"))));
|
||||
verify(apiGatewayV2Service).createRoute(eq(REGION), eq(API_ID), argThat(request ->
|
||||
"GET /public".equals(request.get("routeKey"))
|
||||
&& "NONE".equals(request.get("authorizationType"))
|
||||
&& !request.containsKey("authorizerId")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsProtectedOperationWhenSecuritySchemeCannotBeResolved() throws Exception {
|
||||
StackResource resource = provision(body("""
|
||||
{
|
||||
"security":[{"MissingAuthorizer":[]}],
|
||||
"paths":{"/protected":{"get":{}}}
|
||||
}
|
||||
"""), null, Map.of());
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertEquals("Protected operation GET /protected references unsupported security scheme 'MissingAuthorizer'",
|
||||
resource.getStatusReason());
|
||||
verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAndSecurityRequirementInsteadOfApplyingOnlyOneScheme() throws Exception {
|
||||
Authorizer first = new Authorizer();
|
||||
first.setAuthorizerId("first-authorizer");
|
||||
Authorizer second = new Authorizer();
|
||||
second.setAuthorizerId("second-authorizer");
|
||||
when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap()))
|
||||
.thenReturn(first, second);
|
||||
|
||||
StackResource resource = provision(body("""
|
||||
{
|
||||
"components":{"securitySchemes":{
|
||||
"First":{"x-amazon-apigateway-authorizer":{
|
||||
"type":"jwt","jwtConfiguration":{"issuer":"https://first.example.com"}
|
||||
}},
|
||||
"Second":{"x-amazon-apigateway-authorizer":{
|
||||
"type":"jwt","jwtConfiguration":{"issuer":"https://second.example.com"}
|
||||
}}
|
||||
}},
|
||||
"security":[{"First":[],"Second":[]}],
|
||||
"paths":{"/protected":{"get":{}}}
|
||||
}
|
||||
"""), null, Map.of());
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), anyMap());
|
||||
verify(apiGatewayV2Service).deleteAuthorizer(REGION, API_ID, "first-authorizer");
|
||||
verify(apiGatewayV2Service).deleteAuthorizer(REGION, API_ID, "second-authorizer");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnrepresentableSecurityOrAlternativesInsteadOfChoosingOne() throws Exception {
|
||||
StackResource resource = provision(body("""
|
||||
{
|
||||
"security":[{"First":[]},{"Second":[]}],
|
||||
"paths":{"/protected":{"get":{}}}
|
||||
}
|
||||
"""), null, Map.of());
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void honorsAnonymousAlternativeInSecurityOrList() throws Exception {
|
||||
Authorizer authorizer = new Authorizer();
|
||||
authorizer.setAuthorizerId("optional-authorizer");
|
||||
when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap()))
|
||||
.thenReturn(authorizer);
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap()))
|
||||
.thenReturn(route("optional-route", "GET /optional"));
|
||||
|
||||
StackResource resource = provision(body("""
|
||||
{
|
||||
"components":{"securitySchemes":{"JwtAuth":{
|
||||
"x-amazon-apigateway-authorizer":{
|
||||
"type":"jwt","jwtConfiguration":{"issuer":"https://issuer.example.com"}
|
||||
}
|
||||
}}},
|
||||
"security":[{"JwtAuth":[]},{}],
|
||||
"paths":{"/optional":{"get":{}}}
|
||||
}
|
||||
"""), null, Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
verify(apiGatewayV2Service).createRoute(eq(REGION), eq(API_ID), argThat(request ->
|
||||
"GET /optional".equals(request.get("routeKey"))
|
||||
&& "NONE".equals(request.get("authorizationType"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void materializesRequestAuthorizerSecurityAsCustomAuthorization() throws Exception {
|
||||
Authorizer authorizer = new Authorizer();
|
||||
authorizer.setAuthorizerId("request-authorizer");
|
||||
when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap()))
|
||||
.thenReturn(authorizer);
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap()))
|
||||
.thenReturn(route("protected-route", "POST /protected"));
|
||||
|
||||
StackResource resource = provision(body("""
|
||||
{
|
||||
"components":{"securitySchemes":{"RequestAuth":{
|
||||
"type":"apiKey",
|
||||
"x-amazon-apigateway-authorizer":{
|
||||
"type":"request",
|
||||
"identitySource":["$request.header.Authorization"],
|
||||
"authorizerUri":"arn:aws:apigateway:us-east-1:lambda:path/functions/auth/invocations",
|
||||
"authorizerPayloadFormatVersion":"2.0",
|
||||
"enableSimpleResponses":true
|
||||
}
|
||||
}}},
|
||||
"paths":{"/protected":{"post":{"security":[{"RequestAuth":[]}]}}}
|
||||
}
|
||||
"""), null, Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
verify(apiGatewayV2Service).createAuthorizer(eq(REGION), eq(API_ID), argThat(request ->
|
||||
"REQUEST".equals(request.get("authorizerType"))
|
||||
&& Boolean.TRUE.equals(request.get("enableSimpleResponses"))));
|
||||
verify(apiGatewayV2Service).createRoute(eq(REGION), eq(API_ID), argThat(request ->
|
||||
"POST /protected".equals(request.get("routeKey"))
|
||||
&& "CUSTOM".equals(request.get("authorizationType"))
|
||||
&& "request-authorizer".equals(request.get("authorizerId"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresBodyAuthorizerWhenSecuredRouteReplacementFails() throws Exception {
|
||||
Authorizer oldAuthorizer = new Authorizer();
|
||||
oldAuthorizer.setAuthorizerId("old-authorizer");
|
||||
Authorizer replacementAuthorizer = new Authorizer();
|
||||
replacementAuthorizer.setAuthorizerId("replacement-authorizer");
|
||||
when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap()))
|
||||
.thenReturn(oldAuthorizer, replacementAuthorizer);
|
||||
|
||||
Route oldRoute = route("old-route", "GET /protected");
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap()))
|
||||
.thenReturn(oldRoute)
|
||||
.thenThrow(new AwsException("InternalFailure", "simulated route failure", 500));
|
||||
when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-route")).thenReturn(oldRoute);
|
||||
when(apiGatewayV2Service.getAuthorizer(REGION, API_ID, "old-authorizer"))
|
||||
.thenReturn(oldAuthorizer);
|
||||
|
||||
String securedBody = """
|
||||
{
|
||||
"components":{"securitySchemes":{"JwtAuth":{
|
||||
"x-amazon-apigateway-authorizer":{
|
||||
"type":"jwt",
|
||||
"jwtConfiguration":{"issuer":"https://issuer.example.com"}
|
||||
}
|
||||
}}},
|
||||
"security":[{"JwtAuth":[]}],
|
||||
"paths":{"/protected":{"get":{}}}
|
||||
}
|
||||
""";
|
||||
StackResource original = provision(body(securedBody), null, Map.of());
|
||||
StackResource replacement = provision(body(securedBody), original.getPhysicalId(),
|
||||
original.getAttributes());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", original.getStatus());
|
||||
assertEquals("CREATE_FAILED", replacement.getStatus());
|
||||
assertEquals("old-authorizer",
|
||||
replacement.getAttributes().get("__FlociApiGatewayV2BodyAuthorizerIds"));
|
||||
verify(apiGatewayV2Service).deleteAuthorizer(REGION, API_ID, "old-authorizer");
|
||||
verify(apiGatewayV2Service).deleteAuthorizer(REGION, API_ID, "replacement-authorizer");
|
||||
verify(apiGatewayV2Service).restoreAuthorizer(REGION, API_ID, oldAuthorizer);
|
||||
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldRoute, java.util.List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSigV4SecurityUntilHttpApiIamEnforcementIsSupported() throws Exception {
|
||||
StackResource resource = provision(body("""
|
||||
{
|
||||
"components":{"securitySchemes":{"SigV4":{
|
||||
"type":"apiKey",
|
||||
"x-amazon-apigateway-authtype":"awsSigv4"
|
||||
}}},
|
||||
"security":[{"SigV4":[]}],
|
||||
"paths":{"/iam":{"get":{}}}
|
||||
}
|
||||
"""), null, Map.of());
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
verify(apiGatewayV2Service, never()).createAuthorizer(eq(REGION), eq(API_ID), anyMap());
|
||||
verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresExistingRoutesWhenOldRouteDeletionFails() throws Exception {
|
||||
Route oldOne = route("old-one", "GET /before-one");
|
||||
Route oldTwo = route("old-two", "GET /before-two");
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = invocation.getArgument(2);
|
||||
return switch ((String) request.get("routeKey")) {
|
||||
case "GET /before-one" -> oldOne;
|
||||
case "GET /before-two" -> oldTwo;
|
||||
case "GET /after" -> route("replacement-route", "GET /after");
|
||||
default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey"));
|
||||
};
|
||||
});
|
||||
when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-one")).thenReturn(oldOne);
|
||||
when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-two")).thenReturn(oldTwo);
|
||||
doAnswer(invocation -> {
|
||||
if ("old-two".equals(invocation.getArgument(2))) {
|
||||
throw new AwsException("InternalFailure", "simulated delete failure", 500);
|
||||
}
|
||||
return null;
|
||||
}).when(apiGatewayV2Service).deleteRoute(eq(REGION), eq(API_ID), anyString());
|
||||
|
||||
StackResource original = provision(body("""
|
||||
{"paths":{"/before-one":{"get":{}},"/before-two":{"get":{}}}}
|
||||
"""), null, Map.of());
|
||||
|
||||
StackResource replacement = provision(body("""
|
||||
{"paths":{"/after":{"get":{}}}}
|
||||
"""), original.getPhysicalId(), original.getAttributes());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", original.getStatus());
|
||||
assertEquals("CREATE_FAILED", replacement.getStatus());
|
||||
assertEquals("old-one,old-two", replacement.getAttributes().get("__FlociApiGatewayV2BodyRouteIds"));
|
||||
verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID),
|
||||
argThat(request -> "GET /after".equals(request.get("routeKey"))));
|
||||
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldOne, java.util.List.of());
|
||||
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldTwo, java.util.List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresExistingRoutesWhenDefinitionRemovalFails() throws Exception {
|
||||
Route oldOne = route("old-one", "GET /before-one");
|
||||
Route oldTwo = route("old-two", "GET /before-two");
|
||||
when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = invocation.getArgument(2);
|
||||
return switch ((String) request.get("routeKey")) {
|
||||
case "GET /before-one" -> oldOne;
|
||||
case "GET /before-two" -> oldTwo;
|
||||
default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey"));
|
||||
};
|
||||
});
|
||||
when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-one")).thenReturn(oldOne);
|
||||
when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-two")).thenReturn(oldTwo);
|
||||
doAnswer(invocation -> {
|
||||
if ("old-two".equals(invocation.getArgument(2))) {
|
||||
throw new AwsException("InternalFailure", "simulated delete failure", 500);
|
||||
}
|
||||
return null;
|
||||
}).when(apiGatewayV2Service).deleteRoute(eq(REGION), eq(API_ID), anyString());
|
||||
|
||||
StackResource original = provision(body("""
|
||||
{"paths":{"/before-one":{"get":{}},"/before-two":{"get":{}}}}
|
||||
"""), null, Map.of());
|
||||
|
||||
StackResource removal = provision(propertiesWithoutBody(), original.getPhysicalId(),
|
||||
original.getAttributes());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", original.getStatus());
|
||||
assertEquals("CREATE_FAILED", removal.getStatus());
|
||||
assertEquals("old-one,old-two", removal.getAttributes().get("__FlociApiGatewayV2BodyRouteIds"));
|
||||
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldOne, java.util.List.of());
|
||||
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldTwo, java.util.List.of());
|
||||
}
|
||||
|
||||
private StackResource provision(JsonNode properties, String existingPhysicalId,
|
||||
Map<String, String> existingAttributes) {
|
||||
return provisioner.provision("HttpApi", "AWS::ApiGatewayV2::Api", properties, engine(), REGION,
|
||||
"000000000000", "test-stack", existingPhysicalId, existingAttributes);
|
||||
}
|
||||
|
||||
private JsonNode body(String body) throws Exception {
|
||||
return mapper.readTree("""
|
||||
{"Name":"test-api","ProtocolType":"HTTP","Body":%s}
|
||||
""".formatted(body));
|
||||
}
|
||||
|
||||
private JsonNode propertiesWithoutBody() throws Exception {
|
||||
return mapper.readTree("""
|
||||
{"Name":"test-api","ProtocolType":"HTTP"}
|
||||
""");
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engine() {
|
||||
return new CloudFormationTemplateEngine("000000000000", REGION, "test-stack", "stack/id",
|
||||
Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,
|
||||
(Function<String, String>) name -> null);
|
||||
}
|
||||
|
||||
private static Route route(String id, String routeKey) {
|
||||
Route route = new Route();
|
||||
route.setRouteId(id);
|
||||
route.setRouteKey(routeKey);
|
||||
return route;
|
||||
}
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doCallRealMethod;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationApiGatewayV2CleanupIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ROUTE_IDS_ATTR = "__FlociApiGatewayV2BodyRouteIds";
|
||||
|
||||
@InjectSpy
|
||||
ApiGatewayV2Service apiGatewayV2Service;
|
||||
|
||||
@Inject
|
||||
CloudFormationService cloudFormationService;
|
||||
|
||||
private String stackName;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteStack() {
|
||||
if (stackName != null) {
|
||||
doCallRealMethod().when(apiGatewayV2Service)
|
||||
.deleteRoute(anyString(), anyString(), anyString());
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedUpdatePersistsOwnershipOfAReplacementThatCleanupCouldNotDelete() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
stackName = "http-api-cleanup-" + suffix;
|
||||
String apiName = "http-api-cleanup-" + suffix;
|
||||
|
||||
createStack(httpApiTemplate(apiName, List.of("/before")));
|
||||
waitForStackStatus("CREATE_COMPLETE");
|
||||
String apiId = apiIdForName(apiName);
|
||||
String oldRouteId = apiGatewayV2Service.findRouteByKey(REGION, apiId, "GET /before").getRouteId();
|
||||
|
||||
AtomicReference<String> survivingRouteId = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = invocation.getArgument(2);
|
||||
if ("GET /fail".equals(request.get("routeKey"))) {
|
||||
throw new AwsException("InternalFailure", "simulated route failure", 500);
|
||||
}
|
||||
Route route = (Route) invocation.callRealMethod();
|
||||
if ("GET /survivor".equals(route.getRouteKey())) {
|
||||
survivingRouteId.set(route.getRouteId());
|
||||
}
|
||||
return route;
|
||||
}).when(apiGatewayV2Service).createRoute(eq(REGION), eq(apiId), anyMap());
|
||||
doAnswer(invocation -> {
|
||||
String routeId = invocation.getArgument(2);
|
||||
if (routeId.equals(survivingRouteId.get())) {
|
||||
throw new AwsException("InternalFailure", "simulated cleanup failure", 500);
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
}).when(apiGatewayV2Service).deleteRoute(eq(REGION), eq(apiId), anyString());
|
||||
|
||||
updateStack(httpApiTemplate(apiName, List.of("/survivor", "/fail")));
|
||||
waitForStackStatus("UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
StackResource persisted = cloudFormationService.describeStacks(stackName, REGION)
|
||||
.getFirst().getResources().get("HttpApi");
|
||||
assertEquals("CREATE_COMPLETE", persisted.getStatus());
|
||||
assertTrue(Arrays.asList(persisted.getAttributes().get(ROUTE_IDS_ATTR).split(","))
|
||||
.containsAll(List.of(oldRouteId, survivingRouteId.get())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedSnapshotRestorationMarksUpdateRollbackFailed() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
stackName = "http-api-restore-failure-" + suffix;
|
||||
String apiName = "http-api-restore-failure-" + suffix;
|
||||
|
||||
createStack(httpApiTemplate(apiName, List.of("/before")));
|
||||
waitForStackStatus("CREATE_COMPLETE");
|
||||
String apiId = apiIdForName(apiName);
|
||||
String oldRouteId = apiGatewayV2Service.findRouteByKey(REGION, apiId, "GET /before").getRouteId();
|
||||
|
||||
AtomicReference<String> independentRouteId = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = invocation.getArgument(2);
|
||||
if ("GET /fail".equals(request.get("routeKey"))) {
|
||||
Route independent = apiGatewayV2Service.createRoute(
|
||||
REGION, apiId, Map.of("routeKey", "GET /before"));
|
||||
independentRouteId.set(independent.getRouteId());
|
||||
throw new AwsException("InternalFailure", "simulated route failure", 500);
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
}).when(apiGatewayV2Service).createRoute(eq(REGION), eq(apiId), anyMap());
|
||||
|
||||
updateStack(httpApiTemplate(apiName, List.of("/fail")));
|
||||
waitForStackStatus("UPDATE_ROLLBACK_FAILED");
|
||||
|
||||
Route independent = apiGatewayV2Service.findRouteByKey(REGION, apiId, "GET /before");
|
||||
assertEquals(independentRouteId.get(), independent.getRouteId());
|
||||
assertThrows(AwsException.class,
|
||||
() -> apiGatewayV2Service.getRoute(REGION, apiId, oldRouteId));
|
||||
}
|
||||
|
||||
private void createStack(String template) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void updateStack(String template) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void waitForStackStatus(String expected) {
|
||||
for (int attempt = 0; attempt < 100; attempt++) {
|
||||
String status = cloudFormationService.describeStacks(stackName, REGION).getFirst().getStatus();
|
||||
if (expected.equals(status)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(25);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError("Interrupted while waiting for stack status", e);
|
||||
}
|
||||
}
|
||||
throw new AssertionError("Stack did not reach " + expected);
|
||||
}
|
||||
|
||||
private static String apiIdForName(String apiName) {
|
||||
return given()
|
||||
.when()
|
||||
.get("/v2/apis")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.path("items.find { it.name == '" + apiName + "' }.apiId");
|
||||
}
|
||||
|
||||
private static String httpApiTemplate(String apiName, List<String> paths) {
|
||||
String pathDefinitions = paths.stream()
|
||||
.map(path -> "\"" + path + "\":{\"get\":{}}")
|
||||
.collect(java.util.stream.Collectors.joining(","));
|
||||
return """
|
||||
{"AWSTemplateFormatVersion":"2010-09-09",
|
||||
"Transform":"AWS::Serverless-2016-10-31",
|
||||
"Resources":{"HttpApi":{"Type":"AWS::Serverless::HttpApi","Properties":{
|
||||
"Name":"%s","DefinitionBody":{"openapi":"3.0.1","paths":{%s}}
|
||||
}}}}
|
||||
""".formatted(apiName, pathDefinitions);
|
||||
}
|
||||
}
|
||||
+269
@@ -13,7 +13,10 @@ import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
@QuarkusTest
|
||||
@@ -466,6 +469,272 @@ class SamTransformIntegrationTest {
|
||||
assertThat(resourcesXml, not(containsString("AWS::Serverless::Api")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void samHttpApi_definitionBodyCreatesApiGatewayV2Routes() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "sam-http-api-" + suffix;
|
||||
String apiName = "sam-http-api-" + suffix;
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: AWS::Serverless-2016-10-31
|
||||
Resources:
|
||||
HttpApi:
|
||||
Type: AWS::Serverless::HttpApi
|
||||
Properties:
|
||||
Name: %s
|
||||
DefinitionBody:
|
||||
openapi: 3.0.1
|
||||
paths:
|
||||
/hello:
|
||||
get: {}
|
||||
/widgets:
|
||||
post: {}
|
||||
""".formatted(apiName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
waitForStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
String apiId = given()
|
||||
.when()
|
||||
.get("/v2/apis")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("items.find { it.name == '" + apiName + "' }.protocolType", equalTo("HTTP"))
|
||||
.extract()
|
||||
.path("items.find { it.name == '" + apiName + "' }.apiId");
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v2/apis/" + apiId + "/routes")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("items.routeKey", hasItems("GET /hello", "POST /widgets"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void samHttpApi_matchingDefinitionBodyAndFunctionEventCreateOneIntegratedRoute() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "sam-http-api-overlap-" + suffix;
|
||||
String apiName = "sam-http-api-overlap-" + suffix;
|
||||
String functionName = "sam-http-overlap-fn-" + suffix;
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: AWS::Serverless-2016-10-31
|
||||
Resources:
|
||||
HttpApi:
|
||||
Type: AWS::Serverless::HttpApi
|
||||
Properties:
|
||||
Name: %s
|
||||
Auth:
|
||||
DefaultAuthorizer: JwtAuth
|
||||
Authorizers:
|
||||
JwtAuth:
|
||||
IdentitySource: '$request.header.Authorization'
|
||||
AuthorizationScopes: [read:items]
|
||||
JwtConfiguration:
|
||||
issuer: https://issuer.example.com
|
||||
audience: [items-client]
|
||||
DefinitionBody:
|
||||
openapi: 3.0.1
|
||||
info: {title: overlap, version: '1.0'}
|
||||
components: {}
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
responses: {'200': {description: ok}}
|
||||
Handler:
|
||||
Type: AWS::Serverless::Function
|
||||
Properties:
|
||||
FunctionName: %s
|
||||
Runtime: python3.12
|
||||
Handler: index.handler
|
||||
InlineCode: 'def handler(e,c): return {}'
|
||||
Events:
|
||||
Api:
|
||||
Type: HttpApi
|
||||
Properties:
|
||||
ApiId: {Ref: HttpApi}
|
||||
Path: /items
|
||||
Method: GET
|
||||
""".formatted(apiName, functionName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
waitForStackStatus(stackName, "CREATE_COMPLETE");
|
||||
String apiId = apiIdForName(apiName);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v2/apis/" + apiId + "/routes")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("items.size()", equalTo(1))
|
||||
.body("items[0].routeKey", equalTo("GET /items"))
|
||||
.body("items[0].authorizationType", equalTo("JWT"))
|
||||
.body("items[0].authorizationScopes", hasItem("read:items"))
|
||||
.body("items[0].authorizerId", notNullValue())
|
||||
.body("items[0].target", containsString("integrations/"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v2/apis/" + apiId + "/integrations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("items.size()", equalTo(1))
|
||||
.body("items[0].integrationUri", containsString(functionName));
|
||||
}
|
||||
|
||||
@Test
|
||||
void samHttpApi_intrinsicDefinitionUriCreatesApiGatewayV2Routes() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "sam-http-api-uri-" + suffix;
|
||||
String apiName = "sam-http-api-uri-" + suffix;
|
||||
String bucketName = "sam-http-api-spec-" + suffix;
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.put("/" + bucketName)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"openapi":"3.0.1","paths":{"/from-uri":{"get":{}}}}
|
||||
""")
|
||||
.when()
|
||||
.put("/" + bucketName + "/openapi.json")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String template = """
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: AWS::Serverless-2016-10-31
|
||||
Resources:
|
||||
HttpApi:
|
||||
Type: AWS::Serverless::HttpApi
|
||||
Properties:
|
||||
Name: %s
|
||||
DefinitionUri:
|
||||
Fn::Sub: s3://%s/openapi.json
|
||||
""".formatted(apiName, bucketName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
waitForStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
String apiId = apiIdForName(apiName);
|
||||
given()
|
||||
.when()
|
||||
.get("/v2/apis/" + apiId + "/routes")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("items.routeKey", hasItem("GET /from-uri"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void samHttpApi_definitionBodyReconcilesRoutesOnStackUpdate() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "sam-http-api-update-" + suffix;
|
||||
String apiName = "sam-http-api-update-" + suffix;
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String initialTemplate = httpApiTemplate(apiName, "/before");
|
||||
String updatedTemplate = httpApiTemplate(apiName, "/after");
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", initialTemplate)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
waitForStackStatus(stackName, "CREATE_COMPLETE");
|
||||
String apiId = apiIdForName(apiName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", updatedTemplate)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
waitForStackStatus(stackName, "UPDATE_COMPLETE");
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v2/apis/" + apiId + "/routes")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("items.routeKey", hasItem("GET /after"))
|
||||
.body("items.routeKey", not(hasItem("GET /before")));
|
||||
}
|
||||
|
||||
private static String httpApiTemplate(String apiName, String path) {
|
||||
return """
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: AWS::Serverless-2016-10-31
|
||||
Resources:
|
||||
HttpApi:
|
||||
Type: AWS::Serverless::HttpApi
|
||||
Properties:
|
||||
Name: %s
|
||||
DefinitionBody:
|
||||
openapi: 3.0.1
|
||||
paths:
|
||||
%s:
|
||||
get: {}
|
||||
""".formatted(apiName, path);
|
||||
}
|
||||
|
||||
private static String apiIdForName(String apiName) {
|
||||
return given()
|
||||
.when()
|
||||
.get("/v2/apis")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("items.find { it.name == '" + apiName + "' }.protocolType", equalTo("HTTP"))
|
||||
.extract()
|
||||
.path("items.find { it.name == '" + apiName + "' }.apiId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void samFunction_withCodeUri_s3Reference() {
|
||||
String stackName = "sam-s3code-stack";
|
||||
|
||||
+231
@@ -897,4 +897,235 @@ class SamTransformProcessorTest {
|
||||
assertTrue(expanded.path("Transform").isMissingNode());
|
||||
assertTrue(expanded.path("Globals").isMissingNode());
|
||||
}
|
||||
@Test
|
||||
void expandSamTemplate_httpApiPreservesDefinitionBodyAsRoutes() throws Exception {
|
||||
// Regression for #1956: a route-bearing HttpApi carries its routes in the inline
|
||||
// OpenAPI DefinitionBody, which must survive as the ApiGatewayV2::Api Body — otherwise
|
||||
// the API expands with no routes.
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Resources": {
|
||||
"MyHttpApi": {
|
||||
"Type": "AWS::Serverless::HttpApi",
|
||||
"Properties": {
|
||||
"DefinitionBody": {
|
||||
"openapi": "3.0.1",
|
||||
"paths": {
|
||||
"/hello": { "get": { "x-amazon-apigateway-integration": { "type": "aws_proxy" } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
JsonNode resources = processor.expandSamTemplate(template).path("Resources");
|
||||
|
||||
JsonNode api = resources.path("MyHttpApi");
|
||||
assertEquals("AWS::ApiGatewayV2::Api", api.path("Type").asText());
|
||||
JsonNode body = api.path("Properties").path("Body");
|
||||
assertFalse(body.isMissingNode(), "DefinitionBody must be preserved as the API Body");
|
||||
assertEquals("3.0.1", body.path("openapi").asText());
|
||||
assertTrue(body.path("paths").has("/hello"), "route definitions must survive the transform");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_httpApiEventMergesIntoMatchingDefinitionBodyOperation() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Resources": {
|
||||
"MyHttpApi": {
|
||||
"Type": "AWS::Serverless::HttpApi",
|
||||
"Properties": {
|
||||
"Auth": {
|
||||
"DefaultAuthorizer": "JwtAuth",
|
||||
"Authorizers": {
|
||||
"JwtAuth": {
|
||||
"IdentitySource": "$request.header.Authorization",
|
||||
"AuthorizationScopes": ["read:items"],
|
||||
"JwtConfiguration": {
|
||||
"Issuer": "https://issuer.example.com",
|
||||
"Audience": ["items-client"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"DefinitionBody": {
|
||||
"openapi": "3.0.1",
|
||||
"paths": {
|
||||
"/items": {
|
||||
"get": {
|
||||
"security": [],
|
||||
"responses": { "200": { "description": "ok" } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"MyFunction": {
|
||||
"Type": "AWS::Serverless::Function",
|
||||
"Properties": {
|
||||
"Runtime": "python3.12",
|
||||
"Handler": "index.handler",
|
||||
"InlineCode": "def handler(e,c): return {}",
|
||||
"Events": {
|
||||
"Api": {
|
||||
"Type": "HttpApi",
|
||||
"Properties": {
|
||||
"ApiId": { "Ref": "MyHttpApi" },
|
||||
"Path": "/items",
|
||||
"Method": "GET"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
JsonNode resources = processor.expandSamTemplate(template).path("Resources");
|
||||
JsonNode operation = resources.path("MyHttpApi").path("Properties").path("Body")
|
||||
.path("paths").path("/items").path("get");
|
||||
JsonNode integration = operation.path("x-amazon-apigateway-integration");
|
||||
JsonNode authorizer = resources.path("MyHttpApi").path("Properties").path("Body")
|
||||
.path("components").path("securitySchemes").path("JwtAuth");
|
||||
|
||||
assertEquals("ok", operation.path("responses").path("200").path("description").asText());
|
||||
assertEquals("aws_proxy", integration.path("type").asText());
|
||||
assertEquals("POST", integration.path("httpMethod").asText());
|
||||
assertEquals("2.0", integration.path("payloadFormatVersion").asText());
|
||||
assertEquals("MyFunction", integration.path("uri").path("Fn::Sub").path(1)
|
||||
.path("FnArn").path("Fn::GetAtt").path(0).asText());
|
||||
assertEquals("oauth2", authorizer.path("type").asText());
|
||||
assertEquals("jwt", authorizer.path("x-amazon-apigateway-authorizer").path("type").asText());
|
||||
assertEquals("$request.header.Authorization", authorizer.path("x-amazon-apigateway-authorizer")
|
||||
.path("identitySource").path(0).asText());
|
||||
assertEquals("https://issuer.example.com", authorizer.path("x-amazon-apigateway-authorizer")
|
||||
.path("jwtConfiguration").path("issuer").asText());
|
||||
assertEquals("items-client", authorizer.path("x-amazon-apigateway-authorizer")
|
||||
.path("jwtConfiguration").path("audience").path(0).asText());
|
||||
assertEquals("read:items", operation.path("security").path(0).path("JwtAuth").path(0).asText());
|
||||
|
||||
int routeResources = 0;
|
||||
int integrationResources = 0;
|
||||
int permissionResources = 0;
|
||||
Iterator<JsonNode> definitions = resources.elements();
|
||||
while (definitions.hasNext()) {
|
||||
String type = definitions.next().path("Type").asText();
|
||||
routeResources += "AWS::ApiGatewayV2::Route".equals(type) ? 1 : 0;
|
||||
integrationResources += "AWS::ApiGatewayV2::Integration".equals(type) ? 1 : 0;
|
||||
permissionResources += "AWS::Lambda::Permission".equals(type) ? 1 : 0;
|
||||
}
|
||||
assertEquals(0, routeResources, "matching body operations must not emit a duplicate route resource");
|
||||
assertEquals(0, integrationResources, "the body owns the merged integration");
|
||||
assertEquals(1, permissionResources, "API Gateway still needs permission to invoke the function");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_matchingHttpApiEventCanOptOutOfDefaultAuthorizer() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Resources": {
|
||||
"HttpApi": {
|
||||
"Type": "AWS::Serverless::HttpApi",
|
||||
"Properties": {
|
||||
"Auth": {
|
||||
"DefaultAuthorizer": "JwtAuth",
|
||||
"Authorizers": {
|
||||
"JwtAuth": {
|
||||
"IdentitySource": ["$request.header.Authorization"],
|
||||
"JwtConfiguration": {
|
||||
"issuer": "https://issuer.example.com",
|
||||
"audience": ["client-id"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"DefinitionBody": {
|
||||
"openapi": "3.0.1",
|
||||
"paths": { "/public": { "get": {} } }
|
||||
}
|
||||
}
|
||||
},
|
||||
"Handler": {
|
||||
"Type": "AWS::Serverless::Function",
|
||||
"Properties": {
|
||||
"Runtime": "python3.12",
|
||||
"Handler": "index.handler",
|
||||
"InlineCode": "def handler(e,c): return {}",
|
||||
"Events": {
|
||||
"Public": {
|
||||
"Type": "HttpApi",
|
||||
"Properties": {
|
||||
"ApiId": { "Ref": "HttpApi" },
|
||||
"Path": "/public",
|
||||
"Method": "GET",
|
||||
"Auth": { "Authorizer": "NONE" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
JsonNode operation = processor.expandSamTemplate(template).path("Resources")
|
||||
.path("HttpApi").path("Properties").path("Body")
|
||||
.path("paths").path("/public").path("get");
|
||||
|
||||
assertTrue(operation.path("security").isArray());
|
||||
assertTrue(operation.path("security").isEmpty(),
|
||||
"Authorizer NONE must override the API's default authorizer");
|
||||
assertTrue(operation.path("x-amazon-apigateway-integration").isObject());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_httpApiMapsDefinitionUriToBodyS3Location() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Resources": {
|
||||
"MyHttpApi": {
|
||||
"Type": "AWS::Serverless::HttpApi",
|
||||
"Properties": { "DefinitionUri": "s3://api-specs/openapi.yaml" }
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
JsonNode properties = processor.expandSamTemplate(template)
|
||||
.path("Resources").path("MyHttpApi").path("Properties");
|
||||
|
||||
assertTrue(properties.path("Body").isMissingNode(), "DefinitionUri must not become an inline Body");
|
||||
assertEquals("api-specs", properties.path("BodyS3Location").path("Bucket").asText());
|
||||
assertEquals("openapi.yaml", properties.path("BodyS3Location").path("Key").asText());
|
||||
}
|
||||
@Test
|
||||
void expandSamTemplate_httpApiPreservesIntrinsicDefinitionUriForProvisioning() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Resources": {
|
||||
"MyHttpApi": {
|
||||
"Type": "AWS::Serverless::HttpApi",
|
||||
"Properties": {
|
||||
"DefinitionUri": { "Fn::Sub": "s3://${SpecBucket}/openapi.yaml" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
JsonNode bodyS3Location = processor.expandSamTemplate(template)
|
||||
.path("Resources").path("MyHttpApi").path("Properties").path("BodyS3Location");
|
||||
|
||||
assertEquals("s3://${SpecBucket}/openapi.yaml", bodyS3Location.path("Fn::Sub").asText());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user