mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): provision AWS::Transfer::User (#5076)
* feat(cloudformation): provision AWS::Transfer::User Adds the user type to TransferCfnProvisioner with in-place update and replacement. * Fix #4655 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * docs: count the IAM SSH public key operations in the service matrix Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> --------- Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
108f2b54bf
commit
c6304a26c8
12 files changed
+921
-10
No files matched your search
@@ -164,6 +164,10 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>signin</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>transfer</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>kafka</artifactId>
|
||||
|
||||
@@ -46,6 +46,7 @@ import software.amazon.awssdk.services.identitystore.IdentitystoreClient;
|
||||
import software.amazon.awssdk.services.budgets.BudgetsClient;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.BcmPricingCalculatorClient;
|
||||
import software.amazon.awssdk.services.timestreaminfluxdb.TimestreamInfluxDbClient;
|
||||
import software.amazon.awssdk.services.transfer.TransferClient;
|
||||
import software.amazon.awssdk.services.macie2.Macie2Client;
|
||||
import software.amazon.awssdk.services.controlcatalog.ControlCatalogClient;
|
||||
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
|
||||
@@ -735,6 +736,14 @@ public final class TestFixtures {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static TransferClient transferClient() {
|
||||
return TransferClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static StsClient stsClient() {
|
||||
return StsClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Output;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.transfer.TransferClient;
|
||||
import software.amazon.awssdk.services.transfer.model.DescribedUser;
|
||||
import software.amazon.awssdk.services.transfer.model.ResourceNotFoundException;
|
||||
import software.amazon.awssdk.services.transfer.model.SshPublicKey;
|
||||
import software.amazon.awssdk.services.transfer.model.Tag;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.groups.Tuple.tuple;
|
||||
|
||||
@DisplayName("CloudFormation AWS::Transfer::User")
|
||||
class CloudFormationTransferUserTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFormationTransferUserTest.class);
|
||||
|
||||
private static final String INITIAL_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAAinitial";
|
||||
private static final String UPDATED_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAAupdated";
|
||||
|
||||
private static CloudFormationClient cloudFormation;
|
||||
private static TransferClient transfer;
|
||||
private static String stackName;
|
||||
private static String userName;
|
||||
private static String initialRole;
|
||||
private static String updatedRole;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
cloudFormation = TestFixtures.cloudFormationClient();
|
||||
transfer = TestFixtures.transferClient();
|
||||
stackName = TestFixtures.uniqueName("compat-cfn-transfer-user");
|
||||
userName = TestFixtures.uniqueName("compat-sftp-user");
|
||||
initialRole = "arn:" + TestFixtures.partition() + ":iam::000000000000:role/compat-transfer-initial";
|
||||
updatedRole = "arn:" + TestFixtures.partition() + ":iam::000000000000:role/compat-transfer-updated";
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (cloudFormation != null) {
|
||||
try {
|
||||
cloudFormation.deleteStack(
|
||||
DeleteStackRequest.builder().stackName(stackName).build());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Failed to delete CloudFormation Transfer user test stack {0}", stackName);
|
||||
}
|
||||
cloudFormation.close();
|
||||
}
|
||||
if (transfer != null) {
|
||||
transfer.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsValidatesUpdatesAndDeletesTransferUserThroughAwsSdk() throws InterruptedException {
|
||||
cloudFormation.createStack(CreateStackRequest.builder()
|
||||
.stackName(stackName)
|
||||
.templateBody(template(initialRole, INITIAL_KEY))
|
||||
.build());
|
||||
assertThat(waitForTerminal(stackName, 30)).isEqualTo("CREATE_COMPLETE");
|
||||
|
||||
Stack createdStack = cloudFormation.describeStacks(
|
||||
DescribeStacksRequest.builder().stackName(stackName).build())
|
||||
.stacks().get(0);
|
||||
Map<String, String> outputs = createdStack.outputs().stream()
|
||||
.collect(Collectors.toMap(Output::outputKey, Output::outputValue));
|
||||
|
||||
String serverId = outputs.get("ServerId");
|
||||
assertThat(serverId).startsWith("s-");
|
||||
String userArn = outputs.get("UserArn");
|
||||
assertThat(userArn).startsWith("arn:" + TestFixtures.partition() + ":transfer:")
|
||||
.endsWith(":user/" + serverId + "/" + userName);
|
||||
assertThat(outputs).containsEntry("UserRef", userArn);
|
||||
|
||||
DescribedUser user = describeUser(serverId);
|
||||
assertThat(user.userName()).isEqualTo(userName);
|
||||
assertThat(user.arn()).isEqualTo(userArn);
|
||||
assertThat(user.role()).isEqualTo(initialRole);
|
||||
assertThat(user.homeDirectory()).isEqualTo("/compat-bucket/home");
|
||||
assertThat(user.sshPublicKeys()).extracting(SshPublicKey::sshPublicKeyBody)
|
||||
.containsExactly(INITIAL_KEY);
|
||||
assertThat(user.tags()).extracting(Tag::key, Tag::value)
|
||||
.contains(tuple("Env", "compat"));
|
||||
assertThat(transfer.listTagsForResource(r -> r.arn(userArn)).tags())
|
||||
.extracting(Tag::key, Tag::value)
|
||||
.contains(tuple("Env", "compat"));
|
||||
|
||||
cloudFormation.updateStack(r -> r
|
||||
.stackName(stackName)
|
||||
.templateBody(template(updatedRole, UPDATED_KEY)));
|
||||
assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_COMPLETE");
|
||||
|
||||
DescribedUser updatedUser = describeUser(serverId);
|
||||
assertThat(updatedUser.role()).isEqualTo(updatedRole);
|
||||
assertThat(updatedUser.sshPublicKeys()).extracting(SshPublicKey::sshPublicKeyBody)
|
||||
.containsExactly(UPDATED_KEY);
|
||||
|
||||
cloudFormation.deleteStack(DeleteStackRequest.builder().stackName(stackName).build());
|
||||
waitForDeleted(stackName, 30);
|
||||
|
||||
assertThatThrownBy(() -> describeUser(serverId))
|
||||
.isInstanceOf(ResourceNotFoundException.class);
|
||||
}
|
||||
|
||||
private static DescribedUser describeUser(String serverId) {
|
||||
return transfer.describeUser(r -> r.serverId(serverId).userName(userName)).user();
|
||||
}
|
||||
|
||||
private static String template(String roleArn, String sshKey) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"SftpServer": {
|
||||
"Type": "AWS::Transfer::Server",
|
||||
"Properties": {
|
||||
"Protocols": ["SFTP"],
|
||||
"IdentityProviderType": "SERVICE_MANAGED",
|
||||
"EndpointType": "PUBLIC"
|
||||
}
|
||||
},
|
||||
"SftpUser": {
|
||||
"Type": "AWS::Transfer::User",
|
||||
"Properties": {
|
||||
"ServerId": {"Fn::GetAtt": ["SftpServer", "ServerId"]},
|
||||
"UserName": "%s",
|
||||
"Role": "%s",
|
||||
"HomeDirectory": "/compat-bucket/home",
|
||||
"SshPublicKeys": ["%s"],
|
||||
"Tags": [{"Key": "Env", "Value": "compat"}]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"UserRef": {"Value": {"Ref": "SftpUser"}},
|
||||
"UserArn": {"Value": {"Fn::GetAtt": ["SftpUser", "Arn"]}},
|
||||
"ServerId": {"Value": {"Fn::GetAtt": ["SftpServer", "ServerId"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(userName, roleArn, sshKey);
|
||||
}
|
||||
|
||||
private static String waitForTerminal(String name, int maxSeconds) throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
List<Stack> stacks = cloudFormation.describeStacks(
|
||||
DescribeStacksRequest.builder().stackName(name).build()).stacks();
|
||||
if (!stacks.isEmpty()) {
|
||||
String status = stacks.get(0).stackStatusAsString();
|
||||
if (!status.endsWith("_IN_PROGRESS")) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
throw new AssertionError(
|
||||
"Stack " + name + " did not reach a terminal state within " + maxSeconds + "s");
|
||||
}
|
||||
|
||||
private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
try {
|
||||
List<Stack> stacks = cloudFormation.describeStacks(
|
||||
DescribeStacksRequest.builder().stackName(name).build()).stacks();
|
||||
if (stacks.isEmpty()
|
||||
|| "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) {
|
||||
return;
|
||||
}
|
||||
} catch (CloudFormationException e) {
|
||||
if (e.getMessage() != null && e.getMessage().contains("does not exist")) {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
throw new AssertionError(
|
||||
"Stack " + name + " was not deleted within " + maxSeconds + "s");
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,7 @@ cross-resource references.
|
||||
| ACM | `Certificate` |
|
||||
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored) |
|
||||
| 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) |
|
||||
| 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), `User` (management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user) |
|
||||
| Backup | `BackupVault` |
|
||||
| Pipes | `Pipe` |
|
||||
| Kinesis | `Stream` |
|
||||
|
||||
@@ -111,6 +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.
|
||||
- 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. CloudFormation also provisions `AWS::Transfer::User`: `Ref` returns the user ARN, `Fn::GetAtt` exposes `Arn` (the only attribute the registry schema declares), `Policy` and `PosixProfile` fail explicitly, and a `ServerId` or `UserName` change replaces the user. 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.
|
||||
+301
-7
@@ -8,21 +8,33 @@ 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.HomeDirectoryMapping;
|
||||
import io.github.hectorvent.floci.services.transfer.model.Server;
|
||||
import io.github.hectorvent.floci.services.transfer.model.SshPublicKey;
|
||||
import io.github.hectorvent.floci.services.transfer.model.User;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/** CloudFormation lifecycle for a Transfer Family server. */
|
||||
/** CloudFormation lifecycle for Transfer Family servers and users. */
|
||||
@ApplicationScoped
|
||||
public class TransferCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(TransferCfnProvisioner.class);
|
||||
private static final String TYPE = "AWS::Transfer::Server";
|
||||
private static final String USER_TYPE = "AWS::Transfer::User";
|
||||
private static final Set<String> USER_SUPPORTED_PROPERTIES = Set.of("ServerId", "UserName", "Role",
|
||||
"HomeDirectory", "HomeDirectoryType", "HomeDirectoryMappings", "SshPublicKeys", "Tags");
|
||||
private static final String SECURITY_POLICY_DEFAULT = "TransferSecurityPolicy-2020-06";
|
||||
private static final Set<String> SUPPORTED_PROPERTIES = Set.of("Domain", "Protocols", "EndpointType",
|
||||
"EndpointDetails", "IdentityProviderType", "IdentityProviderDetails", "LoggingRole",
|
||||
@@ -30,6 +42,8 @@ public class TransferCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String UPDATE_SNAPSHOT = "__FlociTransferServerUpdateSnapshot";
|
||||
private static final String TEMPLATE_TAG_KEYS = "__FlociTransferServerTemplateTagKeys";
|
||||
private static final String USER_UPDATE_SNAPSHOT = "__FlociTransferUserUpdateSnapshot";
|
||||
private static final String TEMPLATE_SSH_KEYS = "__FlociTransferUserTemplateSshKeys";
|
||||
|
||||
private final TransferService transferService;
|
||||
|
||||
@@ -40,13 +54,17 @@ public class TransferCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TYPE);
|
||||
return Set.of(TYPE, USER_TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {
|
||||
if (USER_TYPE.equals(resource.getResourceType())) {
|
||||
provisionUser(resource, props, ctx);
|
||||
return;
|
||||
}
|
||||
resource.getAttributes().remove(UPDATE_SNAPSHOT);
|
||||
validateProperties(props);
|
||||
validateProperties(TYPE, SUPPORTED_PROPERTIES, 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;
|
||||
@@ -108,12 +126,24 @@ public class TransferCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
if (USER_TYPE.equals(resourceType)) {
|
||||
UserRef ref = parseUserArn(physicalId);
|
||||
CfnDeletes.safeDelete("Transfer user", physicalId,
|
||||
() -> transferService.deleteUser(ref.serverId(), ref.userName()), "ResourceNotFoundException");
|
||||
return;
|
||||
}
|
||||
CfnDeletes.safeDelete("Transfer server", physicalId,
|
||||
() -> transferService.deleteServer(serverId(physicalId)), "ResourceNotFoundException");
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
if (USER_TYPE.equals(resource.getResourceType())) {
|
||||
if ("UPDATE_COMPLETE".equals(resource.getStatus())) {
|
||||
resource.getAttributes().remove(USER_UPDATE_SNAPSHOT);
|
||||
}
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
if ("UPDATE_COMPLETE".equals(resource.getStatus())) {
|
||||
resource.getAttributes().remove(UPDATE_SNAPSHOT);
|
||||
}
|
||||
@@ -122,6 +152,13 @@ public class TransferCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
if (USER_TYPE.equals(resource.getResourceType())) {
|
||||
if (resource.getAttributes().containsKey(USER_UPDATE_SNAPSHOT)) {
|
||||
restoreUser(resource);
|
||||
return true;
|
||||
}
|
||||
return ReplacementCleanup.rollback(resource, this::delete);
|
||||
}
|
||||
String saved = resource.getAttributes().get(UPDATE_SNAPSHOT);
|
||||
if (saved == null) {
|
||||
return true;
|
||||
@@ -174,6 +211,7 @@ public class TransferCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
private record ConfigurationSnapshot(String serverId, List<String> protocols, String endpointType,
|
||||
Map<String, Object> endpointDetails,
|
||||
Map<String, String> identityProviderDetails, String loggingRole,
|
||||
@@ -192,17 +230,273 @@ public class TransferCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateProperties(JsonNode props) {
|
||||
private void provisionUser(StackResource resource, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = new HashMap<>(resource.getAttributes());
|
||||
validateProperties(USER_TYPE, USER_SUPPORTED_PROPERTIES, props);
|
||||
String serverId = requiredUserProperty(props, "ServerId", ctx);
|
||||
String userName = requiredUserProperty(props, "UserName", ctx);
|
||||
String role = requiredUserProperty(props, "Role", ctx);
|
||||
String homeDirectory = ctx.resolveOptional(props, "HomeDirectory");
|
||||
String homeDirectoryType = ctx.resolveOptional(props, "HomeDirectoryType");
|
||||
List<HomeDirectoryMapping> mappings = homeDirectoryMappings(props, ctx);
|
||||
List<String> sshKeys = ctx.resolveStringList(props, "SshPublicKeys");
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
|
||||
UserRef prior = ctx.isUpdate() ? parseUserArn(ctx.priorPhysicalId()) : null;
|
||||
boolean inPlace = prior != null && prior.serverId().equals(serverId) && prior.userName().equals(userName);
|
||||
User user;
|
||||
if (inPlace) {
|
||||
user = updateUserInPlace(resource, serverId, userName, role, homeDirectory, homeDirectoryType, mappings,
|
||||
sshKeys, tags);
|
||||
} else {
|
||||
user = createUserWithKeys(serverId, ctx.region(), userName, role, homeDirectory, homeDirectoryType,
|
||||
mappings, sshKeys, tags);
|
||||
}
|
||||
resource.setPhysicalId(user.getArn());
|
||||
resource.getAttributes().put("Arn", user.getArn());
|
||||
resource.getAttributes().put(TEMPLATE_TAG_KEYS, MAPPER.valueToTree(tags.keySet()).toString());
|
||||
resource.getAttributes().put(TEMPLATE_SSH_KEYS, MAPPER.valueToTree(sshKeys).toString());
|
||||
ReplacementCleanup.record(resource, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
private User createUserWithKeys(String serverId, String region, String userName, String role,
|
||||
String homeDirectory, String homeDirectoryType,
|
||||
List<HomeDirectoryMapping> mappings, List<String> sshKeys,
|
||||
Map<String, String> tags) {
|
||||
User user = transferService.createUser(serverId, region, userName, role,
|
||||
homeDirectory != null && !homeDirectory.isBlank() ? homeDirectory : null,
|
||||
homeDirectoryType != null && !homeDirectoryType.isBlank() ? homeDirectoryType : null,
|
||||
mappings, tags);
|
||||
try {
|
||||
for (String key : sshKeys) {
|
||||
transferService.importSshPublicKey(serverId, userName, key);
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
try {
|
||||
transferService.deleteUser(serverId, userName);
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
LOG.warnv(cleanupFailure, "Could not remove Transfer user {0} on {1} after a failed key import",
|
||||
userName, serverId);
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
private User updateUserInPlace(StackResource resource, String serverId, String userName, String role,
|
||||
String homeDirectory, String homeDirectoryType,
|
||||
List<HomeDirectoryMapping> mappings, List<String> sshKeys,
|
||||
Map<String, String> tags) {
|
||||
User existing = transferService.getUser(serverId, userName);
|
||||
String previousTemplateTagKeys = resource.getAttributes().get(TEMPLATE_TAG_KEYS);
|
||||
String previousTemplateSshKeys = resource.getAttributes().get(TEMPLATE_SSH_KEYS);
|
||||
UserSnapshot previous = snapshotUser(serverId, existing,
|
||||
transferService.listTagsForResource(existing.getArn()), new ArrayList<>(tags.keySet()),
|
||||
sshKeys, previousTemplateTagKeys, previousTemplateSshKeys);
|
||||
resource.getAttributes().put(USER_UPDATE_SNAPSHOT, MAPPER.valueToTree(previous).toString());
|
||||
try {
|
||||
User user = transferService.updateUser(serverId, userName, role,
|
||||
homeDirectory != null && !homeDirectory.isBlank() ? homeDirectory : "/",
|
||||
homeDirectoryType != null && !homeDirectoryType.isBlank() ? homeDirectoryType : "PATH",
|
||||
mappings);
|
||||
reconcileSshKeys(user, sshKeys, managedValues(previousTemplateSshKeys));
|
||||
reconcileUserTags(user.getArn(), tags, previousTemplateTagKeys);
|
||||
return user;
|
||||
} catch (RuntimeException failure) {
|
||||
try {
|
||||
restoreUser(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 user " + userName + ": " + restoreFailure.getMessage());
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private static UserSnapshot snapshotUser(String serverId, User user, Map<String, String> tags,
|
||||
List<String> newTagKeys, List<String> updateSshKeys,
|
||||
String previousTemplateTagKeys, String previousTemplateSshKeys) {
|
||||
List<SnapshotMapping> mappings = new ArrayList<>();
|
||||
if (user.getHomeDirectoryMappings() != null) {
|
||||
for (HomeDirectoryMapping mapping : user.getHomeDirectoryMappings()) {
|
||||
mappings.add(new SnapshotMapping(mapping.getEntry(), mapping.getTarget()));
|
||||
}
|
||||
}
|
||||
List<SnapshotKey> keys = new ArrayList<>();
|
||||
if (user.getSshPublicKeys() != null) {
|
||||
for (SshPublicKey key : user.getSshPublicKeys()) {
|
||||
keys.add(new SnapshotKey(key.getSshPublicKeyId(), key.getSshPublicKeyBody(),
|
||||
key.getDateImported() != null ? key.getDateImported().toString() : null));
|
||||
}
|
||||
}
|
||||
return new UserSnapshot(serverId, user.getUserName(), user.getRole(), user.getHomeDirectory(),
|
||||
user.getHomeDirectoryType(), mappings, keys, new HashMap<>(tags), newTagKeys,
|
||||
new ArrayList<>(updateSshKeys), previousTemplateTagKeys, previousTemplateSshKeys);
|
||||
}
|
||||
|
||||
private void restoreUser(StackResource resource) {
|
||||
UserSnapshot previous;
|
||||
try {
|
||||
previous = MAPPER.readValue(resource.getAttributes().get(USER_UPDATE_SNAPSHOT), UserSnapshot.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Could not read Transfer user update snapshot", e);
|
||||
}
|
||||
List<HomeDirectoryMapping> mappings = new ArrayList<>();
|
||||
for (SnapshotMapping mapping : previous.mappings()) {
|
||||
mappings.add(new HomeDirectoryMapping(mapping.entry(), mapping.target()));
|
||||
}
|
||||
User user = transferService.updateUser(previous.serverId(), previous.userName(), previous.role(),
|
||||
previous.homeDirectory(), previous.homeDirectoryType(), mappings);
|
||||
Set<String> previousIds = new HashSet<>();
|
||||
Set<String> presentIds = new HashSet<>();
|
||||
for (SnapshotKey key : previous.sshKeys()) {
|
||||
previousIds.add(key.id());
|
||||
}
|
||||
for (SshPublicKey key : user.getSshPublicKeys() != null ? user.getSshPublicKeys() : List.<SshPublicKey>of()) {
|
||||
if (previousIds.contains(key.getSshPublicKeyId())) {
|
||||
presentIds.add(key.getSshPublicKeyId());
|
||||
} else if (previous.updateSshKeys().contains(key.getSshPublicKeyBody())) {
|
||||
transferService.deleteSshPublicKey(previous.serverId(), previous.userName(), key.getSshPublicKeyId());
|
||||
}
|
||||
}
|
||||
for (SnapshotKey key : previous.sshKeys()) {
|
||||
if (!presentIds.contains(key.id())) {
|
||||
transferService.restoreSshPublicKey(previous.serverId(), previous.userName(),
|
||||
new SshPublicKey(key.id(), key.body(),
|
||||
key.dateImported() != null ? Instant.parse(key.dateImported()) : Instant.now()));
|
||||
}
|
||||
}
|
||||
reconcileTags(user.getArn(), previous.newTagKeys(), previous.tags());
|
||||
restoreAttribute(resource, TEMPLATE_TAG_KEYS, previous.previousTemplateTagKeys());
|
||||
restoreAttribute(resource, TEMPLATE_SSH_KEYS, previous.previousTemplateSshKeys());
|
||||
resource.getAttributes().remove(USER_UPDATE_SNAPSHOT);
|
||||
}
|
||||
|
||||
private static void restoreAttribute(StackResource resource, String name, String value) {
|
||||
if (value == null) {
|
||||
resource.getAttributes().remove(name);
|
||||
} else {
|
||||
resource.getAttributes().put(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
private record SnapshotMapping(String entry, String target) {
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
private record SnapshotKey(String id, String body, String dateImported) {
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
private record UserSnapshot(String serverId, String userName, String role, String homeDirectory,
|
||||
String homeDirectoryType, List<SnapshotMapping> mappings,
|
||||
List<SnapshotKey> sshKeys, Map<String, String> tags, List<String> newTagKeys,
|
||||
List<String> updateSshKeys, String previousTemplateTagKeys,
|
||||
String previousTemplateSshKeys) {
|
||||
}
|
||||
|
||||
private static Set<String> managedValues(String stored) {
|
||||
return new HashSet<>(managedTagKeys(stored));
|
||||
}
|
||||
|
||||
private void reconcileSshKeys(User user, List<String> desired, Set<String> managed) {
|
||||
List<SshPublicKey> current = user.getSshPublicKeys() != null ? user.getSshPublicKeys() : List.of();
|
||||
Set<String> currentBodies = new HashSet<>();
|
||||
for (SshPublicKey key : current) {
|
||||
if (desired.contains(key.getSshPublicKeyBody())) {
|
||||
currentBodies.add(key.getSshPublicKeyBody());
|
||||
} else if (managed.contains(key.getSshPublicKeyBody())) {
|
||||
transferService.deleteSshPublicKey(serverIdOf(user), user.getUserName(), key.getSshPublicKeyId());
|
||||
}
|
||||
}
|
||||
for (String body : desired) {
|
||||
if (currentBodies.add(body)) {
|
||||
transferService.importSshPublicKey(serverIdOf(user), user.getUserName(), body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcileUserTags(String arn, Map<String, String> desired, String previousTemplateTagKeys) {
|
||||
reconcileTags(arn, managedTagKeys(previousTemplateTagKeys), desired);
|
||||
}
|
||||
|
||||
private static String serverIdOf(User user) {
|
||||
return parseUserArn(user.getArn()).serverId();
|
||||
}
|
||||
|
||||
private static String requiredUserProperty(JsonNode props, String name, ProvisionContext ctx) {
|
||||
String value = ctx.resolveOptional(props, name);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("ValidationError", USER_TYPE + " requires property " + name, 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static List<HomeDirectoryMapping> homeDirectoryMappings(JsonNode props, ProvisionContext ctx) {
|
||||
if (props == null || !props.has("HomeDirectoryMappings") || props.get("HomeDirectoryMappings").isNull()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
JsonNode resolved = ctx.engine().resolveNode(props.get("HomeDirectoryMappings"));
|
||||
if (resolved == null || resolved.isNull()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
if (!resolved.isArray()) {
|
||||
throw new AwsException("ValidationError", USER_TYPE + " HomeDirectoryMappings must be a list", 400);
|
||||
}
|
||||
List<HomeDirectoryMapping> mappings = new ArrayList<>();
|
||||
for (JsonNode mapping : resolved) {
|
||||
mappings.add(new HomeDirectoryMapping(mapping.path("Entry").asText(null),
|
||||
mapping.path("Target").asText(null)));
|
||||
}
|
||||
return mappings;
|
||||
}
|
||||
|
||||
private static UserRef parseUserArn(String physicalId) {
|
||||
if (AwsArnUtils.isArn(physicalId)) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(physicalId);
|
||||
if ("transfer".equals(arn.service()) && arn.resource().startsWith("user/")) {
|
||||
String[] parts = arn.resource().substring("user/".length()).split("/", 2);
|
||||
if (parts.length == 2) {
|
||||
return new UserRef(parts[0], parts[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AwsException("ValidationError", "Invalid Transfer user ARN: " + physicalId, 400);
|
||||
}
|
||||
|
||||
private record UserRef(String serverId, String userName) {
|
||||
}
|
||||
|
||||
private static void validateProperties(String type, Set<String> supported, JsonNode props) {
|
||||
if (props == null || props.isNull()) {
|
||||
return;
|
||||
}
|
||||
if (!props.isObject()) {
|
||||
throw new AwsException("ValidationError", "AWS::Transfer::Server Properties must be an object", 400);
|
||||
throw new AwsException("ValidationError", type + " Properties must be an object", 400);
|
||||
}
|
||||
props.fieldNames().forEachRemaining(name -> {
|
||||
if (!SUPPORTED_PROPERTIES.contains(name)) {
|
||||
if (!supported.contains(name)) {
|
||||
throw new AwsException("ValidationError",
|
||||
"AWS::Transfer::Server property " + name + " is not supported by Floci", 400);
|
||||
type + " property " + name + " is not supported by Floci", 400);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ public class TransferHandler {
|
||||
kNode.put("SshPublicKeyId", k.getSshPublicKeyId());
|
||||
kNode.put("SshPublicKeyBody", k.getSshPublicKeyBody());
|
||||
if (k.getDateImported() != null) {
|
||||
kNode.put("DateImported", k.getDateImported().toString());
|
||||
kNode.put("DateImported", k.getDateImported().toEpochMilli() / 1000.0);
|
||||
}
|
||||
keys.add(kNode);
|
||||
}
|
||||
|
||||
@@ -294,6 +294,21 @@ public class TransferService {
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts back a key exactly as it was, keeping its id and import date, so a CloudFormation rollback
|
||||
* does not hand callers a new id for a key they already hold. A key already present is left alone.
|
||||
*/
|
||||
public void restoreSshPublicKey(String serverId, String userName, SshPublicKey key) {
|
||||
User user = getUser(serverId, userName);
|
||||
List<SshPublicKey> keys = new ArrayList<>(user.getSshPublicKeys() != null ? user.getSshPublicKeys() : List.of());
|
||||
if (keys.stream().anyMatch(k -> k.getSshPublicKeyId().equals(key.getSshPublicKeyId()))) {
|
||||
return;
|
||||
}
|
||||
keys.add(key);
|
||||
user.setSshPublicKeys(keys);
|
||||
putUser(user);
|
||||
}
|
||||
|
||||
public void deleteSshPublicKey(String serverId, String userName, String sshPublicKeyId) {
|
||||
User user = getUser(serverId, userName);
|
||||
List<SshPublicKey> keys = new ArrayList<>(user.getSshPublicKeys() != null ? user.getSshPublicKeys() : List.of());
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
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.instanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationTransferUserIntegrationTest {
|
||||
|
||||
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 STACK = "cfn-transfer-user-integration";
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Resources": {
|
||||
"Bucket": {"Type": "AWS::S3::Bucket"},
|
||||
"Role": {
|
||||
"Type": "AWS::IAM::Role",
|
||||
"Properties": {
|
||||
"AssumeRolePolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{"Effect": "Allow",
|
||||
"Principal": {"Service": "transfer.amazonaws.com"}, "Action": "sts:AssumeRole"}]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Server": {
|
||||
"Type": "AWS::Transfer::Server",
|
||||
"Properties": {"Protocols": ["SFTP"], "IdentityProviderType": "SERVICE_MANAGED",
|
||||
"EndpointType": "PUBLIC"}
|
||||
},
|
||||
"User": {
|
||||
"Type": "AWS::Transfer::User",
|
||||
"Properties": {
|
||||
"ServerId": {"Fn::GetAtt": ["Server", "ServerId"]},
|
||||
"UserName": "%s",
|
||||
"Role": {"Fn::GetAtt": ["Role", "Arn"]},
|
||||
"HomeDirectory": {"Fn::Sub": "/${Bucket}/%s"},
|
||||
"SshPublicKeys": ["%s"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"UserRef": {"Value": {"Ref": "User"}},
|
||||
"UserArn": {"Value": {"Fn::GetAtt": ["User", "Arn"]}},
|
||||
"ServerId": {"Value": {"Fn::GetAtt": ["Server", "ServerId"]}},
|
||||
"RoleArn": {"Value": {"Fn::GetAtt": ["Role", "Arn"]}},
|
||||
"BucketName": {"Value": {"Ref": "Bucket"}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUpdateReplaceAndDeleteUser() {
|
||||
cloudFormation("CreateStack", TEMPLATE.formatted("example-user", "home", "ssh-rsa AAAAfirst"));
|
||||
Map<String, String> outputs = outputs("CREATE_COMPLETE");
|
||||
String serverId = outputs.get("ServerId");
|
||||
String arn = outputs.get("UserArn");
|
||||
assertEquals(arn, outputs.get("UserRef"));
|
||||
assertEquals("arn:aws:transfer:us-east-1:000000000000:user/" + serverId + "/example-user", arn);
|
||||
describeUser(serverId, "example-user")
|
||||
.statusCode(200)
|
||||
.body("User.Arn", equalTo(arn))
|
||||
.body("User.Role", equalTo(outputs.get("RoleArn")))
|
||||
.body("User.HomeDirectory", equalTo("/" + outputs.get("BucketName") + "/home"))
|
||||
.body("User.SshPublicKeys.SshPublicKeyBody", hasItem("ssh-rsa AAAAfirst"))
|
||||
.body("User.SshPublicKeys[0].DateImported", instanceOf(Number.class));
|
||||
|
||||
cloudFormation("UpdateStack", TEMPLATE.formatted("example-user", "updated", "ssh-rsa AAAAsecond"));
|
||||
Map<String, String> updated = outputs("UPDATE_COMPLETE");
|
||||
assertEquals(arn, updated.get("UserRef"));
|
||||
describeUser(serverId, "example-user")
|
||||
.statusCode(200)
|
||||
.body("User.HomeDirectory", equalTo("/" + outputs.get("BucketName") + "/updated"))
|
||||
.body("User.SshPublicKeys.SshPublicKeyBody", hasItem("ssh-rsa AAAAsecond"))
|
||||
.body("User.SshPublicKeys.size()", equalTo(1));
|
||||
|
||||
cloudFormation("UpdateStack", TEMPLATE.formatted("renamed-user", "updated", "ssh-rsa AAAAsecond"));
|
||||
Map<String, String> replaced = outputs("UPDATE_COMPLETE");
|
||||
assertNotEquals(arn, replaced.get("UserRef"));
|
||||
assertTrue(replaced.get("UserArn").endsWith("/" + serverId + "/renamed-user"));
|
||||
describeUser(serverId, "renamed-user").statusCode(200);
|
||||
describeUser(serverId, "example-user").statusCode(404);
|
||||
|
||||
cloudFormation("DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(STACK);
|
||||
describeUser(serverId, "renamed-user").statusCode(404);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, String template) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.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) {
|
||||
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(STACK, CFN_AUTH);
|
||||
assertEquals(expectedStatus, state.status(), state.reason());
|
||||
String xml = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue");
|
||||
}
|
||||
|
||||
private static ValidatableResponse describeUser(String serverId, String userName) {
|
||||
return given()
|
||||
.header("Authorization", TRANSFER_AUTH)
|
||||
.header("X-Amz-Target", "TransferService.DescribeUser")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"ServerId\":\"" + serverId + "\",\"UserName\":\"" + userName + "\"}")
|
||||
.when().post("/").then();
|
||||
}
|
||||
}
|
||||
+247
@@ -6,9 +6,14 @@ 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.HomeDirectoryMapping;
|
||||
import io.github.hectorvent.floci.services.transfer.model.Server;
|
||||
import io.github.hectorvent.floci.services.transfer.model.SshPublicKey;
|
||||
import io.github.hectorvent.floci.services.transfer.model.User;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -16,9 +21,12 @@ 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.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -27,6 +35,8 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class TransferCfnProvisionerTest {
|
||||
|
||||
private static final String SERVER_ID = "s-12345678901234567";
|
||||
|
||||
private final TransferService transfer = mock(TransferService.class);
|
||||
private final TransferCfnProvisioner provisioner = new TransferCfnProvisioner(transfer);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
@@ -283,6 +293,243 @@ class TransferCfnProvisionerTest {
|
||||
verify(transfer, never()).deleteServer(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userCreateRecordsArnRefAndExactAttributes() throws Exception {
|
||||
User user = user("alice");
|
||||
when(transfer.createUser("s-12345678901234567", "us-east-1", "alice", "role-arn", "/b/home", null,
|
||||
List.of(), Map.of())).thenReturn(user);
|
||||
StackResource resource = userResource();
|
||||
|
||||
provisioner.provision(resource, mapper.readTree("""
|
||||
{"ServerId":"s-12345678901234567","UserName":"alice","Role":"role-arn","HomeDirectory":"/b/home",
|
||||
"SshPublicKeys":["ssh-rsa AAAA"]}"""), context(null));
|
||||
|
||||
assertEquals(user.getArn(), resource.getPhysicalId());
|
||||
assertEquals(Map.of("Arn", user.getArn(),
|
||||
"__FlociTransferServerTemplateTagKeys", "[]",
|
||||
"__FlociTransferUserTemplateSshKeys", "[\"ssh-rsa AAAA\"]"), resource.getAttributes());
|
||||
verify(transfer).importSshPublicKey("s-12345678901234567", "alice", "ssh-rsa AAAA");
|
||||
}
|
||||
|
||||
@Test
|
||||
void userUpdateWithSameKeyUpdatesInPlace() throws Exception {
|
||||
User user = user("alice");
|
||||
when(transfer.getUser(SERVER_ID, "alice")).thenReturn(user);
|
||||
when(transfer.listTagsForResource(user.getArn())).thenReturn(Map.of());
|
||||
when(transfer.updateUser(eq(SERVER_ID), eq("alice"), eq("role-2"), eq("/"), eq("PATH"), any()))
|
||||
.thenReturn(user);
|
||||
StackResource resource = userResource();
|
||||
|
||||
provisioner.provision(resource, mapper.readTree(
|
||||
"{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"alice\",\"Role\":\"role-2\"}"),
|
||||
context(user.getArn()));
|
||||
|
||||
assertEquals(user.getArn(), resource.getPhysicalId());
|
||||
verify(transfer, never()).createUser(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userUpdateClearsHomeDirectoryMappingsRemovedFromTemplate() throws Exception {
|
||||
User user = user("alice");
|
||||
user.setHomeDirectoryType("LOGICAL");
|
||||
user.setHomeDirectoryMappings(List.of(new HomeDirectoryMapping("/a", "/b/a")));
|
||||
when(transfer.getUser(SERVER_ID, "alice")).thenReturn(user);
|
||||
when(transfer.listTagsForResource(user.getArn())).thenReturn(Map.of());
|
||||
when(transfer.updateUser(any(), any(), any(), any(), any(), any())).thenReturn(user);
|
||||
|
||||
provisioner.provision(userResource(), mapper.readTree(
|
||||
"{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"alice\",\"Role\":\"role-2\"}"),
|
||||
context(user.getArn()));
|
||||
|
||||
verify(transfer).updateUser(SERVER_ID, "alice", "role-2", "/", "PATH", List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userUpdateKeepsSshKeysAddedOutsideTheStack() throws Exception {
|
||||
User user = user("alice");
|
||||
user.setSshPublicKeys(List.of(new SshPublicKey("key-managed", "ssh-rsa OLD", null),
|
||||
new SshPublicKey("key-manual", "ssh-rsa MANUAL", null)));
|
||||
when(transfer.getUser(SERVER_ID, "alice")).thenReturn(user);
|
||||
when(transfer.listTagsForResource(user.getArn())).thenReturn(Map.of());
|
||||
when(transfer.updateUser(any(), any(), any(), any(), any(), any())).thenReturn(user);
|
||||
StackResource resource = userResource();
|
||||
resource.getAttributes().put("__FlociTransferUserTemplateSshKeys", "[\"ssh-rsa OLD\"]");
|
||||
|
||||
provisioner.provision(resource, mapper.readTree(
|
||||
"{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"alice\",\"Role\":\"r\","
|
||||
+ "\"SshPublicKeys\":[\"ssh-rsa NEW\"]}"), context(user.getArn()));
|
||||
|
||||
verify(transfer).deleteSshPublicKey(SERVER_ID, "alice", "key-managed");
|
||||
verify(transfer, never()).deleteSshPublicKey(SERVER_ID, "alice", "key-manual");
|
||||
verify(transfer).importSshPublicKey(SERVER_ID, "alice", "ssh-rsa NEW");
|
||||
assertEquals("[\"ssh-rsa NEW\"]", resource.getAttributes().get("__FlociTransferUserTemplateSshKeys"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void userUpdateWithoutPriorKeyRecordDeletesNoKeys() throws Exception {
|
||||
User user = user("alice");
|
||||
user.setSshPublicKeys(List.of(new SshPublicKey("key-1", "ssh-rsa ANY", null)));
|
||||
when(transfer.getUser(SERVER_ID, "alice")).thenReturn(user);
|
||||
when(transfer.listTagsForResource(user.getArn())).thenReturn(Map.of());
|
||||
when(transfer.updateUser(any(), any(), any(), any(), any(), any())).thenReturn(user);
|
||||
|
||||
provisioner.provision(userResource(), mapper.readTree(
|
||||
"{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"alice\",\"Role\":\"r\"}"),
|
||||
context(user.getArn()));
|
||||
|
||||
verify(transfer, never()).deleteSshPublicKey(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userCreateRemovesUserWhenKeyImportFails() throws Exception {
|
||||
User user = user("alice");
|
||||
when(transfer.createUser(eq(SERVER_ID), eq("us-east-1"), eq("alice"), eq("r"), any(), any(), any(),
|
||||
any())).thenReturn(user);
|
||||
AwsException importFailure = new AwsException("InvalidRequestException", "bad key", 400);
|
||||
when(transfer.importSshPublicKey(SERVER_ID, "alice", "ssh-rsa BAD")).thenThrow(importFailure);
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(userResource(),
|
||||
mapper.readTree("{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"alice\","
|
||||
+ "\"Role\":\"r\",\"SshPublicKeys\":[\"ssh-rsa BAD\"]}"), context(null)));
|
||||
|
||||
assertSame(importFailure, failure);
|
||||
verify(transfer).deleteUser(SERVER_ID, "alice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void userCreateKeepsOriginalErrorWhenCleanupFails() throws Exception {
|
||||
User user = user("alice");
|
||||
when(transfer.createUser(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(user);
|
||||
AwsException importFailure = new AwsException("InvalidRequestException", "bad key", 400);
|
||||
when(transfer.importSshPublicKey(any(), any(), any())).thenThrow(importFailure);
|
||||
AwsException cleanupFailure = new AwsException("InternalFailure", "boom", 500);
|
||||
doThrow(cleanupFailure).when(transfer).deleteUser(SERVER_ID, "alice");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(userResource(),
|
||||
mapper.readTree("{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"alice\","
|
||||
+ "\"Role\":\"r\",\"SshPublicKeys\":[\"ssh-rsa BAD\"]}"), context(null)));
|
||||
|
||||
assertSame(importFailure, failure);
|
||||
assertEquals(cleanupFailure, failure.getSuppressed()[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void userRollbackHookRestoresPriorStateAfterLaterResourceFails() throws Exception {
|
||||
User user = user("alice");
|
||||
user.setRole("role-1");
|
||||
user.setHomeDirectory("/b/old");
|
||||
user.setHomeDirectoryType("LOGICAL");
|
||||
user.setHomeDirectoryMappings(List.of(new HomeDirectoryMapping("/a", "/b/a")));
|
||||
Instant imported = Instant.parse("2026-01-02T03:04:05Z");
|
||||
user.setSshPublicKeys(List.of(new SshPublicKey("key-old", "ssh-rsa OLD", imported)));
|
||||
when(transfer.getUser(SERVER_ID, "alice")).thenReturn(user);
|
||||
when(transfer.listTagsForResource(user.getArn())).thenReturn(Map.of("env", "old"));
|
||||
User updated = user("alice");
|
||||
updated.setSshPublicKeys(List.of(new SshPublicKey("key-new", "ssh-rsa NEW", null),
|
||||
new SshPublicKey("key-outside", "ssh-rsa OUTSIDE", null)));
|
||||
when(transfer.updateUser(any(), any(), any(), any(), any(), any())).thenReturn(updated);
|
||||
StackResource resource = userResource();
|
||||
resource.getAttributes().put("__FlociTransferUserTemplateSshKeys", "[\"ssh-rsa OLD\"]");
|
||||
resource.getAttributes().put("__FlociTransferServerTemplateTagKeys", "[\"env\"]");
|
||||
|
||||
provisioner.provision(resource, mapper.readTree(
|
||||
"{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"alice\",\"Role\":\"role-2\","
|
||||
+ "\"SshPublicKeys\":[\"ssh-rsa NEW\"],\"Tags\":[{\"Key\":\"team\",\"Value\":\"x\"}]}"),
|
||||
context(user.getArn()));
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
ArgumentCaptor<List<HomeDirectoryMapping>> restored = ArgumentCaptor.forClass(List.class);
|
||||
verify(transfer).updateUser(eq(SERVER_ID), eq("alice"), eq("role-1"), eq("/b/old"), eq("LOGICAL"),
|
||||
restored.capture());
|
||||
assertEquals("/a", restored.getValue().get(0).getEntry());
|
||||
verify(transfer, atLeastOnce()).deleteSshPublicKey(SERVER_ID, "alice", "key-new");
|
||||
verify(transfer, never()).deleteSshPublicKey(SERVER_ID, "alice", "key-outside");
|
||||
verify(transfer, never()).importSshPublicKey(SERVER_ID, "alice", "ssh-rsa OLD");
|
||||
ArgumentCaptor<SshPublicKey> restoredKey = ArgumentCaptor.forClass(SshPublicKey.class);
|
||||
verify(transfer).restoreSshPublicKey(eq(SERVER_ID), eq("alice"), restoredKey.capture());
|
||||
assertEquals("key-old", restoredKey.getValue().getSshPublicKeyId());
|
||||
assertEquals("ssh-rsa OLD", restoredKey.getValue().getSshPublicKeyBody());
|
||||
assertEquals(imported, restoredKey.getValue().getDateImported());
|
||||
verify(transfer).untagResource(user.getArn(), List.of("team"));
|
||||
assertNull(resource.getAttributes().get("__FlociTransferUserUpdateSnapshot"));
|
||||
assertEquals("[\"ssh-rsa OLD\"]", resource.getAttributes().get("__FlociTransferUserTemplateSshKeys"));
|
||||
assertEquals("[\"env\"]", resource.getAttributes().get("__FlociTransferServerTemplateTagKeys"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void userUpdateFailureRestoresPriorStateEagerly() throws Exception {
|
||||
User user = user("alice");
|
||||
user.setRole("role-1");
|
||||
user.setHomeDirectory("/");
|
||||
user.setHomeDirectoryType("PATH");
|
||||
when(transfer.getUser(SERVER_ID, "alice")).thenReturn(user);
|
||||
when(transfer.listTagsForResource(user.getArn())).thenReturn(Map.of());
|
||||
when(transfer.updateUser(any(), any(), any(), any(), any(), any())).thenReturn(user);
|
||||
doThrow(new AwsException("InvalidRequestException", "tag rejected", 400))
|
||||
.when(transfer).tagResource(user.getArn(), Map.of("new", "v"));
|
||||
StackResource resource = userResource();
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource, mapper.readTree(
|
||||
"{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"alice\",\"Role\":\"role-2\","
|
||||
+ "\"Tags\":[{\"Key\":\"new\",\"Value\":\"v\"}]}"), context(user.getArn())));
|
||||
|
||||
verify(transfer).updateUser(eq(SERVER_ID), eq("alice"), eq("role-1"), eq("/"), eq("PATH"), any());
|
||||
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void userUserNameChangeCreatesReplacement() throws Exception {
|
||||
User replacement = user("bob");
|
||||
when(transfer.createUser("s-12345678901234567", "us-east-1", "bob", "role-arn", null, null, List.of(),
|
||||
Map.of())).thenReturn(replacement);
|
||||
StackResource resource = userResource();
|
||||
|
||||
provisioner.provision(resource, mapper.readTree(
|
||||
"{\"ServerId\":\"s-12345678901234567\",\"UserName\":\"bob\",\"Role\":\"role-arn\"}"),
|
||||
context(user("alice").getArn()));
|
||||
|
||||
assertEquals(replacement.getArn(), resource.getPhysicalId());
|
||||
verify(transfer, never()).updateUser(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userRejectsUnsupportedPropertyAndMissingRole() throws Exception {
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(userResource(), mapper.readTree(
|
||||
"{\"ServerId\":\"s-1\",\"UserName\":\"a\",\"Role\":\"r\",\"Policy\":\"{}\"}"), context(null)));
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(userResource(), mapper.readTree(
|
||||
"{\"ServerId\":\"s-1\",\"UserName\":\"a\"}"), context(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void userDeleteToleratesAlreadyGoneOnly() {
|
||||
User user = user("alice");
|
||||
provisioner.delete("AWS::Transfer::User", user.getArn(), "us-east-1");
|
||||
verify(transfer).deleteUser("s-12345678901234567", "alice");
|
||||
|
||||
doThrow(new AwsException("ResourceNotFoundException", "gone", 404))
|
||||
.when(transfer).deleteUser("s-12345678901234567", "alice");
|
||||
provisioner.delete("AWS::Transfer::User", user.getArn(), "us-east-1");
|
||||
|
||||
doThrow(new AwsException("InternalServiceError", "boom", 500))
|
||||
.when(transfer).deleteUser("s-12345678901234567", "alice");
|
||||
assertThrows(AwsException.class,
|
||||
() -> provisioner.delete("AWS::Transfer::User", user.getArn(), "us-east-1"));
|
||||
}
|
||||
|
||||
private StackResource userResource() {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("User");
|
||||
resource.setResourceType("AWS::Transfer::User");
|
||||
return resource;
|
||||
}
|
||||
|
||||
private User user(String name) {
|
||||
User user = new User();
|
||||
user.setUserName(name);
|
||||
user.setArn("arn:aws:transfer:us-east-1:000000000000:user/s-12345678901234567/" + name);
|
||||
return user;
|
||||
}
|
||||
|
||||
private ProvisionContext context(String priorId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(invocation -> ((JsonNode) invocation.getArgument(0)).asText());
|
||||
|
||||
@@ -157,6 +157,7 @@ AWS::ServiceDiscovery::PublicDnsNamespace CloudMapCfnProvisioner
|
||||
AWS::ServiceDiscovery::Service CloudMapCfnProvisioner
|
||||
AWS::StepFunctions::StateMachine StepFunctionsCfnProvisioner
|
||||
AWS::Transfer::Server TransferCfnProvisioner
|
||||
AWS::Transfer::User TransferCfnProvisioner
|
||||
AWS::WAFv2::WebACL WafV2CfnProvisioner
|
||||
AWS::WAFv2::WebACLAssociation WafV2CfnProvisioner
|
||||
Custom::DynamoDBReplica DynamoDbCfnProvisioner
|
||||
|
@@ -171,6 +171,7 @@ notes:
|
||||
AWS::RedshiftServerless::Workgroup: 'starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form'
|
||||
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::Transfer::User: 'management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user'
|
||||
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'
|
||||
|
||||
Reference in new issue
Block a user