mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): provision AWS::ApiGatewayV2::VpcLink (#5008)
* feat(apigatewayv2): implement UpdateVpcLink and VPC link tagging * feat(cloudformation): provision AWS::ApiGatewayV2::VpcLink * fix(cloudformation): keep VPC link and integration connection state on updates * fix(cloudformation): restore the integration connection when its own update fails
This commit is contained in:
1 parent
db40361a3c
commit
2c544fdb9f
12 files changed
+927
-14
No files matched your search
@@ -581,9 +581,13 @@ Routes carrying `authorizationType: AWS_IAM`: including those an OpenAPI import
|
||||
| **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
|
||||
| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName |
|
||||
| **API Mappings** | CreateApiMapping, GetApiMapping, GetApiMappings, DeleteApiMapping |
|
||||
| **VPC Links** | CreateVpcLink, GetVpcLink, GetVpcLinks, DeleteVpcLink |
|
||||
| **VPC Links** | CreateVpcLink, GetVpcLink, GetVpcLinks, UpdateVpcLink, DeleteVpcLink |
|
||||
| **Tags** | TagResource, UntagResource, GetTags |
|
||||
|
||||
`TagResource`, `UntagResource` and `GetTags` accept API, stage and VPC link ARNs
|
||||
(`arn:<partition>:apigateway:<region>::/vpclinks/<vpcLinkId>`). `UpdateVpcLink` changes only the
|
||||
name, as in the API model.
|
||||
|
||||
### WebSocket Data-Plane {#websocket-data-plane}
|
||||
|
||||
Floci supports real WebSocket connections for API Gateway v2 WebSocket APIs. Clients connect via:
|
||||
@@ -644,7 +648,6 @@ DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Disconn
|
||||
### Not Implemented
|
||||
|
||||
- `ExportApi`, `UpdateDomainName`, `UpdateApiMapping`
|
||||
- `UpdateVpcLink` — the other four VPC Link operations are implemented; see the table above
|
||||
|
||||
### Examples
|
||||
|
||||
|
||||
@@ -145,7 +145,7 @@ cross-resource references.
|
||||
| Route 53 | `HostedZone`, `RecordSet` |
|
||||
| Cloud Map | `HttpNamespace`, `PrivateDnsNamespace`, `PublicDnsNamespace`, `Service` |
|
||||
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` |
|
||||
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` |
|
||||
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment`, `VpcLink` |
|
||||
| AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey` |
|
||||
| Step Functions | `StateMachine` |
|
||||
| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
|
||||
|
||||
+16
@@ -1559,6 +1559,22 @@ public class ApiGatewayController {
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/v2/vpclinks/{vpcLinkId}")
|
||||
public Response updateVpcLink(@Context HttpHeaders headers,
|
||||
@PathParam("vpcLinkId") String vpcLinkId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
VpcLink link = v2Service.updateVpcLink(region, vpcLinkId, request);
|
||||
return Response.ok(toV2VpcLinkNode(link).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/v2/vpclinks/{vpcLinkId}")
|
||||
public Response deleteVpcLink(@Context HttpHeaders headers, @PathParam("vpcLinkId") String vpcLinkId) {
|
||||
|
||||
+66
-9
@@ -15,6 +15,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -782,6 +783,19 @@ public class ApiGatewayV2Service {
|
||||
return integration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the connection type and id exactly as given, null included. UpdateIntegration keeps a
|
||||
* field the request leaves out, so it cannot remove a connection that CloudFormation dropped.
|
||||
*/
|
||||
public Integration replaceIntegrationConnection(String region, String apiId, String integrationId,
|
||||
String connectionType, String connectionId) {
|
||||
Integration integration = getIntegration(region, apiId, integrationId);
|
||||
integration.setConnectionType(connectionType);
|
||||
integration.setConnectionId(connectionId);
|
||||
integrationStore.put(integrationKey(region, apiId, integrationId), integration);
|
||||
return integration;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Stage CRUD ────────────────────────────
|
||||
|
||||
public Stage createStage(String region, String apiId, Map<String, Object> request) {
|
||||
@@ -1143,6 +1157,16 @@ public class ApiGatewayV2Service {
|
||||
return vpcLinkStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
/** UpdateVpcLink: only the name can change, as in the API model. */
|
||||
public VpcLink updateVpcLink(String region, String vpcLinkId, Map<String, Object> request) {
|
||||
VpcLink link = getVpcLink(region, vpcLinkId);
|
||||
if (request.get("name") instanceof String name) {
|
||||
link.setName(name);
|
||||
}
|
||||
vpcLinkStore.put(vpcLinkKey(region, vpcLinkId), link);
|
||||
return link;
|
||||
}
|
||||
|
||||
public void deleteVpcLink(String region, String vpcLinkId) {
|
||||
getVpcLink(region, vpcLinkId);
|
||||
vpcLinkStore.delete(vpcLinkKey(region, vpcLinkId));
|
||||
@@ -1150,18 +1174,23 @@ public class ApiGatewayV2Service {
|
||||
|
||||
// ──────────────────────────── Standalone Tagging ────────────────────────────
|
||||
|
||||
/** A taggable v2 resource: an API, or a stage within one. */
|
||||
private record TaggedResource(String region, String apiId, String stageName) {
|
||||
/** A taggable v2 resource: an API, a stage within one, or a VPC link. */
|
||||
private record TaggedResource(String region, String apiId, String stageName, String vpcLinkId) {
|
||||
boolean isStage() {
|
||||
return stageName != null;
|
||||
}
|
||||
|
||||
boolean isVpcLink() {
|
||||
return vpcLinkId != null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an API Gateway v2 resource ARN.
|
||||
*
|
||||
* <p>Accepted forms: {@code arn:aws:apigateway:{region}::/apis/{apiId}} and
|
||||
* {@code arn:aws:apigateway:{region}::/apis/{apiId}/stages/{stageName}}. Matching on the
|
||||
* <p>Accepted forms: {@code arn:aws:apigateway:{region}::/apis/{apiId}},
|
||||
* {@code arn:aws:apigateway:{region}::/apis/{apiId}/stages/{stageName}} and
|
||||
* {@code arn:aws:apigateway:{region}::/vpclinks/{vpcLinkId}}. Matching on the
|
||||
* trailing segment alone would read a stage ARN's stage name as the API id, which surfaces as
|
||||
* a misleading "Invalid API id specified" on TagResource.
|
||||
*/
|
||||
@@ -1181,10 +1210,13 @@ public class ApiGatewayV2Service {
|
||||
String[] segments = arn.resource().replaceFirst("^/", "").split("/");
|
||||
if (segments.length >= 4 && "apis".equals(segments[0]) && "stages".equals(segments[2])
|
||||
&& !segments[1].isEmpty() && !segments[3].isEmpty()) {
|
||||
return new TaggedResource(region, segments[1], segments[3]);
|
||||
return new TaggedResource(region, segments[1], segments[3], null);
|
||||
}
|
||||
if (segments.length >= 2 && "apis".equals(segments[0]) && !segments[1].isEmpty()) {
|
||||
return new TaggedResource(region, segments[1], null);
|
||||
return new TaggedResource(region, segments[1], null, null);
|
||||
}
|
||||
if (segments.length == 2 && "vpclinks".equals(segments[0]) && !segments[1].isEmpty()) {
|
||||
return new TaggedResource(region, null, null, segments[1]);
|
||||
}
|
||||
throw new AwsException("BadRequestException",
|
||||
"Cannot extract apiId from ResourceArn: " + resourceArn, 400);
|
||||
@@ -1192,6 +1224,18 @@ public class ApiGatewayV2Service {
|
||||
|
||||
public void tagResource(String resourceArn, Map<String, String> tags) {
|
||||
TaggedResource target = parseArn(resourceArn);
|
||||
if (target.isVpcLink()) {
|
||||
ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);
|
||||
VpcLink link = getVpcLink(target.region(), target.vpcLinkId());
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
if (link.getTags() == null) {
|
||||
link.setTags(new HashMap<>());
|
||||
}
|
||||
link.getTags().putAll(tags);
|
||||
}
|
||||
vpcLinkStore.put(vpcLinkKey(target.region(), target.vpcLinkId()), link);
|
||||
return;
|
||||
}
|
||||
if (target.isStage()) {
|
||||
ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);
|
||||
Stage stage = getStage(target.region(), target.apiId(), target.stageName());
|
||||
@@ -1217,6 +1261,14 @@ public class ApiGatewayV2Service {
|
||||
|
||||
public void untagResource(String resourceArn, List<String> tagKeys) {
|
||||
TaggedResource target = parseArn(resourceArn);
|
||||
if (target.isVpcLink()) {
|
||||
VpcLink link = getVpcLink(target.region(), target.vpcLinkId());
|
||||
if (tagKeys != null && link.getTags() != null) {
|
||||
tagKeys.forEach(k -> link.getTags().remove(k));
|
||||
}
|
||||
vpcLinkStore.put(vpcLinkKey(target.region(), target.vpcLinkId()), link);
|
||||
return;
|
||||
}
|
||||
if (target.isStage()) {
|
||||
Stage stage = getStage(target.region(), target.apiId(), target.stageName());
|
||||
if (tagKeys != null && stage.getTags() != null) {
|
||||
@@ -1234,9 +1286,14 @@ public class ApiGatewayV2Service {
|
||||
|
||||
public Map<String, String> getTags(String resourceArn) {
|
||||
TaggedResource target = parseArn(resourceArn);
|
||||
Map<String, String> tags = target.isStage()
|
||||
? getStage(target.region(), target.apiId(), target.stageName()).getTags()
|
||||
: getApi(target.region(), target.apiId()).getTags();
|
||||
Map<String, String> tags;
|
||||
if (target.isVpcLink()) {
|
||||
tags = getVpcLink(target.region(), target.vpcLinkId()).getTags();
|
||||
} else if (target.isStage()) {
|
||||
tags = getStage(target.region(), target.apiId(), target.stageName()).getTags();
|
||||
} else {
|
||||
tags = getApi(target.region(), target.apiId()).getTags();
|
||||
}
|
||||
return (tags != null) ? new java.util.HashMap<>(tags) : java.util.Collections.emptyMap();
|
||||
}
|
||||
|
||||
|
||||
+271
-2
@@ -1,7 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
@@ -10,6 +12,7 @@ import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Deployment;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.VpcLink;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
@@ -48,6 +51,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final String INTEGRATION = "AWS::ApiGatewayV2::Integration";
|
||||
private static final String STAGE = "AWS::ApiGatewayV2::Stage";
|
||||
private static final String DEPLOYMENT = "AWS::ApiGatewayV2::Deployment";
|
||||
private static final String VPC_LINK = "AWS::ApiGatewayV2::VpcLink";
|
||||
|
||||
private static final String BODY_ROUTE_IDS_ATTR = "__FlociApiGatewayV2BodyRouteIds";
|
||||
private static final String BODY_INTEGRATION_IDS_ATTR = "__FlociApiGatewayV2BodyIntegrationIds";
|
||||
@@ -67,7 +71,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(API, AUTHORIZER, ROUTE, INTEGRATION, STAGE, DEPLOYMENT);
|
||||
return Set.of(API, AUTHORIZER, ROUTE, INTEGRATION, STAGE, DEPLOYMENT, VPC_LINK);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -79,6 +83,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
case INTEGRATION -> provisionIntegration(r, props, ctx);
|
||||
case STAGE -> provisionStage(r, props, ctx);
|
||||
case DEPLOYMENT -> provisionDeployment(r, props, ctx);
|
||||
case VPC_LINK -> provisionVpcLink(r, props, ctx);
|
||||
default -> throw new IllegalStateException("Unhandled type: " + r.getResourceType());
|
||||
}
|
||||
}
|
||||
@@ -100,12 +105,57 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
}
|
||||
case VPC_LINK -> delete(VPC_LINK, resource.getPhysicalId(), region);
|
||||
default -> {
|
||||
// Route, Integration, Stage and Deployment are removed when their Api is deleted.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
if (VPC_LINK.equals(resourceType) && physicalId != null && !physicalId.isBlank()) {
|
||||
CfnDeletes.safeDelete("API Gateway V2 VPC link", physicalId,
|
||||
() -> apiGatewayV2Service.deleteVpcLink(region, physicalId), "NotFoundException");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(CfnRollback.VPC_LINK_UPDATE_SNAPSHOT_ATTR);
|
||||
resource.getAttributes().remove(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
if (ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
return true;
|
||||
}
|
||||
if (VPC_LINK.equals(resource.getResourceType())) {
|
||||
return rollbackVpcLinkUpdate(resource);
|
||||
}
|
||||
if (INTEGRATION.equals(resource.getResourceType())) {
|
||||
return rollbackIntegrationConnection(resource);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
|
||||
// Only the Api carries body-generated sub-resource ids; keep any the failed attempt created
|
||||
@@ -813,17 +863,95 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
req.put("integrationType", ctx.resolveOptional(props, "IntegrationType"));
|
||||
req.put("integrationUri", ctx.resolveOptional(props, "IntegrationUri"));
|
||||
req.put("payloadFormatVersion", ctx.resolveOrDefault(props, "PayloadFormatVersion", "2.0"));
|
||||
String connectionType = ctx.resolveOptional(props, "ConnectionType");
|
||||
String connectionId = ctx.resolveOptional(props, "ConnectionId");
|
||||
req.put("connectionType", connectionType);
|
||||
req.put("connectionId", connectionId);
|
||||
// A snapshot describes the update in flight; one an earlier update left behind is stale.
|
||||
r.getAttributes().remove(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR);
|
||||
|
||||
Integration integration;
|
||||
if (r.getPhysicalId() == null) {
|
||||
integration = apiGatewayV2Service.createIntegration(region, apiId, req);
|
||||
} else {
|
||||
integration = apiGatewayV2Service.updateIntegration(region, apiId, r.getPhysicalId(), req);
|
||||
Integration prior = apiGatewayV2Service.getIntegration(region, apiId, r.getPhysicalId());
|
||||
r.getAttributes().put(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR,
|
||||
integrationConnectionSnapshot(region, apiId, prior, req));
|
||||
// The connection changes first, in one call. If the update after it fails, the connection
|
||||
// is the only change to undo.
|
||||
try {
|
||||
// A connection removed from the template is removed here too. INTERNET is the AWS default.
|
||||
apiGatewayV2Service.replaceIntegrationConnection(region, apiId, r.getPhysicalId(),
|
||||
connectionType != null ? connectionType : "INTERNET", connectionId);
|
||||
integration = apiGatewayV2Service.updateIntegration(region, apiId, r.getPhysicalId(), req);
|
||||
} catch (RuntimeException failure) {
|
||||
// The stack skips rollbackUpdate for a resource whose own update failed, so undo it here.
|
||||
try {
|
||||
rollbackIntegrationConnection(r);
|
||||
} catch (RuntimeException restoreFailure) {
|
||||
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
|
||||
"Could not roll back the connection of integration " + r.getPhysicalId() + ": "
|
||||
+ restoreFailure.getMessage());
|
||||
if (restoreFailure != failure) {
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
r.setPhysicalId(integration.getIntegrationId());
|
||||
r.getAttributes().put("IntegrationId", integration.getIntegrationId());
|
||||
}
|
||||
|
||||
/**
|
||||
* The connection the integration had before this update, and whether the update also changes
|
||||
* another field. UpdateIntegration keeps a field the request leaves out, so only a value that
|
||||
* is set and differs counts as a change.
|
||||
*/
|
||||
private String integrationConnectionSnapshot(String region, String apiId, Integration prior,
|
||||
Map<String, Object> req) {
|
||||
boolean otherFieldChanged = changes(req.get("integrationType"), prior.getIntegrationType())
|
||||
|| changes(req.get("integrationUri"), prior.getIntegrationUri())
|
||||
|| changes(req.get("payloadFormatVersion"), prior.getPayloadFormatVersion());
|
||||
ObjectNode snapshot = objectMapper.createObjectNode();
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("apiId", apiId);
|
||||
snapshot.put("connectionType", prior.getConnectionType());
|
||||
snapshot.put("connectionId", prior.getConnectionId());
|
||||
snapshot.put("otherFieldChanged", otherFieldChanged);
|
||||
return snapshot.toString();
|
||||
}
|
||||
|
||||
private static boolean changes(Object requested, String current) {
|
||||
return requested != null && !requested.equals(current);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the connection back from the snapshot taken before the update. Answers true only when the
|
||||
* update changed nothing else: this provisioner keeps no copy of the other fields, so the stack
|
||||
* must still report that their rollback is not implemented.
|
||||
*/
|
||||
private boolean rollbackIntegrationConnection(StackResource resource) {
|
||||
String raw = resource.getAttributes().get(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR);
|
||||
if (raw == null) {
|
||||
return false;
|
||||
}
|
||||
JsonNode snapshot;
|
||||
try {
|
||||
snapshot = objectMapper.readTree(raw);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.errorv("Could not parse integration connection snapshot for {0}: {1}",
|
||||
resource.getLogicalId(), e.getMessage());
|
||||
return false;
|
||||
}
|
||||
apiGatewayV2Service.replaceIntegrationConnection(snapshot.path("region").asText(),
|
||||
snapshot.path("apiId").asText(), resource.getPhysicalId(),
|
||||
textOrNull(snapshot, "connectionType"), textOrNull(snapshot, "connectionId"));
|
||||
// Spent only once the restore succeeded, so a restore that throws can be tried again.
|
||||
resource.getAttributes().remove(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR);
|
||||
return !snapshot.path("otherFieldChanged").asBoolean();
|
||||
}
|
||||
|
||||
// ── Stage ────────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionStage(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
@@ -865,6 +993,147 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().put("DeploymentId", deployment.getDeploymentId());
|
||||
}
|
||||
|
||||
// ── VpcLink ──────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Creates the VPC link, or updates it in place when its subnets and security groups did not
|
||||
* change: on AWS only {@code Name} and {@code Tags} update without replacement. Any other change
|
||||
* creates a new link, and {@link ReplacementCleanup} deletes the old one after the update.
|
||||
*/
|
||||
private void provisionVpcLink(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String region = ctx.region();
|
||||
String name = ctx.resolveOptional(props, "Name");
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("ValidationError", VPC_LINK + " requires Name", 400);
|
||||
}
|
||||
List<String> subnetIds = ctx.resolveStringList(props, "SubnetIds");
|
||||
if (subnetIds.isEmpty()) {
|
||||
throw new AwsException("ValidationError", VPC_LINK + " requires SubnetIds", 400);
|
||||
}
|
||||
List<String> securityGroupIds = ctx.resolveStringList(props, "SecurityGroupIds");
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
// A snapshot describes the update in flight; one an earlier update left behind is stale.
|
||||
r.getAttributes().remove(CfnRollback.VPC_LINK_UPDATE_SNAPSHOT_ATTR);
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
|
||||
VpcLink prior = ctx.isUpdate() ? findVpcLink(region, ctx.priorPhysicalId()) : null;
|
||||
String vpcLinkId;
|
||||
if (prior != null && subnetIds.equals(listOrEmpty(prior.getSubnetIds()))
|
||||
&& securityGroupIds.equals(listOrEmpty(prior.getSecurityGroupIds()))) {
|
||||
vpcLinkId = prior.getVpcLinkId();
|
||||
r.getAttributes().put(CfnRollback.VPC_LINK_UPDATE_SNAPSHOT_ATTR, vpcLinkSnapshot(prior, region));
|
||||
r.setPhysicalId(vpcLinkId);
|
||||
// Tags go first: the service refuses a reserved tag key, and refusing it before the
|
||||
// rename leaves the name as the stack last committed it.
|
||||
try {
|
||||
reconcileVpcLinkTags(region, vpcLinkId, tags);
|
||||
apiGatewayV2Service.updateVpcLink(region, vpcLinkId, Map.of("name", name));
|
||||
} catch (RuntimeException failure) {
|
||||
// The stack skips rollbackUpdate for a resource whose own update failed, so undo it here.
|
||||
try {
|
||||
rollbackVpcLinkUpdate(r);
|
||||
} catch (RuntimeException restoreFailure) {
|
||||
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
|
||||
"Could not roll back the update of VPC link " + vpcLinkId + ": "
|
||||
+ restoreFailure.getMessage());
|
||||
if (restoreFailure != failure) {
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
} else {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("name", name);
|
||||
req.put("subnetIds", subnetIds);
|
||||
req.put("securityGroupIds", securityGroupIds);
|
||||
if (!tags.isEmpty()) {
|
||||
req.put("tags", tags);
|
||||
}
|
||||
vpcLinkId = apiGatewayV2Service.createVpcLink(region, req).getVpcLinkId();
|
||||
}
|
||||
r.setPhysicalId(vpcLinkId);
|
||||
r.getAttributes().put("VpcLinkId", vpcLinkId);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
private VpcLink findVpcLink(String region, String vpcLinkId) {
|
||||
try {
|
||||
return apiGatewayV2Service.getVpcLink(region, vpcLinkId);
|
||||
} catch (AwsException e) {
|
||||
if (!"NotFoundException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
// The prior link is gone, so the update creates a new one.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcileVpcLinkTags(String region, String vpcLinkId, Map<String, String> desired) {
|
||||
String arn = AwsArnUtils.Arn.of("apigateway", region, "", "/vpclinks/" + vpcLinkId).toString();
|
||||
Map<String, String> current = apiGatewayV2Service.getTags(arn);
|
||||
// Only new or changed tags are sent: TagResource refuses a reserved key, even one the link
|
||||
// already carries from its creation.
|
||||
Map<String, String> changed = new LinkedHashMap<>();
|
||||
desired.forEach((key, value) -> {
|
||||
if (!value.equals(current.get(key))) {
|
||||
changed.put(key, value);
|
||||
}
|
||||
});
|
||||
if (!changed.isEmpty()) {
|
||||
apiGatewayV2Service.tagResource(arn, changed);
|
||||
}
|
||||
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
|
||||
if (!stale.isEmpty()) {
|
||||
apiGatewayV2Service.untagResource(arn, stale);
|
||||
}
|
||||
}
|
||||
|
||||
private String vpcLinkSnapshot(VpcLink link, String region) {
|
||||
ObjectNode snapshot = objectMapper.createObjectNode();
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("name", link.getName());
|
||||
ObjectNode tags = snapshot.putObject("tags");
|
||||
if (link.getTags() != null) {
|
||||
link.getTags().forEach(tags::put);
|
||||
}
|
||||
return snapshot.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the name and tags back from the snapshot taken before an in-place update. With no
|
||||
* snapshot, this update did not change the link.
|
||||
*/
|
||||
private boolean rollbackVpcLinkUpdate(StackResource resource) {
|
||||
String raw = resource.getAttributes().get(CfnRollback.VPC_LINK_UPDATE_SNAPSHOT_ATTR);
|
||||
if (raw == null) {
|
||||
return true;
|
||||
}
|
||||
JsonNode snapshot;
|
||||
try {
|
||||
snapshot = objectMapper.readTree(raw);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.errorv("Could not parse VPC link update snapshot for {0}: {1}",
|
||||
resource.getLogicalId(), e.getMessage());
|
||||
return false;
|
||||
}
|
||||
String region = snapshot.path("region").asText();
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
snapshot.path("tags").properties().forEach(e -> tags.put(e.getKey(), e.getValue().asText()));
|
||||
if (snapshot.path("name").isTextual()) {
|
||||
apiGatewayV2Service.updateVpcLink(region, resource.getPhysicalId(),
|
||||
Map.of("name", snapshot.path("name").asText()));
|
||||
}
|
||||
reconcileVpcLinkTags(region, resource.getPhysicalId(), tags);
|
||||
// Spent only once the restore succeeded, so a restore that throws can be tried again.
|
||||
resource.getAttributes().remove(CfnRollback.VPC_LINK_UPDATE_SNAPSHOT_ATTR);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<String> listOrEmpty(List<String> values) {
|
||||
return values == null ? List.of() : values;
|
||||
}
|
||||
|
||||
// ── Local copies of shared utilities (still used by staying monolith types) ──
|
||||
|
||||
private static String textOrNull(JsonNode node, String field) {
|
||||
|
||||
+15
@@ -95,6 +95,21 @@ public final class CfnRollback {
|
||||
*/
|
||||
public static final String API_KEY_UPDATE_SNAPSHOT_ATTR = "__FlociApiKeyUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the name and tags an API Gateway V2 VPC link carried before an in-place update changed
|
||||
* them, so a failed stack update can put them back. Written by {@code ApiGatewayV2CfnProvisioner}
|
||||
* before its update call and spent by its {@code rollbackUpdate}.
|
||||
*/
|
||||
public static final String VPC_LINK_UPDATE_SNAPSHOT_ATTR = "__FlociVpcLinkUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the connection type and id an API Gateway V2 integration carried before an update, and
|
||||
* whether that update also changed another field, so a failed stack update can put the
|
||||
* connection back. Written by {@code ApiGatewayV2CfnProvisioner} before its update call and
|
||||
* spent by its {@code rollbackUpdate}.
|
||||
*/
|
||||
public static final String INTEGRATION_CONNECTION_SNAPSHOT_ATTR = "__FlociIntegrationConnectionSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the complete prior metric filter, identity, name mode and per-address mutation outcomes
|
||||
* and ownership states.
|
||||
|
||||
@@ -63,6 +63,10 @@
|
||||
"StageName",
|
||||
"ApiId"
|
||||
],
|
||||
"AWS::ApiGatewayV2::VpcLink": [
|
||||
"SecurityGroupIds",
|
||||
"SubnetIds"
|
||||
],
|
||||
"AWS::AppSync::ApiKey": [
|
||||
"ApiId"
|
||||
],
|
||||
|
||||
+92
@@ -82,6 +82,94 @@ class ApiGatewayV2VpcLinkRestTest {
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void updateVpcLinkRenamesTheLinkOnly() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"name":"renamed-vpc-link"}
|
||||
""")
|
||||
.when().patch("/v2/vpclinks/" + vpcLinkId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("vpcLinkId", equalTo(vpcLinkId))
|
||||
.body("name", equalTo("renamed-vpc-link"))
|
||||
.body("subnetIds", hasItems("subnet-aaaa1111", "subnet-bbbb2222"))
|
||||
.body("securityGroupIds", hasItem("sg-cccc3333"))
|
||||
.body("tags.Env", equalTo("test"));
|
||||
|
||||
given()
|
||||
.when().get("/v2/vpclinks/" + vpcLinkId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("name", equalTo("renamed-vpc-link"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void updateNonexistentVpcLinkReturns404() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"name":"missing"}
|
||||
""")
|
||||
.when().patch("/v2/vpclinks/does-not-exist")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("message", containsString("VpcLink not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void tagResourceAddsTagsToTheVpcLink() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"tags":{"Team":"platform"}}
|
||||
""")
|
||||
.when().post("/v2/tags/" + vpcLinkArn())
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
given()
|
||||
.when().get("/v2/tags/" + vpcLinkArn())
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags.Env", equalTo("test"))
|
||||
.body("tags.Team", equalTo("platform"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void untagResourceRemovesTagsFromTheVpcLink() {
|
||||
given()
|
||||
.queryParam("tagKeys", "Env")
|
||||
.when().delete("/v2/tags/" + vpcLinkArn())
|
||||
.then()
|
||||
.statusCode(204);
|
||||
|
||||
given()
|
||||
.when().get("/v2/vpclinks/" + vpcLinkId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags.Env", nullValue())
|
||||
.body("tags.Team", equalTo("platform"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void tagResourceOnUnknownVpcLinkReturns404() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"tags":{"Team":"platform"}}
|
||||
""")
|
||||
.when().post("/v2/tags/arn:aws:apigateway:us-east-1::/vpclinks/does-not-exist")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void createApi() {
|
||||
@@ -216,6 +304,10 @@ class ApiGatewayV2VpcLinkRestTest {
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
private static String vpcLinkArn() {
|
||||
return "arn:aws:apigateway:us-east-1::/vpclinks/" + vpcLinkId;
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(99)
|
||||
void cleanup() {
|
||||
|
||||
+222
@@ -6,7 +6,9 @@ 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.Integration;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.VpcLink;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
@@ -14,19 +16,24 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudForm
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
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.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
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.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -530,12 +537,227 @@ class ApiGatewayV2CfnProvisionerTest {
|
||||
verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldTwo, List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcLinkCreatesTheLinkAndPublishesItsId() throws Exception {
|
||||
when(apiGatewayV2Service.createVpcLink(eq(REGION), anyMap())).thenReturn(vpcLink("vl-1", List.of("subnet-a")));
|
||||
|
||||
StackResource link = provisionVpcLink("""
|
||||
{"Name":"my-link","SubnetIds":["subnet-a"],"SecurityGroupIds":["sg-1"],"Tags":{"Env":"test"}}
|
||||
""", null, Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", link.getStatus());
|
||||
assertEquals("vl-1", link.getPhysicalId());
|
||||
assertEquals("vl-1", link.getAttributes().get("VpcLinkId"));
|
||||
verify(apiGatewayV2Service).createVpcLink(eq(REGION), argThat(req -> "my-link".equals(req.get("name"))
|
||||
&& List.of("subnet-a").equals(req.get("subnetIds"))
|
||||
&& List.of("sg-1").equals(req.get("securityGroupIds"))
|
||||
&& Map.of("Env", "test").equals(req.get("tags"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcLinkNameChangeUpdatesTheLinkInPlace() throws Exception {
|
||||
VpcLink prior = vpcLink("vl-1", List.of("subnet-a"));
|
||||
prior.setName("old-name");
|
||||
when(apiGatewayV2Service.getVpcLink(REGION, "vl-1")).thenReturn(prior);
|
||||
|
||||
StackResource link = provisionVpcLink("""
|
||||
{"Name":"new-name","SubnetIds":["subnet-a"]}
|
||||
""", "vl-1", Map.of("VpcLinkId", "vl-1"));
|
||||
|
||||
assertEquals("vl-1", link.getPhysicalId());
|
||||
verify(apiGatewayV2Service).updateVpcLink(REGION, "vl-1", Map.of("name", "new-name"));
|
||||
verify(apiGatewayV2Service, never()).createVpcLink(anyString(), anyMap());
|
||||
assertFalse(provisioner.hasReplacementUpdate(link));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcLinkSubnetChangeReplacesTheLink() throws Exception {
|
||||
when(apiGatewayV2Service.getVpcLink(REGION, "vl-1")).thenReturn(vpcLink("vl-1", List.of("subnet-a")));
|
||||
when(apiGatewayV2Service.createVpcLink(eq(REGION), anyMap())).thenReturn(vpcLink("vl-2", List.of("subnet-b")));
|
||||
|
||||
StackResource link = provisionVpcLink("""
|
||||
{"Name":"my-link","SubnetIds":["subnet-b"]}
|
||||
""", "vl-1", Map.of("VpcLinkId", "vl-1"));
|
||||
|
||||
assertEquals("vl-2", link.getPhysicalId());
|
||||
assertEquals("vl-2", link.getAttributes().get("VpcLinkId"));
|
||||
verify(apiGatewayV2Service, never()).updateVpcLink(anyString(), anyString(), anyMap());
|
||||
assertTrue(provisioner.hasReplacementUpdate(link), "the displaced link is deleted after the update");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcLinkWithoutSubnetIdsFailsBeforeCallingTheService() throws Exception {
|
||||
StackResource link = provisionVpcLink("""
|
||||
{"Name":"my-link"}
|
||||
""", null, Map.of());
|
||||
|
||||
assertEquals("CREATE_FAILED", link.getStatus());
|
||||
assertTrue(link.getStatusReason().contains("requires SubnetIds"), link.getStatusReason());
|
||||
verify(apiGatewayV2Service, never()).createVpcLink(anyString(), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackOfAnInPlaceVpcLinkUpdateRestoresNameAndTags() throws Exception {
|
||||
VpcLink prior = vpcLink("vl-1", List.of("subnet-a"));
|
||||
prior.setName("old-name");
|
||||
prior.setTags(new HashMap<>(Map.of("Env", "old")));
|
||||
when(apiGatewayV2Service.getVpcLink(REGION, "vl-1")).thenReturn(prior);
|
||||
when(apiGatewayV2Service.getTags(anyString())).thenReturn(Map.of("Env", "new"));
|
||||
StackResource link = provisionVpcLink("""
|
||||
{"Name":"new-name","SubnetIds":["subnet-a"],"Tags":{"Env":"new"}}
|
||||
""", "vl-1", Map.of("VpcLinkId", "vl-1"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(link));
|
||||
|
||||
verify(apiGatewayV2Service).updateVpcLink(REGION, "vl-1", Map.of("name", "old-name"));
|
||||
verify(apiGatewayV2Service).tagResource("arn:aws:apigateway:us-east-1::/vpclinks/vl-1", Map.of("Env", "old"));
|
||||
assertFalse(link.getAttributes().containsKey("__FlociVpcLinkUpdateSnapshot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void integrationPassesItsVpcLinkConnection() throws Exception {
|
||||
Integration integration = new Integration();
|
||||
integration.setIntegrationId("int-1");
|
||||
when(apiGatewayV2Service.createIntegration(eq(REGION), eq(API_ID), anyMap())).thenReturn(integration);
|
||||
|
||||
provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree("""
|
||||
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY",
|
||||
"IntegrationUri":"arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/alb/1/2",
|
||||
"ConnectionType":"VPC_LINK","ConnectionId":"vl-1"}
|
||||
"""),
|
||||
engine(), REGION, "000000000000", "test-stack", null, Map.of());
|
||||
|
||||
verify(apiGatewayV2Service).createIntegration(eq(REGION), eq(API_ID),
|
||||
argThat(req -> "VPC_LINK".equals(req.get("connectionType")) && "vl-1".equals(req.get("connectionId"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInPlaceVpcLinkUpdateRestoresTagsAndSendsOnlyChangedTags() throws Exception {
|
||||
String arn = "arn:aws:apigateway:us-east-1::/vpclinks/vl-1";
|
||||
VpcLink prior = vpcLink("vl-1", List.of("subnet-a"));
|
||||
prior.setName("old-name");
|
||||
prior.setTags(new HashMap<>(Map.of("floci:override-id", "vl-1", "Env", "old")));
|
||||
when(apiGatewayV2Service.getVpcLink(REGION, "vl-1")).thenReturn(prior);
|
||||
when(apiGatewayV2Service.getTags(arn)).thenReturn(
|
||||
Map.of("floci:override-id", "vl-1", "Env", "old"),
|
||||
Map.of("floci:override-id", "vl-1", "Env", "new"));
|
||||
when(apiGatewayV2Service.updateVpcLink(REGION, "vl-1", Map.of("name", "new-name")))
|
||||
.thenThrow(new AwsException("BadRequestException", "rename failed", 400));
|
||||
|
||||
StackResource link = provisionVpcLink("""
|
||||
{"Name":"new-name","SubnetIds":["subnet-a"],"Tags":{"floci:override-id":"vl-1","Env":"new"}}
|
||||
""", "vl-1", Map.of("VpcLinkId", "vl-1"));
|
||||
|
||||
assertTrue(link.getStatus().endsWith("_FAILED"), link.getStatus());
|
||||
verify(apiGatewayV2Service).tagResource(arn, Map.of("Env", "new"));
|
||||
verify(apiGatewayV2Service).tagResource(arn, Map.of("Env", "old"));
|
||||
verify(apiGatewayV2Service).updateVpcLink(REGION, "vl-1", Map.of("name", "old-name"));
|
||||
assertFalse(link.getAttributes().containsKey("__FlociUpdateRollbackFailure"));
|
||||
assertFalse(link.getAttributes().containsKey("__FlociVpcLinkUpdateSnapshot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void integrationUpdateWithoutConnectionResetsItToInternet() throws Exception {
|
||||
stubIntegrationUpdate(priorVpcLinkIntegration());
|
||||
|
||||
StackResource integration = provisionIntegration("""
|
||||
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend"}
|
||||
""");
|
||||
|
||||
assertTrue(integration.getStatus().endsWith("_COMPLETE"), integration.getStatus());
|
||||
verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "INTERNET", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackOfAnIntegrationUpdateRestoresItsConnection() throws Exception {
|
||||
stubIntegrationUpdate(priorVpcLinkIntegration());
|
||||
StackResource integration = provisionIntegration("""
|
||||
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
|
||||
"ConnectionType":"VPC_LINK","ConnectionId":"vl-2"}
|
||||
""");
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(integration));
|
||||
|
||||
verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "VPC_LINK", "vl-1");
|
||||
assertFalse(integration.getAttributes().containsKey("__FlociIntegrationConnectionSnapshot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackOfAnIntegrationUpdateWithOtherChangesRestoresConnectionButReportsFailure() throws Exception {
|
||||
stubIntegrationUpdate(priorVpcLinkIntegration());
|
||||
StackResource integration = provisionIntegration("""
|
||||
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://other-backend",
|
||||
"ConnectionType":"VPC_LINK","ConnectionId":"vl-2"}
|
||||
""");
|
||||
|
||||
assertFalse(provisioner.rollbackUpdate(integration), "the IntegrationUri change has no rollback");
|
||||
|
||||
verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "VPC_LINK", "vl-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedIntegrationUpdateRestoresItsConnection() throws Exception {
|
||||
stubIntegrationUpdate(priorVpcLinkIntegration());
|
||||
when(apiGatewayV2Service.updateIntegration(eq(REGION), eq(API_ID), eq("int-1"), anyMap()))
|
||||
.thenThrow(new AwsException("NotFoundException", "Integration not found", 404));
|
||||
|
||||
StackResource integration = provisionIntegration("""
|
||||
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
|
||||
"ConnectionType":"VPC_LINK","ConnectionId":"vl-2"}
|
||||
""");
|
||||
|
||||
assertTrue(integration.getStatus().endsWith("_FAILED"), integration.getStatus());
|
||||
InOrder order = inOrder(apiGatewayV2Service);
|
||||
order.verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "VPC_LINK", "vl-2");
|
||||
order.verify(apiGatewayV2Service).updateIntegration(eq(REGION), eq(API_ID), eq("int-1"), anyMap());
|
||||
order.verify(apiGatewayV2Service).replaceIntegrationConnection(REGION, API_ID, "int-1", "VPC_LINK", "vl-1");
|
||||
assertFalse(integration.getAttributes().containsKey("__FlociUpdateRollbackFailure"));
|
||||
assertFalse(integration.getAttributes().containsKey("__FlociIntegrationConnectionSnapshot"));
|
||||
}
|
||||
|
||||
private static Integration priorVpcLinkIntegration() {
|
||||
Integration prior = new Integration();
|
||||
prior.setIntegrationId("int-1");
|
||||
prior.setIntegrationType("HTTP_PROXY");
|
||||
prior.setIntegrationUri("http://backend");
|
||||
prior.setPayloadFormatVersion("2.0");
|
||||
prior.setConnectionType("VPC_LINK");
|
||||
prior.setConnectionId("vl-1");
|
||||
return prior;
|
||||
}
|
||||
|
||||
private void stubIntegrationUpdate(Integration prior) {
|
||||
when(apiGatewayV2Service.getIntegration(REGION, API_ID, "int-1")).thenReturn(prior);
|
||||
when(apiGatewayV2Service.updateIntegration(eq(REGION), eq(API_ID), eq("int-1"), anyMap())).thenReturn(prior);
|
||||
when(apiGatewayV2Service.replaceIntegrationConnection(eq(REGION), eq(API_ID), eq("int-1"), anyString(), any()))
|
||||
.thenReturn(prior);
|
||||
}
|
||||
|
||||
private StackResource provisionIntegration(String properties) throws Exception {
|
||||
return provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree(properties),
|
||||
engine(), REGION, "000000000000", "test-stack", "int-1", Map.of("IntegrationId", "int-1"));
|
||||
}
|
||||
|
||||
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 StackResource provisionVpcLink(String properties, String existingPhysicalId,
|
||||
Map<String, String> existingAttributes) throws Exception {
|
||||
return provisioner.provision("VpcLink", "AWS::ApiGatewayV2::VpcLink", mapper.readTree(properties),
|
||||
engine(), REGION, "000000000000", "test-stack", existingPhysicalId, existingAttributes);
|
||||
}
|
||||
|
||||
private static VpcLink vpcLink(String id, List<String> subnetIds) {
|
||||
VpcLink link = new VpcLink();
|
||||
link.setVpcLinkId(id);
|
||||
link.setName("my-link");
|
||||
link.setSubnetIds(subnetIds);
|
||||
return link;
|
||||
}
|
||||
|
||||
private JsonNode body(String body) throws Exception {
|
||||
return mapper.readTree("""
|
||||
{"Name":"test-api","ProtocolType":"HTTP","Body":%s}
|
||||
|
||||
+8
@@ -27,6 +27,14 @@ class CfnCreateOnlyPropertiesTest {
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::S3::Bucket", "VersioningConfiguration"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isCreateOnly_vpcLinkReplacesOnlyForSubnetsAndSecurityGroups() {
|
||||
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "SubnetIds"));
|
||||
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "SecurityGroupIds"));
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "Name"));
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "Tags"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
|
||||
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
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.Integration;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.VpcLink;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* AWS::ApiGatewayV2::VpcLink through a real stack: Ref and Fn::GetAtt VpcLinkId resolve to the
|
||||
* real link, an integration can use it through ConnectionId, a Name change updates the link in
|
||||
* place, a SubnetIds change replaces it, and DeleteStack removes it. A failed update puts the link
|
||||
* and the integration connection back.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationApiGatewayV2VpcLinkIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String STACK_NAME = "vpclink-stack";
|
||||
private static final String VPC_LINK_CONNECTION =
|
||||
",\"ConnectionType\":\"VPC_LINK\",\"ConnectionId\":{\"Ref\":\"VpcLink\"}";
|
||||
private static final String FAILING_RESOURCE =
|
||||
",\"Broken\":{\"Type\":\"AWS::ApiGatewayV2::VpcLink\",\"DependsOn\":\"Integration\","
|
||||
+ "\"Properties\":{\"Name\":\"broken\"}}";
|
||||
|
||||
@Inject
|
||||
ApiGatewayV2Service apiGatewayV2Service;
|
||||
|
||||
@Inject
|
||||
CloudFormationService cloudFormationService;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcLinkLifecycleFollowsTheCloudFormationUpdateRules() {
|
||||
stackAction("CreateStack", STACK_NAME, template("first-name", "subnet-aaaa1111"));
|
||||
waitForStackStatus(STACK_NAME, "CREATE_COMPLETE");
|
||||
|
||||
Stack created = stack(STACK_NAME);
|
||||
String vpcLinkId = created.getOutputs().get("VpcLinkRef");
|
||||
assertEquals(vpcLinkId, created.getOutputs().get("VpcLinkIdAttr"));
|
||||
VpcLink link = apiGatewayV2Service.getVpcLink(REGION, vpcLinkId);
|
||||
assertEquals("first-name", link.getName());
|
||||
assertEquals(List.of("subnet-aaaa1111"), link.getSubnetIds());
|
||||
assertEquals(Map.of("Env", "test"), link.getTags());
|
||||
Integration integration = integration(created);
|
||||
assertEquals("VPC_LINK", integration.getConnectionType());
|
||||
assertEquals(vpcLinkId, integration.getConnectionId());
|
||||
|
||||
stackAction("UpdateStack", STACK_NAME, template("second-name", "subnet-aaaa1111"));
|
||||
waitForStackStatus(STACK_NAME, "UPDATE_COMPLETE");
|
||||
assertEquals(vpcLinkId, stack(STACK_NAME).getOutputs().get("VpcLinkRef"), "a Name change keeps the same link");
|
||||
assertEquals("second-name", apiGatewayV2Service.getVpcLink(REGION, vpcLinkId).getName());
|
||||
|
||||
stackAction("UpdateStack", STACK_NAME, template("second-name", "subnet-bbbb2222"));
|
||||
waitForStackStatus(STACK_NAME, "UPDATE_COMPLETE");
|
||||
Stack replaced = stack(STACK_NAME);
|
||||
String newVpcLinkId = replaced.getOutputs().get("VpcLinkRef");
|
||||
assertNotEquals(vpcLinkId, newVpcLinkId, "a SubnetIds change replaces the link");
|
||||
assertEquals(List.of("subnet-bbbb2222"), apiGatewayV2Service.getVpcLink(REGION, newVpcLinkId).getSubnetIds());
|
||||
assertNotFound(vpcLinkId);
|
||||
assertEquals(newVpcLinkId, integration(replaced).getConnectionId());
|
||||
|
||||
stackAction("DeleteStack", STACK_NAME, null);
|
||||
waitForStackStatus(STACK_NAME, "DELETE_COMPLETE");
|
||||
assertNotFound(newVpcLinkId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedUpdateRestoresTheIntegrationConnectionAndDeletesTheNewLink() {
|
||||
String stackName = "vpclink-rollback-stack";
|
||||
stackAction("CreateStack", stackName,
|
||||
template("rollback-link", "subnet-aaaa1111", "{}", VPC_LINK_CONNECTION, ""));
|
||||
waitForStackStatus(stackName, "CREATE_COMPLETE");
|
||||
String vpcLinkId = stack(stackName).getOutputs().get("VpcLinkRef");
|
||||
|
||||
stackAction("UpdateStack", stackName,
|
||||
template("rollback-link", "subnet-bbbb2222", "{}", VPC_LINK_CONNECTION, FAILING_RESOURCE));
|
||||
waitForStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
Stack rolledBack = stack(stackName);
|
||||
assertEquals(vpcLinkId, rolledBack.getOutputs().get("VpcLinkRef"));
|
||||
assertEquals(List.of("subnet-aaaa1111"), apiGatewayV2Service.getVpcLink(REGION, vpcLinkId).getSubnetIds());
|
||||
Integration integration = integration(rolledBack);
|
||||
assertEquals("VPC_LINK", integration.getConnectionType());
|
||||
assertEquals(vpcLinkId, integration.getConnectionId());
|
||||
assertEquals(1, apiGatewayV2Service.getVpcLinks(REGION).stream()
|
||||
.filter(link -> "rollback-link".equals(link.getName()))
|
||||
.count(), "the link created by the failed update is deleted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingTheConnectionFromTheTemplateResetsTheIntegrationToInternet() {
|
||||
String stackName = "vpclink-connection-stack";
|
||||
stackAction("CreateStack", stackName,
|
||||
template("connection-link", "subnet-aaaa1111", "{}", VPC_LINK_CONNECTION, ""));
|
||||
waitForStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
stackAction("UpdateStack", stackName, template("connection-link", "subnet-aaaa1111", "{}", "", ""));
|
||||
waitForStackStatus(stackName, "UPDATE_COMPLETE");
|
||||
|
||||
Integration integration = integration(stack(stackName));
|
||||
assertEquals("INTERNET", integration.getConnectionType());
|
||||
assertNull(integration.getConnectionId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renamingALinkKeepsAReservedTagSetAtCreation() {
|
||||
String stackName = "vpclink-reserved-tag-stack";
|
||||
String tags = "{\"floci:note\":\"kept\",\"Env\":\"test\"}";
|
||||
stackAction("CreateStack", stackName, template("reserved-v1", "subnet-aaaa1111", tags, "", ""));
|
||||
waitForStackStatus(stackName, "CREATE_COMPLETE");
|
||||
String vpcLinkId = stack(stackName).getOutputs().get("VpcLinkRef");
|
||||
|
||||
stackAction("UpdateStack", stackName, template("reserved-v2", "subnet-aaaa1111", tags, "", ""));
|
||||
waitForStackStatus(stackName, "UPDATE_COMPLETE");
|
||||
|
||||
VpcLink link = apiGatewayV2Service.getVpcLink(REGION, vpcLinkId);
|
||||
assertEquals("reserved-v2", link.getName());
|
||||
assertEquals(Map.of("floci:note", "kept", "Env", "test"), link.getTags());
|
||||
}
|
||||
|
||||
private void assertNotFound(String vpcLinkId) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> apiGatewayV2Service.getVpcLink(REGION, vpcLinkId));
|
||||
assertEquals("NotFoundException", e.getErrorCode());
|
||||
}
|
||||
|
||||
private Integration integration(Stack stack) {
|
||||
StackResource api = stack.getResources().get("HttpApi");
|
||||
StackResource integration = stack.getResources().get("Integration");
|
||||
return apiGatewayV2Service.getIntegration(REGION, api.getPhysicalId(), integration.getPhysicalId());
|
||||
}
|
||||
|
||||
private Stack stack(String stackName) {
|
||||
return cloudFormationService.describeStacks(stackName, REGION).getFirst();
|
||||
}
|
||||
|
||||
private static void stackAction(String action, String stackName, String template) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stackName);
|
||||
if (template != null) {
|
||||
request.formParam("TemplateBody", template);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private void waitForStackStatus(String stackName, String expected) {
|
||||
String status = null;
|
||||
for (int attempt = 0; attempt < 200; attempt++) {
|
||||
try {
|
||||
status = cloudFormationService.describeStacks(stackName, REGION).getFirst().getStatus();
|
||||
} catch (AwsException e) {
|
||||
// A deleted stack can no longer be described by name.
|
||||
status = "DELETE_COMPLETE";
|
||||
}
|
||||
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 + ", last status " + status);
|
||||
}
|
||||
|
||||
private static String template(String linkName, String subnetId) {
|
||||
return """
|
||||
{"Resources":{
|
||||
"VpcLink":{"Type":"AWS::ApiGatewayV2::VpcLink","Properties":{
|
||||
"Name":"%s","SubnetIds":["%s"],"SecurityGroupIds":["sg-cccc3333"],"Tags":{"Env":"test"}}},
|
||||
"HttpApi":{"Type":"AWS::ApiGatewayV2::Api","Properties":{
|
||||
"Name":"vpclink-api","ProtocolType":"HTTP"}},
|
||||
"Integration":{"Type":"AWS::ApiGatewayV2::Integration","Properties":{
|
||||
"ApiId":{"Ref":"HttpApi"},"IntegrationType":"HTTP_PROXY","IntegrationMethod":"ANY",
|
||||
"IntegrationUri":"arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/alb/1/2",
|
||||
"ConnectionType":"VPC_LINK","ConnectionId":{"Ref":"VpcLink"},
|
||||
"PayloadFormatVersion":"1.0"}}},
|
||||
"Outputs":{
|
||||
"VpcLinkRef":{"Value":{"Ref":"VpcLink"}},
|
||||
"VpcLinkIdAttr":{"Value":{"Fn::GetAtt":["VpcLink","VpcLinkId"]}}}}
|
||||
""".formatted(linkName, subnetId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A link, an HTTP API and an integration. {@code connection} adds integration properties and
|
||||
* {@code extraResources} adds resources, both as JSON fragments that start with a comma.
|
||||
*/
|
||||
private static String template(String linkName, String subnetId, String tags, String connection,
|
||||
String extraResources) {
|
||||
return """
|
||||
{"Resources":{
|
||||
"VpcLink":{"Type":"AWS::ApiGatewayV2::VpcLink","Properties":{
|
||||
"Name":"%s","SubnetIds":["%s"],"Tags":%s}},
|
||||
"HttpApi":{"Type":"AWS::ApiGatewayV2::Api","Properties":{
|
||||
"Name":"vpclink-api","ProtocolType":"HTTP"}},
|
||||
"Integration":{"Type":"AWS::ApiGatewayV2::Integration","Properties":{
|
||||
"ApiId":{"Ref":"HttpApi"},"IntegrationType":"HTTP_PROXY","IntegrationMethod":"ANY",
|
||||
"IntegrationUri":"http://backend.example","PayloadFormatVersion":"1.0"%s}}%s},
|
||||
"Outputs":{"VpcLinkRef":{"Value":{"Ref":"VpcLink"}}}}
|
||||
""".formatted(linkName, subnetId, tags, connection, extraResources);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ AWS::ApiGatewayV2::Deployment ApiGatewayV2CfnProvisioner
|
||||
AWS::ApiGatewayV2::Integration ApiGatewayV2CfnProvisioner
|
||||
AWS::ApiGatewayV2::Route ApiGatewayV2CfnProvisioner
|
||||
AWS::ApiGatewayV2::Stage ApiGatewayV2CfnProvisioner
|
||||
AWS::ApiGatewayV2::VpcLink ApiGatewayV2CfnProvisioner
|
||||
AWS::AppSync::ApiKey AppSyncCfnProvisioner
|
||||
AWS::AppSync::DataSource AppSyncCfnProvisioner
|
||||
AWS::AppSync::FunctionConfiguration AppSyncCfnProvisioner
|
||||
|
||||
|
Reference in new issue
Block a user