diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 6f6097b984..8ba4b205ce 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -155,6 +155,7 @@ cross-resource references. | ACM | `Certificate` | | EventBridge | `Rule`, `EventBus`, `EventBusPolicy` | | EventBridge Scheduler | `ScheduleGroup` | +| Transfer Family | `Server` (management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported) | | Backup | `BackupVault` | | Pipes | `Pipe` | | Kinesis | `Stream` | diff --git a/docs/services/transfer.md b/docs/services/transfer.md index 70144d5d4e..0b66a50159 100644 --- a/docs/services/transfer.md +++ b/docs/services/transfer.md @@ -111,5 +111,6 @@ aws transfer delete-server --server-id s-01234567890abcdef ## Notes - **Phase 1** covers the management-plane API only. Data-plane SFTP connectivity (actual file transfer) is not emulated. +- CloudFormation provisions `AWS::Transfer::Server` through the management-plane service. `Ref` returns the server ARN; `Fn::GetAtt` exposes `Arn`, `ServerId`, and `State`. AS2 managed egress IP allocation is not modeled, so `As2ServiceManagedEgressIpAddresses` is not exposed. `AWS::Transfer::User` is not yet provisioned. Server properties not supported by the management-plane implementation fail explicitly. Changing `Domain` requires replacement, which is not yet supported. `IdentityProviderType` changes are also not supported by Floci, although AWS supports updating that property without replacement. - Server `EndpointType` defaults to `PUBLIC`. The `State` field transitions between `ONLINE` and `OFFLINE` via `StartServer` / `StopServer`. - SSH key bodies are stored and returned as-is; no cryptographic validation is performed. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index f1bc0de1c4..ae2aa3102d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -738,7 +738,7 @@ public class CloudFormationService implements ResourceProvider { String templateBody = cs.getTemplateBody(); Map params = cs.getParameters() != null ? cs.getParameters() : Map.of(); - return submitOperation(() -> runUnderAccount(accountId, () -> { + return submitOperation(() -> runUnderScope(accountId, region, () -> { executeTemplate(stack, templateBody, params, isCreate, region, accountId); String status = stack.getStatus(); cs.setExecutionStatus(status != null && (status.contains("ROLLBACK") || status.endsWith("_FAILED")) @@ -748,11 +748,10 @@ public class CloudFormationService implements ResourceProvider { } /** - * Runs {@code body} under a synthetic CDI request scope whose account is {@code accountId}, so - * that account-aware storage in the downstream services namespaces provisioned resources under - * the intended account. Mirrors the pattern used by other background workers. + * Runs {@code body} under the stack's account and region, so downstream services resolve the + * same scope as the CloudFormation request that submitted this background operation. */ - private void runUnderAccount(String accountId, Runnable body) { + private void runUnderScope(String accountId, String region, Runnable body) { ManagedContext requestContext = Arc.container().requestContext(); boolean alreadyActive = requestContext.isActive(); if (!alreadyActive) { @@ -760,19 +759,27 @@ public class CloudFormationService implements ResourceProvider { } // Background workers normally have no active scope, so a fresh one is activated and // terminated below. But if we ran inside an already-active scope, restore its previous - // account afterwards so we never leave the overridden account ID behind on a reused thread. + // scope afterwards so we never leave the overridden values behind on a reused thread. RequestContext ctx = Arc.container().instance(RequestContext.class).get(); String previousAccountId = alreadyActive ? ctx.getAccountId() : null; + String previousRegion = alreadyActive ? ctx.getRegion() : null; + String previousPartition = alreadyActive ? ctx.getPartition() : null; try { if (accountId != null) { ctx.setAccountId(accountId); } + if (region != null) { + ctx.setRegion(region); + ctx.setPartition(regionResolver.partitionForRegion(region)); + } body.run(); } finally { if (!alreadyActive) { requestContext.terminate(); } else { ctx.setAccountId(previousAccountId); + ctx.setRegion(previousRegion); + ctx.setPartition(previousPartition); } } } @@ -836,7 +843,7 @@ public class CloudFormationService implements ResourceProvider { "AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null); try { - return submitOperation(() -> runUnderAccount(accountId, + return submitOperation(() -> runUnderScope(accountId, region, () -> deleteStackResources(stack, region, accountId))); } catch (AwsException e) { if ("LimitExceededException".equals(e.getErrorCode())) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/TransferCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/TransferCfnProvisioner.java new file mode 100644 index 0000000000..de908463c1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/TransferCfnProvisioner.java @@ -0,0 +1,231 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +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 jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** CloudFormation lifecycle for a Transfer Family server. */ +@ApplicationScoped +public class TransferCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::Transfer::Server"; + private static final String SECURITY_POLICY_DEFAULT = "TransferSecurityPolicy-2020-06"; + private static final Set SUPPORTED_PROPERTIES = Set.of("Domain", "Protocols", "EndpointType", + "EndpointDetails", "IdentityProviderType", "IdentityProviderDetails", "LoggingRole", + "SecurityPolicyName", "Tags"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String UPDATE_SNAPSHOT = "__FlociTransferServerUpdateSnapshot"; + private static final String TEMPLATE_TAG_KEYS = "__FlociTransferServerTemplateTagKeys"; + + private final TransferService transferService; + + @Inject + public TransferCfnProvisioner(TransferService transferService) { + this.transferService = transferService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) { + resource.getAttributes().remove(UPDATE_SNAPSHOT); + validateProperties(props); + String domain = ctx.resolveOrDefault(props, "Domain", "S3"); + JsonNode protocolNode = props != null ? props.get("Protocols") : null; + JsonNode resolvedProtocols = protocolNode != null ? ctx.engine().resolveNode(protocolNode) : null; + boolean protocolsOmitted = resolvedProtocols == null || resolvedProtocols.isNull() + || (resolvedProtocols.isTextual() && resolvedProtocols.asText().isBlank()); + List protocols = protocolsOmitted ? List.of("SFTP") : ctx.resolveStringList(props, "Protocols"); + if (protocols.isEmpty()) { + throw new AwsException("ValidationError", "AWS::Transfer::Server Protocols must not be empty", 400); + } + String endpointType = ctx.resolveOrDefault(props, "EndpointType", "PUBLIC"); + Map endpointDetails = resolvedMap(props, "EndpointDetails", ctx, + new TypeReference>() {}); + String identityProviderType = ctx.resolveOrDefault(props, "IdentityProviderType", "SERVICE_MANAGED"); + Map identityProviderDetails = resolvedMap(props, "IdentityProviderDetails", ctx, + new TypeReference>() {}); + String loggingRole = ctx.resolveOptional(props, "LoggingRole"); + if (loggingRole != null && loggingRole.isBlank()) { + loggingRole = null; + } + String securityPolicyName = ctx.resolveOrDefault(props, "SecurityPolicyName", SECURITY_POLICY_DEFAULT); + Map tags = ctx.resolveTags(props, "Tags"); + + Server server; + if (ctx.isUpdate()) { + Server existing = transferService.getServer(serverId(ctx.priorPhysicalId())); + rejectUnsupportedChange("Domain", existing.getDomain(), domain); + rejectUnsupportedChange("IdentityProviderType", existing.getIdentityProviderType(), identityProviderType); + Map previousTags = transferService.listTagsForResource(existing.getArn()); + String previousTemplateTagKeys = resource.getAttributes().get(TEMPLATE_TAG_KEYS); + ConfigurationSnapshot previous = new ConfigurationSnapshot(existing.getServerId(), + existing.getProtocols(), existing.getEndpointType(), existing.getEndpointDetails(), + existing.getIdentityProviderDetails(), existing.getLoggingRole(), + existing.getSecurityPolicyName(), previousTags, new ArrayList<>(tags.keySet()), + previousTemplateTagKeys); + resource.getAttributes().put(UPDATE_SNAPSHOT, MAPPER.valueToTree(previous).toString()); + try { + server = transferService.replaceServerConfiguration(existing.getServerId(), protocols, endpointType, + endpointDetails, identityProviderDetails, loggingRole, securityPolicyName); + reconcileTags(server.getArn(), managedTagKeys(previousTemplateTagKeys), tags); + } catch (RuntimeException failure) { + try { + rollbackUpdate(resource); + resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true"); + } catch (RuntimeException restoreFailure) { + resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, + "Could not restore Transfer server " + existing.getServerId() + ": " + + restoreFailure.getMessage()); + failure.addSuppressed(restoreFailure); + } + throw failure; + } + } else { + server = transferService.createServer(ctx.region(), domain, protocols, endpointType, endpointDetails, + identityProviderType, identityProviderDetails, loggingRole, securityPolicyName, tags); + } + recordServer(resource, server); + resource.getAttributes().put(TEMPLATE_TAG_KEYS, MAPPER.valueToTree(tags.keySet()).toString()); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + CfnDeletes.safeDelete("Transfer server", physicalId, + () -> transferService.deleteServer(serverId(physicalId)), "ResourceNotFoundException"); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + if ("UPDATE_COMPLETE".equals(resource.getStatus())) { + resource.getAttributes().remove(UPDATE_SNAPSHOT); + } + return UpdateCleanupResult.notApplicable(); + } + + @Override + public boolean rollbackUpdate(StackResource resource) { + String saved = resource.getAttributes().get(UPDATE_SNAPSHOT); + if (saved == null) { + return true; + } + ConfigurationSnapshot previous; + try { + previous = MAPPER.readValue(saved, ConfigurationSnapshot.class); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read Transfer server update snapshot", e); + } + Server server = transferService.replaceServerConfiguration(previous.serverId(), previous.protocols(), + previous.endpointType(), previous.endpointDetails(), previous.identityProviderDetails(), + previous.loggingRole(), previous.securityPolicyName()); + reconcileTags(server.getArn(), previous.newTagKeys(), previous.tags()); + recordServer(resource, server); + if (previous.previousTemplateTagKeys() == null) { + resource.getAttributes().remove(TEMPLATE_TAG_KEYS); + } else { + resource.getAttributes().put(TEMPLATE_TAG_KEYS, previous.previousTemplateTagKeys()); + } + resource.getAttributes().remove(UPDATE_SNAPSHOT); + return true; + } + + private static void recordServer(StackResource resource, Server server) { + resource.setPhysicalId(server.getArn()); + resource.getAttributes().put("ServerId", server.getServerId()); + resource.getAttributes().put("Arn", server.getArn()); + resource.getAttributes().put("State", server.getState()); + } + + private static String serverId(String physicalId) { + if (!AwsArnUtils.isArn(physicalId)) { + return physicalId; + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(physicalId); + if (!"transfer".equals(arn.service()) || !arn.resource().startsWith("server/")) { + throw new AwsException("ValidationError", "Invalid Transfer server ARN: " + physicalId, 400); + } + return arn.resource().substring("server/".length()); + } + + private void reconcileTags(String arn, List managedKeys, Map desired) { + List staleTags = managedKeys.stream().filter(key -> !desired.containsKey(key)).toList(); + if (!staleTags.isEmpty()) { + transferService.untagResource(arn, staleTags); + } + if (!desired.isEmpty()) { + transferService.tagResource(arn, desired); + } + } + + private record ConfigurationSnapshot(String serverId, List protocols, String endpointType, + Map endpointDetails, + Map identityProviderDetails, String loggingRole, + String securityPolicyName, Map tags, + List newTagKeys, String previousTemplateTagKeys) { + } + + private static List managedTagKeys(String stored) { + if (stored == null) { + return List.of(); + } + try { + return MAPPER.readValue(stored, new TypeReference>() {}); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read Transfer server template tag keys", e); + } + } + + private static void validateProperties(JsonNode props) { + if (props == null || props.isNull()) { + return; + } + if (!props.isObject()) { + throw new AwsException("ValidationError", "AWS::Transfer::Server Properties must be an object", 400); + } + props.fieldNames().forEachRemaining(name -> { + if (!SUPPORTED_PROPERTIES.contains(name)) { + throw new AwsException("ValidationError", + "AWS::Transfer::Server property " + name + " is not supported by Floci", 400); + } + }); + } + + private static T resolvedMap(JsonNode props, String name, ProvisionContext ctx, TypeReference type) { + if (props == null || !props.has(name) || props.get(name).isNull()) { + return null; + } + JsonNode resolved = ctx.engine().resolveNode(props.get(name)); + if (resolved == null || resolved.isNull() + || (resolved.isTextual() && resolved.asText().isBlank())) { + return null; + } + if (!resolved.isObject()) { + throw new AwsException("ValidationError", "AWS::Transfer::Server " + name + " must be an object", 400); + } + return MAPPER.convertValue(resolved, type); + } + + private static void rejectUnsupportedChange(String name, String current, String requested) { + if (!Objects.equals(current, requested)) { + throw new AwsException("ValidationError", + "Updating " + name + " is not supported by Floci.", 400); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java b/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java index 5f1cd8dea1..cf81b28f39 100644 --- a/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java +++ b/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java @@ -75,10 +75,18 @@ public class TransferService { server.setTags(tags != null ? tags : new HashMap<>()); server.setCreationTime(Instant.now()); - putServer(server); - - if (tags != null && !tags.isEmpty()) { - putTags("server/" + serverId, tags); + try { + putServer(server); + if (tags != null && !tags.isEmpty()) { + putTags("server/" + serverId, tags); + } + } catch (RuntimeException failure) { + try { + deleteServerRecord(server); + } catch (RuntimeException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; } return server; @@ -175,6 +183,25 @@ public class TransferService { return server; } + /** Reconciles mutable server properties, including ones removed from a CloudFormation template. */ + public Server replaceServerConfiguration(String serverId, + List protocols, + String endpointType, + Map endpointDetails, + Map identityProviderDetails, + String loggingRole, + String securityPolicyName) { + Server server = getServer(serverId); + server.setProtocols(protocols); + server.setEndpointType(endpointType); + server.setEndpointDetails(endpointDetails); + server.setIdentityProviderDetails(identityProviderDetails); + server.setLoggingRole(loggingRole); + server.setSecurityPolicyName(securityPolicyName); + putServer(server); + return server; + } + // ── Users ───────────────────────────────────────────────────────────────── public User createUser(String serverId, String region, String userName, String role, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 2b85ac196b..564de84116 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -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; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnStackWaits.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnStackWaits.java index dd41888548..d248cb48e2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnStackWaits.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnStackWaits.java @@ -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("DELETE_FAILED"))); if (response.statusCode() == 400) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTransferServerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTransferServerIntegrationTest.java new file mode 100644 index 0000000000..0ce7622841 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTransferServerIntegrationTest.java @@ -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 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 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 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 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 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 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 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 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 outputs(String expectedStatus) { + return outputs(STACK, expectedStatus); + } + + private static Map outputs(String stack, String expectedStatus) { + return outputs(stack, expectedStatus, CFN_AUTH); + } + + private static Map 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); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/TransferCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/TransferCfnProvisionerTest.java new file mode 100644 index 0000000000..95f8b6f7bb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/TransferCfnProvisionerTest.java @@ -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 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; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/transfer/TransferServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/transfer/TransferServiceTest.java index 210980326b..fdb3bacaf6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/transfer/TransferServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/transfer/TransferServiceTest.java @@ -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 AccountAwareStorageBackend 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, diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 3f8aa72dc3..366b4bda66 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -47,6 +47,7 @@ AWS::RDS::DBInstance StorageOperationPercentProgress storage operations (scaling AWS::RDS::DBInstance StorageOperationStatus storage operations (scaling, type changes) are not emulated; storage changes apply synchronously AWS::Redshift::Cluster DeferMaintenanceIdentifier Floci does not emulate deferred maintenance windows AWS::SQS::QueuePolicy Id schema gives no description; the policy has no backing entity to take an id from +AWS::Transfer::Server As2ServiceManagedEgressIpAddresses AS2 managed egress IP allocation is not emulated by the Transfer management-plane service AWS::SecretsManager::Secret Id Fn::GetAtt Id on a secret is its ARN, which the provisioner already sets as the physical id and as Arn; closable, deferred to a follow-up PR to keep this one a pure move AWS::EKS::Cluster ClusterSecurityGroupId not modeled: Floci does not create a cluster security group, so there is no id to publish AWS::EKS::Cluster EncryptionConfigKeyArn not modeled: Floci does not apply envelope encryption, so no KMS key arn is resolved diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 6a433973f3..911395e3c9 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -149,5 +149,6 @@ AWS::ServiceDiscovery::PrivateDnsNamespace CloudMapCfnProvisioner AWS::ServiceDiscovery::PublicDnsNamespace CloudMapCfnProvisioner AWS::ServiceDiscovery::Service CloudMapCfnProvisioner AWS::StepFunctions::StateMachine StepFunctionsCfnProvisioner +AWS::Transfer::Server TransferCfnProvisioner AWS::WAFv2::WebACL WafV2CfnProvisioner Custom::DynamoDBReplica DynamoDbCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 361ac3bb6e..d568dda5c5 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -41,6 +41,7 @@ order: - AWS::CertificateManager - AWS::Events - AWS::Scheduler + - AWS::Transfer - AWS::Backup - AWS::Pipes - AWS::Kinesis @@ -146,6 +147,7 @@ service_labels: AWS::SecretsManager: Secrets Manager AWS::ServiceDiscovery: Cloud Map AWS::StepFunctions: Step Functions + AWS::Transfer: Transfer Family AWS::WAFv2: WAFv2 Custom: CloudFormation @@ -162,6 +164,7 @@ notes: AWS::Redshift::ClusterSecurityGroup: accepted; no EC2-Classic security group model AWS::Redshift::Cluster: single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported AWS::CDK::Metadata: accepted; no-op + AWS::Transfer::Server: 'management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported' AWS::IAM::User: 'template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete' AWS::IoT::DomainConfiguration: '`ServerCertificates` resolves to a JSON string' AWS::IoT::Policy: 'deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached'