mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): expose RegionalEndpoints of a web function endpoint to Fn::GetAtt (#6907)
This commit is contained in:
1 parent
5f89a70095
commit
c4ae11c414
11 files changed
+232
-18
No files matched your search
+62
@@ -1,17 +1,21 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebCodeBuckets;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebRoles;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
@@ -35,6 +39,10 @@ class CloudFormationLambdaWebIntegrationTest {
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
|
||||
private static final String BUCKET = "cfn-web-code";
|
||||
private static final String PROBE_TOKEN = "arn:aws:lambda:us-east-1:000000000000:function:cfn-web-regional-probe";
|
||||
|
||||
@InjectMock
|
||||
LambdaService lambdaService;
|
||||
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
@@ -144,6 +152,60 @@ class CloudFormationLambdaWebIntegrationTest {
|
||||
.then().statusCode(404));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCustomResourceIsGivenRegionalEndpointsAsAnObject() {
|
||||
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");
|
||||
LambdaWebCodeBuckets.create(s3Service, BUCKET);
|
||||
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String functionName = "cfn-web-probe-" + suffix;
|
||||
String stackName = "cfn-web-probe-stack-" + suffix;
|
||||
CustomResourceProbe handler = CustomResourceProbe.stub(lambdaService, PROBE_TOKEN, "regional-probe");
|
||||
String probe = """
|
||||
"Probe": {
|
||||
"Type": "Custom::Probe",
|
||||
"Properties": {"ServiceToken": "%s", "Value": {"Fn::GetAtt": ["Ep", "RegionalEndpoints"]}}
|
||||
},
|
||||
""".formatted(PROBE_TOKEN);
|
||||
|
||||
cloudFormation(stackName, "CreateStack", template(functionName, 30, probe));
|
||||
await().untilAsserted(() -> describeStacks(stackName, "CREATE_COMPLETE"));
|
||||
String revisionId = outputs(describeStacks(stackName, "CREATE_COMPLETE")).get("RevId");
|
||||
JsonNode value = handler.request("Create").path("ResourceProperties").path("Value");
|
||||
assertEquals(List.of("us-east-1"), value.properties().stream().map(Map.Entry::getKey).toList());
|
||||
JsonNode home = value.path("us-east-1");
|
||||
assertEquals(List.of("AuthType", "RevisionWeights", "State", "StateReason"),
|
||||
home.properties().stream().map(Map.Entry::getKey).toList());
|
||||
assertEquals("ApplicationManaged", home.path("AuthType").asText());
|
||||
assertEquals(revisionId, home.path("RevisionWeights").path(0).path("RevisionId").asText());
|
||||
// The custom resource stringifies every scalar it is given, so the weight is compared as text.
|
||||
assertEquals("100", home.path("RevisionWeights").path(0).path("Weight").asText());
|
||||
assertEquals("Active", home.path("State").asText());
|
||||
assertEquals("The endpoint is active in the region.", home.path("StateReason").asText());
|
||||
|
||||
cloudFormation(stackName, "DeleteStack", null);
|
||||
await().untilAsserted(() -> given().when().get("/2025-03-07/web-functions/" + functionName)
|
||||
.then().statusCode(404));
|
||||
}
|
||||
|
||||
@Test
|
||||
void regionalEndpointsIsAnObjectThatAnOutputCannotHold() {
|
||||
LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");
|
||||
LambdaWebCodeBuckets.create(s3Service, BUCKET);
|
||||
s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String functionName = "cfn-web-regional-" + suffix;
|
||||
String stackName = "cfn-web-regional-stack-" + suffix;
|
||||
String state = "\"EpState\": {\"Value\": {\"Fn::GetAtt\": [\"Ep\", \"State\"]}}";
|
||||
|
||||
cloudFormation(stackName, "CreateStack", template(functionName, 30).replace(state,
|
||||
state + ", \"EpRegional\": {\"Value\": {\"Fn::GetAtt\": [\"Ep\", \"RegionalEndpoints\"]}}"));
|
||||
await().untilAsserted(() -> describeStacks(stackName, "ROLLBACK_COMPLETE"));
|
||||
stackEvents(stackName).body(containsString("Template format error: Every Value member must be a string."));
|
||||
given().when().get("/2025-03-07/web-functions/" + functionName).then().statusCode(404);
|
||||
cloudFormation(stackName, "DeleteStack", null);
|
||||
}
|
||||
|
||||
private static ValidatableResponse stackEvents(String stackName) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The handler of a custom resource in a stack test. It stands in for the ServiceToken Lambda on a
|
||||
* mocked {@link LambdaService}, keeps every request it is sent, and answers each the way a handler
|
||||
* does: a PUT of a SUCCESS result to the event's {@code ResponseURL}.
|
||||
*/
|
||||
final class CustomResourceProbe {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final List<JsonNode> events = new CopyOnWriteArrayList<>();
|
||||
private final String physicalId;
|
||||
|
||||
private CustomResourceProbe(String physicalId) {
|
||||
this.physicalId = physicalId;
|
||||
}
|
||||
|
||||
static CustomResourceProbe stub(LambdaService lambdaService, String serviceToken, String physicalId) {
|
||||
CustomResourceProbe probe = new CustomResourceProbe(physicalId);
|
||||
when(lambdaService.invoke(any(), eq(serviceToken), any(), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(invocation -> {
|
||||
JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
|
||||
probe.events.add(event);
|
||||
probe.succeed(event);
|
||||
return new InvokeResult(200, null, "null".getBytes(StandardCharsets.UTF_8), null, "req-1");
|
||||
});
|
||||
return probe;
|
||||
}
|
||||
|
||||
/** The first request of {@code requestType}, such as Create. */
|
||||
JsonNode request(String requestType) {
|
||||
return events.stream().filter(event -> requestType.equals(event.path("RequestType").asText()))
|
||||
.findFirst().orElseThrow(() -> new AssertionError("No " + requestType + " request in " + events));
|
||||
}
|
||||
|
||||
private void succeed(JsonNode event) {
|
||||
ObjectNode response = MAPPER.createObjectNode().put("Status", "SUCCESS")
|
||||
.put("RequestId", event.get("RequestId").asText())
|
||||
.put("StackId", event.get("StackId").asText())
|
||||
.put("LogicalResourceId", event.get("LogicalResourceId").asText())
|
||||
.put("PhysicalResourceId", physicalId);
|
||||
given().body(response.toString()).when().put(URI.create(event.get("ResponseURL").asText()).getPath())
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
+37
-1
@@ -44,7 +44,8 @@ class LambdaWebCfnProvisionerTest {
|
||||
private static final Set<String> REVISION_ATTRIBUTES =
|
||||
Set.of("FunctionArn", "RevisionArn", "RevisionId", "State", "StateReason", "CreatedAt");
|
||||
private static final Set<String> ENDPOINT_ATTRIBUTES =
|
||||
Set.of("FunctionArn", "EndpointArn", "DomainName", "State", "StateReason", "CreatedAt", "UpdatedAt");
|
||||
Set.of("FunctionArn", "EndpointArn", "DomainName", "RegionalEndpoints", "State", "StateReason", "CreatedAt",
|
||||
"UpdatedAt");
|
||||
|
||||
private final LambdaWebService service = mock(LambdaWebService.class);
|
||||
private final LambdaWebCfnProvisioner provisioner = new LambdaWebCfnProvisioner(service);
|
||||
@@ -371,6 +372,34 @@ class LambdaWebCfnProvisionerTest {
|
||||
assertEquals("The endpoint is active and invokable.", r.getAttributes().get("StateReason"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void regionalEndpointsIsTheApiBlockInPascalCase() {
|
||||
WebFunctionEndpoint created = endpoint("prod", "PerRegion", List.of("us-east-1", "us-west-2"));
|
||||
created.authType = "ApplicationManaged";
|
||||
WebFunctionEndpoint.RevisionWeight weight = new WebFunctionEndpoint.RevisionWeight();
|
||||
weight.revisionId = "rev-aaaaa";
|
||||
weight.weight = 100;
|
||||
created.revisionWeights.add(weight);
|
||||
created.scalingConfig = new WebFunctionEndpoint.ScalingConfig();
|
||||
created.scalingConfig.maxEnvironments = 3;
|
||||
created.regionalDomainNames.put("us-east-1", "abc.001.lambda-web.us-east-1.localhost:4566");
|
||||
created.regionalDomainNames.put("us-west-2", "abc.001.lambda-web.us-west-2.localhost:4566");
|
||||
when(service.createEndpoint(eq(REGION), eq("app"), any())).thenReturn(created);
|
||||
StackResource r = resource(LambdaWebCfnProvisioner.ENDPOINT);
|
||||
|
||||
provisioner.provision(r, endpointProps("PerRegion"), ctx(null));
|
||||
|
||||
String entry = "{\"AuthType\":\"ApplicationManaged\",\"DomainName\":\"abc.001.lambda-web.%s.localhost:4566\","
|
||||
+ "\"RevisionWeights\":[{\"RevisionId\":\"rev-aaaaa\",\"Weight\":100}],"
|
||||
+ "\"ScalingConfig\":{\"MaxEnvironments\":3},\"State\":\"Active\","
|
||||
+ "\"StateReason\":\"The endpoint is active in the region.\"}";
|
||||
assertEquals("{\"us-east-1\":" + entry.formatted("us-east-1") + ",\"us-west-2\":" + entry.formatted("us-west-2")
|
||||
+ "}", provisioner.attributeValue(LambdaWebCfnProvisioner.ENDPOINT, "RegionalEndpoints",
|
||||
r.getAttributes().get("RegionalEndpoints")).toString());
|
||||
assertEquals("Active", provisioner.attributeValue(LambdaWebCfnProvisioner.ENDPOINT, "State",
|
||||
r.getAttributes().get("State")).textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointWithTheSameIdentityIsUpdatedInPlace() {
|
||||
WebFunctionEndpoint existing = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
@@ -405,7 +434,14 @@ class LambdaWebCfnProvisionerTest {
|
||||
assertEquals("The endpoint is updated.", r.getAttributes().get("UpdateStatusReason"));
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
// A failed stack update puts the prior configuration back.
|
||||
WebFunctionEndpoint restoredEndpoint = endpoint("prod", "HomeRegion", List.of("us-east-1"));
|
||||
restoredEndpoint.authType = "ApplicationManaged";
|
||||
when(service.updateEndpoint(eq(REGION), eq(FN_ARN), eq("prod"), any()))
|
||||
.thenReturn(new LambdaWebService.EndpointUpdate(updated, restoredEndpoint));
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
assertEquals("ApplicationManaged", provisioner.attributeValue(LambdaWebCfnProvisioner.ENDPOINT,
|
||||
"RegionalEndpoints", r.getAttributes().get("RegionalEndpoints")).path("us-east-1").path("AuthType")
|
||||
.textValue(), "the restored endpoint's regional block");
|
||||
ArgumentCaptor<JsonNode> restored = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updateEndpoint(eq(REGION), eq(FN_ARN), eq("prod"), restored.capture());
|
||||
assertEquals("ApplicationManaged", restored.getValue().path("authType").asText());
|
||||
|
||||
Reference in new issue
Block a user