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:
Matheus Oliveira authored and GitHub committed 2026-10-04 18:19:43 -04:00
1 parent 108f2b54bf
commit c6304a26c8
12 files changed
+921 -10

No files matched your search

@@ -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();
}
}
@@ -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());