mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): provision Transfer Family servers (#4809)
* feat(cloudformation): provision Transfer Family servers * fix(cloudformation): clear Transfer update snapshot after success * test(cloudformation): cover Transfer tag rollback * fix(cloudformation): match Transfer server return values
This commit is contained in:
1 parent
2bdfe45207
commit
bcb50b765f
13 files changed
+944
-19
No files matched your search
+11
@@ -29,6 +29,7 @@ import io.github.hectorvent.floci.services.ec2.FlowLogService;
|
||||
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.transfer.TransferService;
|
||||
import io.github.hectorvent.floci.services.wafv2.WafV2Service;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AcmCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayAccountCfnProvisioner;
|
||||
@@ -90,6 +91,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftC
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Route53CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.S3CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SchedulerScheduleGroupCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.TransferCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretTargetAttachmentCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretsManagerCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SnsCfnProvisioner;
|
||||
@@ -199,6 +201,7 @@ final class CfnProvisionerFixture {
|
||||
private Route53Service route53Service;
|
||||
private CloudTrailService cloudTrailService;
|
||||
private SchedulerService schedulerService;
|
||||
private TransferService transferService;
|
||||
// Services that back a provisioner without being a constructor argument of the
|
||||
// dispatcher. They exist only so inferredProvisioners() can wire their provisioner.
|
||||
private FlowLogService flowLogService;
|
||||
@@ -420,6 +423,9 @@ final class CfnProvisionerFixture {
|
||||
if (schedulerService != null) {
|
||||
discovered.add(new SchedulerScheduleGroupCfnProvisioner(schedulerService));
|
||||
}
|
||||
if (transferService != null) {
|
||||
discovered.add(new TransferCfnProvisioner(transferService));
|
||||
}
|
||||
if (redshiftService != null) {
|
||||
discovered.add(new RedshiftClusterCfnProvisioner(redshiftService));
|
||||
}
|
||||
@@ -569,6 +575,11 @@ final class CfnProvisionerFixture {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder transfer(TransferService v) {
|
||||
this.transferService = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder eks(EksService v) {
|
||||
this.eksService = v;
|
||||
return this;
|
||||
|
||||
+21
-8
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@@ -36,15 +37,21 @@ final class CfnStackWaits {
|
||||
* ten seconds without a terminal status fails too.
|
||||
*/
|
||||
static StackState awaitTerminal(String stackName) {
|
||||
return awaitTerminal(stackName, null);
|
||||
}
|
||||
|
||||
static StackState awaitTerminal(String stackName, String authorization) {
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
StackState last = new StackState(null, "");
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
Response response = given()
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/");
|
||||
.formParam("StackName", stackName);
|
||||
if (authorization != null) {
|
||||
request.header("Authorization", authorization);
|
||||
}
|
||||
Response response = request.when().post("/");
|
||||
if (response.statusCode() != 200) {
|
||||
fail("DescribeStacks " + stackName + " answered " + response.statusCode() + ": " + response.asString());
|
||||
}
|
||||
@@ -71,15 +78,21 @@ final class CfnStackWaits {
|
||||
* DELETE_FAILED or after ten seconds.
|
||||
*/
|
||||
static void awaitStackDeleted(String stackName) {
|
||||
awaitStackDeleted(stackName, null);
|
||||
}
|
||||
|
||||
static void awaitStackDeleted(String stackName, String authorization) {
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
String body = "";
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
Response response = given()
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/");
|
||||
.formParam("StackName", stackName);
|
||||
if (authorization != null) {
|
||||
request.header("Authorization", authorization);
|
||||
}
|
||||
Response response = request.when().post("/");
|
||||
body = response.asString();
|
||||
assertThat(body, not(containsString("<StackStatus>DELETE_FAILED</StackStatus>")));
|
||||
if (response.statusCode() == 400) {
|
||||
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
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.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationTransferServerIntegrationTest {
|
||||
|
||||
@Inject
|
||||
CloudFormationService cloudFormationService;
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/cloudformation/aws4_request";
|
||||
private static final String TRANSFER_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/transfer/aws4_request";
|
||||
private static final String WEST_CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261001/us-west-2/cloudformation/aws4_request";
|
||||
private static final String WEST_TRANSFER_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261001/us-west-2/transfer/aws4_request";
|
||||
private static final String STACK = "cfn-transfer-server-integration";
|
||||
private static final String ROLLBACK_STACK = "cfn-transfer-server-rollback-integration";
|
||||
private static final String WEST_STACK = "cfn-transfer-server-west-integration";
|
||||
private static final String LEGACY_STACK = "cfn-transfer-server-legacy-integration";
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Resources": {
|
||||
"Server": {
|
||||
"Type": "AWS::Transfer::Server",
|
||||
"Properties": {
|
||||
%s
|
||||
}
|
||||
},
|
||||
"Defaulted": {"Type": "AWS::Transfer::Server"}
|
||||
},
|
||||
"Outputs": {
|
||||
"ServerRef": {"Value": {"Ref": "Server"}},
|
||||
"ServerId": {"Value": {"Fn::GetAtt": ["Server", "ServerId"]}},
|
||||
"ServerArn": {"Value": {"Fn::GetAtt": ["Server", "Arn"]}},
|
||||
"ServerState": {"Value": {"Fn::GetAtt": ["Server", "State"]}},
|
||||
"DefaultedRef": {"Value": {"Ref": "Defaulted"}},
|
||||
"DefaultedId": {"Value": {"Fn::GetAtt": ["Defaulted", "ServerId"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
private static final String ROLLBACK_TEMPLATE = """
|
||||
{
|
||||
"Resources": {
|
||||
"Server": {"Type":"AWS::Transfer::Server", "Properties":{
|
||||
"LoggingRole":"%s", "Tags":[{"Key":"stage","Value":"%s"}]
|
||||
}}%s
|
||||
},
|
||||
"Outputs": {
|
||||
"ServerRef":{"Value":{"Ref":"Server"}},
|
||||
"ServerId":{"Value":{"Fn::GetAtt":["Server","ServerId"]}},
|
||||
"ServerArn":{"Value":{"Fn::GetAtt":["Server","Arn"]}},
|
||||
"ServerState":{"Value":{"Fn::GetAtt":["Server","State"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUpdateAndDeleteBackedServers() {
|
||||
cloudFormation("CreateStack", template("role-1", "TransferSecurityPolicy-2023-05", "first"));
|
||||
Map<String, String> outputs = outputs("CREATE_COMPLETE");
|
||||
String serverId = outputs.get("ServerId");
|
||||
String serverArn = outputs.get("ServerArn");
|
||||
String defaultedId = outputs.get("DefaultedId");
|
||||
assertEquals(serverArn, outputs.get("ServerRef"));
|
||||
assertTrue(serverArn.endsWith("server/" + serverId));
|
||||
assertTrue(outputs.get("DefaultedRef").endsWith("server/" + defaultedId));
|
||||
assertEquals("ONLINE", outputs.get("ServerState"));
|
||||
describeServer(serverId)
|
||||
.body("Server.ServerId", equalTo(serverId))
|
||||
.body("Server.Arn", equalTo(outputs.get("ServerArn")))
|
||||
.body("Server.LoggingRole", equalTo("role-1"))
|
||||
.body("Server.Tags[0].Key", equalTo("stage"))
|
||||
.body("Server.Tags[0].Value", equalTo("first"));
|
||||
describeServer(defaultedId)
|
||||
.body("Server.Domain", equalTo("S3"))
|
||||
.body("Server.EndpointType", equalTo("PUBLIC"))
|
||||
.body("Server.IdentityProviderType", equalTo("SERVICE_MANAGED"))
|
||||
.body("Server.Protocols", hasItem("SFTP"));
|
||||
tagServer(outputs.get("ServerArn"), "external", "keep");
|
||||
|
||||
cloudFormation("UpdateStack", template("role-2", "TransferSecurityPolicy-2020-06", "second"));
|
||||
Map<String, String> updatedOutputs = outputs("UPDATE_COMPLETE");
|
||||
assertEquals(serverId, updatedOutputs.get("ServerId"));
|
||||
assertEquals(serverArn, updatedOutputs.get("ServerRef"));
|
||||
assertEquals("ONLINE", updatedOutputs.get("ServerState"));
|
||||
StackResource updated = cloudFormationService.describeStackResources(STACK, "us-east-1").stream()
|
||||
.filter(resource -> "Server".equals(resource.getLogicalId()))
|
||||
.findFirst().orElseThrow();
|
||||
assertNull(updated.getAttributes().get("__FlociTransferServerUpdateSnapshot"));
|
||||
describeServer(serverId)
|
||||
.body("Server.LoggingRole", equalTo("role-2"))
|
||||
.body("Server.SecurityPolicyName", equalTo("TransferSecurityPolicy-2020-06"))
|
||||
.body("Server.Tags.find { it.Key == 'stage' }.Value", equalTo("second"))
|
||||
.body("Server.Tags.find { it.Key == 'external' }.Value", equalTo("keep"));
|
||||
|
||||
cloudFormation("UpdateStack", TEMPLATE.formatted("\"Protocols\": [\"SFTP\"]"));
|
||||
assertEquals(serverArn, outputs("UPDATE_COMPLETE").get("ServerRef"));
|
||||
describeServer(serverId)
|
||||
.body("Server.LoggingRole", nullValue())
|
||||
.body("Server.Tags.find { it.Key == 'stage' }", nullValue())
|
||||
.body("Server.Tags.find { it.Key == 'external' }.Value", equalTo("keep"))
|
||||
.body("Server.SecurityPolicyName", equalTo("TransferSecurityPolicy-2020-06"));
|
||||
|
||||
cloudFormation("DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(STACK);
|
||||
describeServer(serverId).statusCode(404);
|
||||
describeServer(defaultedId).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void laterResourceFailureRestoresServerSettings() {
|
||||
cloudFormation(ROLLBACK_STACK, "CreateStack",
|
||||
ROLLBACK_TEMPLATE.formatted("original-role", "original", ""));
|
||||
Map<String, String> created = outputs(ROLLBACK_STACK, "CREATE_COMPLETE");
|
||||
String serverId = created.get("ServerId");
|
||||
String serverArn = created.get("ServerArn");
|
||||
assertEquals(serverArn, created.get("ServerRef"));
|
||||
describeServer(serverId).body("Server.Tags.find { it.Key == 'stage' }.Value", equalTo("original"));
|
||||
String failingResource = """
|
||||
, "BadServer": {
|
||||
"Type":"AWS::Transfer::Server", "DependsOn":"Server",
|
||||
"Properties":{"WorkflowDetails":{}}
|
||||
}
|
||||
""";
|
||||
|
||||
cloudFormation(ROLLBACK_STACK, "UpdateStack",
|
||||
ROLLBACK_TEMPLATE.formatted("changed-role", "changed", failingResource));
|
||||
Map<String, String> restored = outputs(ROLLBACK_STACK, "UPDATE_ROLLBACK_COMPLETE");
|
||||
assertEquals(serverArn, restored.get("ServerRef"));
|
||||
assertEquals(serverId, restored.get("ServerId"));
|
||||
assertEquals("ONLINE", restored.get("ServerState"));
|
||||
describeServer(serverId)
|
||||
.body("Server.LoggingRole", equalTo("original-role"))
|
||||
.body("Server.Tags.find { it.Key == 'stage' }.Value", equalTo("original"));
|
||||
|
||||
cloudFormation(ROLLBACK_STACK, "UpdateStack",
|
||||
ROLLBACK_TEMPLATE.formatted("retry-role", "retry", ""));
|
||||
Map<String, String> retried = outputs(ROLLBACK_STACK, "UPDATE_COMPLETE");
|
||||
assertEquals(serverArn, retried.get("ServerRef"));
|
||||
assertEquals(serverId, retried.get("ServerId"));
|
||||
describeServer(serverId)
|
||||
.body("Server.LoggingRole", equalTo("retry-role"))
|
||||
.body("Server.Tags.find { it.Key == 'stage' }.Value", equalTo("retry"));
|
||||
|
||||
cloudFormation(ROLLBACK_STACK, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(ROLLBACK_STACK);
|
||||
describeServer(serverId).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverFollowsNonDefaultStackRegionThroughLifecycle() {
|
||||
cloudFormation(WEST_STACK, "CreateStack", TEMPLATE.formatted("\"LoggingRole\":\"west-original\""),
|
||||
WEST_CFN_AUTH);
|
||||
Map<String, String> created = outputs(WEST_STACK, "CREATE_COMPLETE", WEST_CFN_AUTH);
|
||||
String serverId = created.get("ServerId");
|
||||
String serverArn = created.get("ServerArn");
|
||||
assertEquals(serverArn, created.get("ServerRef"));
|
||||
assertTrue(serverArn.contains(":us-west-2:"));
|
||||
assertEquals("ONLINE", created.get("ServerState"));
|
||||
describeServer(serverId, WEST_TRANSFER_AUTH)
|
||||
.statusCode(200)
|
||||
.body("Server.LoggingRole", equalTo("west-original"));
|
||||
describeServer(serverId).statusCode(404);
|
||||
|
||||
cloudFormation(WEST_STACK, "UpdateStack", TEMPLATE.formatted("\"LoggingRole\":\"west-updated\""),
|
||||
WEST_CFN_AUTH);
|
||||
assertEquals(serverArn, outputs(WEST_STACK, "UPDATE_COMPLETE", WEST_CFN_AUTH).get("ServerRef"));
|
||||
describeServer(serverId, WEST_TRANSFER_AUTH)
|
||||
.statusCode(200)
|
||||
.body("Server.LoggingRole", equalTo("west-updated"));
|
||||
describeServer(serverId).statusCode(404);
|
||||
|
||||
cloudFormation(WEST_STACK, "DeleteStack", null, WEST_CFN_AUTH);
|
||||
CfnStackWaits.awaitStackDeleted(WEST_STACK, WEST_CFN_AUTH);
|
||||
describeServer(serverId, WEST_TRANSFER_AUTH).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyServerIdCanUpdateAndDeleteWithArnRef() {
|
||||
cloudFormation(LEGACY_STACK, "CreateStack", TEMPLATE.formatted("\"LoggingRole\":\"legacy-role\""));
|
||||
Map<String, String> created = outputs(LEGACY_STACK, "CREATE_COMPLETE");
|
||||
String serverId = created.get("ServerId");
|
||||
String serverArn = created.get("ServerArn");
|
||||
StackResource legacy = cloudFormationService.describeStackResources(LEGACY_STACK, "us-east-1").stream()
|
||||
.filter(resource -> "Server".equals(resource.getLogicalId()))
|
||||
.findFirst().orElseThrow();
|
||||
legacy.setPhysicalId(serverId);
|
||||
legacy.getAttributes().remove("State");
|
||||
|
||||
cloudFormation(LEGACY_STACK, "UpdateStack", TEMPLATE.formatted("\"LoggingRole\":\"updated-role\""));
|
||||
Map<String, String> updated = outputs(LEGACY_STACK, "UPDATE_COMPLETE");
|
||||
assertEquals(serverId, updated.get("ServerId"));
|
||||
assertEquals(serverArn, updated.get("ServerRef"));
|
||||
assertEquals(serverArn, updated.get("ServerArn"));
|
||||
assertEquals("ONLINE", updated.get("ServerState"));
|
||||
describeServer(serverId).body("Server.LoggingRole", equalTo("updated-role"));
|
||||
|
||||
cloudFormation(LEGACY_STACK, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(LEGACY_STACK);
|
||||
describeServer(serverId).statusCode(404);
|
||||
}
|
||||
|
||||
private static String template(String role, String policy, String stage) {
|
||||
return TEMPLATE.formatted("\"Protocols\": [\"SFTP\"], "
|
||||
+ "\"LoggingRole\": \"" + role + "\", "
|
||||
+ "\"SecurityPolicyName\": \"" + policy + "\", "
|
||||
+ "\"Tags\": [{\"Key\":\"stage\",\"Value\":\"" + stage + "\"}]");
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, String template) {
|
||||
cloudFormation(STACK, action, template);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String stack, String action, String template) {
|
||||
cloudFormation(stack, action, template, CFN_AUTH);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String stack, String action, String template, String authorization) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", authorization)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stack);
|
||||
if (template != null) {
|
||||
request.formParam("TemplateBody", template);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static Map<String, String> outputs(String expectedStatus) {
|
||||
return outputs(STACK, expectedStatus);
|
||||
}
|
||||
|
||||
private static Map<String, String> outputs(String stack, String expectedStatus) {
|
||||
return outputs(stack, expectedStatus, CFN_AUTH);
|
||||
}
|
||||
|
||||
private static Map<String, String> outputs(String stack, String expectedStatus, String authorization) {
|
||||
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, authorization);
|
||||
assertEquals(expectedStatus, state.status(), state.reason());
|
||||
String xml = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", authorization)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue");
|
||||
}
|
||||
|
||||
private static ValidatableResponse describeServer(String serverId) {
|
||||
return describeServer(serverId, TRANSFER_AUTH);
|
||||
}
|
||||
|
||||
private static ValidatableResponse describeServer(String serverId, String authorization) {
|
||||
return given()
|
||||
.header("Authorization", authorization)
|
||||
.header("X-Amz-Target", "TransferService.DescribeServer")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"ServerId\":\"" + serverId + "\"}")
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
private static void tagServer(String arn, String key, String value) {
|
||||
given()
|
||||
.header("Authorization", TRANSFER_AUTH)
|
||||
.header("X-Amz-Target", "TransferService.TagResource")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"Arn\":\"" + arn + "\",\"Tags\":[{\"Key\":\"" + key
|
||||
+ "\",\"Value\":\"" + value + "\"}]}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
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.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.transfer.TransferService;
|
||||
import io.github.hectorvent.floci.services.transfer.model.Server;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
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 TransferCfnProvisionerTest {
|
||||
|
||||
private final TransferService transfer = mock(TransferService.class);
|
||||
private final TransferCfnProvisioner provisioner = new TransferCfnProvisioner(transfer);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void createUsesTransferDefaultsAndRecordsExactAttributes() throws Exception {
|
||||
Server server = server();
|
||||
when(transfer.createServer(eq("us-east-1"), eq("S3"), eq(List.of("SFTP")), eq("PUBLIC"),
|
||||
eq(null), eq("SERVICE_MANAGED"), eq(null), eq(null),
|
||||
eq("TransferSecurityPolicy-2020-06"), eq(Map.of()))).thenReturn(server);
|
||||
StackResource resource = resource();
|
||||
|
||||
provisioner.provision(resource, mapper.readTree("{}"), context(null));
|
||||
|
||||
assertEquals(server.getArn(), resource.getPhysicalId());
|
||||
assertEquals(server.getServerId(), resource.getAttributes().get("ServerId"));
|
||||
assertEquals(server.getArn(), resource.getAttributes().get("Arn"));
|
||||
assertEquals("ONLINE", resource.getAttributes().get("State"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUsesArnAndClearsRemovedOptionalProperties() throws Exception {
|
||||
Server server = server();
|
||||
server.setDomain("S3");
|
||||
server.setIdentityProviderType("SERVICE_MANAGED");
|
||||
when(transfer.getServer(server.getServerId())).thenReturn(server);
|
||||
when(transfer.replaceServerConfiguration(eq(server.getServerId()), eq(List.of("SFTP")),
|
||||
eq("PUBLIC"), eq(null), eq(null), eq(null),
|
||||
eq("TransferSecurityPolicy-2020-06"))).thenReturn(server);
|
||||
when(transfer.listTagsForResource(server.getArn())).thenReturn(Map.of("stale", "value"));
|
||||
StackResource resource = resource();
|
||||
resource.getAttributes().put("__FlociTransferServerTemplateTagKeys", "[\"stale\"]");
|
||||
|
||||
provisioner.provision(resource, mapper.readTree("{}"), context(server.getArn()));
|
||||
|
||||
assertEquals(server.getArn(), resource.getPhysicalId());
|
||||
verify(transfer).untagResource(server.getArn(), List.of("stale"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateLegacyServerIdMigratesRefWithoutCreatingAnotherServer() throws Exception {
|
||||
Server server = server();
|
||||
server.setDomain("S3");
|
||||
server.setIdentityProviderType("SERVICE_MANAGED");
|
||||
server.setState("OFFLINE");
|
||||
when(transfer.getServer(server.getServerId())).thenReturn(server);
|
||||
when(transfer.replaceServerConfiguration(eq(server.getServerId()), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(server);
|
||||
when(transfer.listTagsForResource(server.getArn())).thenReturn(Map.of());
|
||||
StackResource resource = resource();
|
||||
resource.setPhysicalId(server.getServerId());
|
||||
|
||||
provisioner.provision(resource, mapper.readTree("{}"), context(server.getServerId()));
|
||||
|
||||
assertEquals(server.getArn(), resource.getPhysicalId());
|
||||
assertEquals(server.getServerId(), resource.getAttributes().get("ServerId"));
|
||||
assertEquals("OFFLINE", resource.getAttributes().get("State"));
|
||||
verify(transfer, never()).createServer(any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void committedUpdateClearsRollbackSnapshot() {
|
||||
StackResource resource = resource();
|
||||
resource.getAttributes().put("__FlociTransferServerUpdateSnapshot", "previous-state");
|
||||
resource.setStatus("UPDATE_COMPLETE");
|
||||
|
||||
UpdateCleanupResult result = provisioner.completeUpdate(resource);
|
||||
|
||||
assertFalse(result.applicable());
|
||||
assertNull(resource.getAttributes().get("__FlociTransferServerUpdateSnapshot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePreservesTagsAddedOutsideTheTemplate() throws Exception {
|
||||
Server server = server();
|
||||
server.setDomain("S3");
|
||||
server.setIdentityProviderType("SERVICE_MANAGED");
|
||||
when(transfer.getServer(server.getServerId())).thenReturn(server);
|
||||
when(transfer.replaceServerConfiguration(eq(server.getServerId()), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(server);
|
||||
when(transfer.listTagsForResource(server.getArn()))
|
||||
.thenReturn(Map.of("managed", "old", "external", "keep"));
|
||||
StackResource resource = resource();
|
||||
resource.getAttributes().put("__FlociTransferServerTemplateTagKeys", "[\"managed\"]");
|
||||
|
||||
provisioner.provision(resource, mapper.readTree("{}"), context(server.getServerId()));
|
||||
|
||||
verify(transfer).untagResource(server.getArn(), List.of("managed"));
|
||||
verify(transfer, never()).untagResource(server.getArn(), List.of("external"));
|
||||
assertEquals("[]", resource.getAttributes().get("__FlociTransferServerTemplateTagKeys"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void structuredEndpointDetailsRetainBooleanAndListTypes() throws Exception {
|
||||
Server server = server();
|
||||
when(transfer.createServer(eq("us-east-1"), eq("S3"), eq(List.of("SFTP")), eq("VPC"),
|
||||
any(), eq("SERVICE_MANAGED"), eq(null), eq(null),
|
||||
eq("TransferSecurityPolicy-2020-06"), eq(Map.of()))).thenReturn(server);
|
||||
JsonNode props = mapper.readTree("""
|
||||
{"EndpointType":"VPC","EndpointDetails":{"SubnetIds":["subnet-1"],"AddressAllocationIds":[],"DualStack":true}}
|
||||
""");
|
||||
|
||||
provisioner.provision(resource(), props, context(null));
|
||||
|
||||
verify(transfer).createServer(eq("us-east-1"), eq("S3"), eq(List.of("SFTP")), eq("VPC"),
|
||||
eq(Map.of("SubnetIds", List.of("subnet-1"), "AddressAllocationIds", List.of(), "DualStack", true)),
|
||||
eq("SERVICE_MANAGED"), eq(null), eq(null), eq("TransferSecurityPolicy-2020-06"), eq(Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void immutablePropertyChangeFailsBeforeMutation() throws Exception {
|
||||
Server server = server();
|
||||
server.setDomain("S3");
|
||||
server.setIdentityProviderType("SERVICE_MANAGED");
|
||||
when(transfer.getServer(server.getServerId())).thenReturn(server);
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(),
|
||||
mapper.readTree("{\"Domain\":\"EFS\"}"), context(server.getServerId())));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
verify(transfer, never()).replaceServerConfiguration(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void identityProviderTypeChangeIsRejectedAsFlociLimitation() throws Exception {
|
||||
Server server = server();
|
||||
server.setDomain("S3");
|
||||
server.setIdentityProviderType("SERVICE_MANAGED");
|
||||
when(transfer.getServer(server.getServerId())).thenReturn(server);
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(),
|
||||
mapper.readTree("{\"IdentityProviderType\":\"AWS_LAMBDA\"}"), context(server.getArn())));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertEquals("Updating IdentityProviderType is not supported by Floci.", failure.getMessage());
|
||||
verify(transfer, never()).replaceServerConfiguration(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedTagUpdateRestoresPriorServerConfiguration() throws Exception {
|
||||
Server server = server();
|
||||
server.setDomain("S3");
|
||||
server.setIdentityProviderType("SERVICE_MANAGED");
|
||||
server.setProtocols(List.of("SFTP"));
|
||||
server.setEndpointType("PUBLIC");
|
||||
server.setLoggingRole("original-role");
|
||||
server.setSecurityPolicyName("TransferSecurityPolicy-2020-06");
|
||||
when(transfer.getServer(server.getServerId())).thenReturn(server);
|
||||
when(transfer.replaceServerConfiguration(eq(server.getServerId()), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(server);
|
||||
when(transfer.listTagsForResource(server.getArn()))
|
||||
.thenReturn(Map.of("old", "value"), Map.of("new", "value"));
|
||||
doThrow(new AwsException("InvalidRequestException", "tag rejected", 400))
|
||||
.when(transfer).tagResource(server.getArn(), Map.of("new", "value"));
|
||||
StackResource resource = resource();
|
||||
resource.setPhysicalId(server.getArn());
|
||||
JsonNode props = mapper.readTree("""
|
||||
{"LoggingRole":"new-role", "Tags":[{"Key":"new", "Value":"value"}]}
|
||||
""");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource, props, context(server.getArn())));
|
||||
|
||||
assertEquals("InvalidRequestException", failure.getErrorCode());
|
||||
verify(transfer).replaceServerConfiguration(server.getServerId(), List.of("SFTP"), "PUBLIC", null,
|
||||
null, "new-role", "TransferSecurityPolicy-2020-06");
|
||||
verify(transfer).replaceServerConfiguration(server.getServerId(), List.of("SFTP"), "PUBLIC", null,
|
||||
null, "original-role", "TransferSecurityPolicy-2020-06");
|
||||
verify(transfer).tagResource(server.getArn(), Map.of("old", "value"));
|
||||
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
|
||||
assertEquals(server.getArn(), resource.getPhysicalId());
|
||||
assertEquals("ONLINE", resource.getAttributes().get("State"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackHookRestoresPriorConfigurationAfterLaterResourceFails() throws Exception {
|
||||
Server server = server();
|
||||
server.setDomain("S3");
|
||||
server.setIdentityProviderType("SERVICE_MANAGED");
|
||||
server.setProtocols(List.of("SFTP"));
|
||||
server.setEndpointType("PUBLIC");
|
||||
server.setLoggingRole("original-role");
|
||||
server.setSecurityPolicyName("TransferSecurityPolicy-2020-06");
|
||||
when(transfer.getServer(server.getServerId())).thenReturn(server);
|
||||
when(transfer.replaceServerConfiguration(eq(server.getServerId()), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(server);
|
||||
when(transfer.listTagsForResource(server.getArn())).thenReturn(Map.of());
|
||||
StackResource resource = resource();
|
||||
|
||||
provisioner.provision(resource, mapper.readTree("{\"LoggingRole\":\"new-role\"}"),
|
||||
context(server.getArn()));
|
||||
provisioner.rollbackUpdate(resource);
|
||||
|
||||
verify(transfer).replaceServerConfiguration(server.getServerId(), List.of("SFTP"), "PUBLIC", null,
|
||||
null, "original-role", "TransferSecurityPolicy-2020-06");
|
||||
assertNull(resource.getAttributes().get("__FlociTransferServerUpdateSnapshot"));
|
||||
assertEquals(server.getArn(), resource.getPhysicalId());
|
||||
assertEquals(server.getServerId(), resource.getAttributes().get("ServerId"));
|
||||
assertEquals("ONLINE", resource.getAttributes().get("State"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedPropertyAndEmptyProtocolsFailExplicitly() throws Exception {
|
||||
AwsException unsupported = assertThrows(AwsException.class, () -> provisioner.provision(resource(),
|
||||
mapper.readTree("{\"WorkflowDetails\":{}}"), context(null)));
|
||||
assertEquals("ValidationError", unsupported.getErrorCode());
|
||||
|
||||
AwsException empty = assertThrows(AwsException.class, () -> provisioner.provision(resource(),
|
||||
mapper.readTree("{\"Protocols\":[]}"), context(null)));
|
||||
assertEquals("ValidationError", empty.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullProtocolPropertyUsesDefault() throws Exception {
|
||||
Server server = server();
|
||||
when(transfer.createServer(eq("us-east-1"), eq("S3"), eq(List.of("SFTP")), eq("PUBLIC"),
|
||||
eq(null), eq("SERVICE_MANAGED"), eq(null), eq(null),
|
||||
eq("TransferSecurityPolicy-2020-06"), eq(Map.of()))).thenReturn(server);
|
||||
|
||||
provisioner.provision(resource(), mapper.readTree("{\"Protocols\":null}"), context(null));
|
||||
|
||||
verify(transfer).createServer(eq("us-east-1"), eq("S3"), eq(List.of("SFTP")), eq("PUBLIC"),
|
||||
eq(null), eq("SERVICE_MANAGED"), eq(null), eq(null),
|
||||
eq("TransferSecurityPolicy-2020-06"), eq(Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesOnlyMissingServer() {
|
||||
doThrow(new AwsException("ResourceNotFoundException", "gone", 404))
|
||||
.when(transfer).deleteServer("s-123");
|
||||
doThrow(new AwsException("ConflictException", "busy", 409))
|
||||
.when(transfer).deleteServer("s-456");
|
||||
|
||||
provisioner.delete("AWS::Transfer::Server", "s-123", "us-east-1");
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.delete("AWS::Transfer::Server", "s-456", "us-east-1"));
|
||||
assertEquals("ConflictException", failure.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteArnResolvesServerIdAcrossPartitions() {
|
||||
provisioner.delete("AWS::Transfer::Server",
|
||||
"arn:aws-cn:transfer:cn-north-1:000000000000:server/s-123", "cn-north-1");
|
||||
|
||||
verify(transfer).deleteServer("s-123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRejectsArnForAnotherResourceType() {
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.delete("AWS::Transfer::Server",
|
||||
"arn:aws:transfer:us-east-1:000000000000:user/s-123/user", "us-east-1"));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
verify(transfer, never()).deleteServer(any());
|
||||
}
|
||||
|
||||
private ProvisionContext context(String priorId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(invocation -> ((JsonNode) invocation.getArgument(0)).asText());
|
||||
when(engine.resolveNode(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(engine.resolveStringList(any())).thenAnswer(invocation -> {
|
||||
JsonNode node = invocation.getArgument(0);
|
||||
List<String> values = new ArrayList<>();
|
||||
for (JsonNode item : node) {
|
||||
values.add(item.asText());
|
||||
}
|
||||
return values;
|
||||
});
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "stack", priorId);
|
||||
}
|
||||
|
||||
private StackResource resource() {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("Server");
|
||||
resource.setResourceType("AWS::Transfer::Server");
|
||||
return resource;
|
||||
}
|
||||
|
||||
private Server server() {
|
||||
Server server = new Server();
|
||||
server.setServerId("s-12345678901234567");
|
||||
server.setArn("arn:aws:transfer:us-east-1:000000000000:server/s-12345678901234567");
|
||||
server.setState("ONLINE");
|
||||
return server;
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
|
||||
class TransferServiceTest {
|
||||
|
||||
@@ -54,6 +56,7 @@ class TransferServiceTest {
|
||||
tagDelegate = new InMemoryStorage<>();
|
||||
tagStore = new AccountAwareStorageBackend<>(
|
||||
tagDelegate, requestContextInstance, "111111111111");
|
||||
tagStore = Mockito.spy(tagStore);
|
||||
StorageFactory factory = new StorageFactory(null, null) {
|
||||
@Override
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
@@ -78,6 +81,18 @@ class TransferServiceTest {
|
||||
service = new TransferService(factory, null, regionResolver);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedTagWriteDoesNotLeaveCreatedServerBehind() {
|
||||
doThrow(new IllegalStateException("tag write failed"))
|
||||
.when(tagStore).putForAccount(anyString(), anyString(), any());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> service.createServer("us-east-1", null, null,
|
||||
null, null, null, null, null, null, Map.of("stage", "test")));
|
||||
|
||||
assertTrue(serverDelegate.keys().isEmpty());
|
||||
assertTrue(tagDelegate.keys().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serversAndUsersAreIsolatedByAccountAndRegion() {
|
||||
Server first = service.createServer("us-east-1", null, null, null, null,
|
||||
|
||||
Reference in new issue
Block a user