feat(datasync): add the DataSync management plane (#3377)

* feat(datasync): add the DataSync management plane

Emulates the AWS DataSync management API over JSON (X-Amz-Target
FmrsService.<Action>, signing name datasync): agents, the eleven
CreateLocation/DescribeLocation/UpdateLocation trios plus the shared
ListLocations and DeleteLocation, tasks, and resource tagging.

Each DescribeLocation* projects the create request that produced the
location, so the configuration that went in is the configuration that comes
back, and LocationUri is derived from that request per the scheme AWS
documents for the type. DescribeAgent reports ONLINE and DescribeTask reports
AVAILABLE from the first read, which is what the Terraform provider's
aws_datasync_task waits on. Credential members (Password, SecretKey,
SasConfiguration, the Kerberos files and the nested Protocol.SMB.Password)
are dropped before the configuration is stored, as AWS never reads them back
either. Errors use InvalidRequestException, the only client error the
DataSync model declares.

The task-execution data plane (StartTaskExecution, DescribeTaskExecution,
ListTaskExecutions, CancelTaskExecution, UpdateTaskExecution) transfers real
bytes between real storage systems and keeps raising UnknownOperationException
rather than a stub success.

* fix(datasync): default VerifyMode from the task mode

The DataSync model documents two VerifyMode defaults, not one:
POINT_IN_TIME_CONSISTENT for a BASIC task and ONLY_FILES_TRANSFERRED for an
ENHANCED one, which also cannot use POINT_IN_TIME_CONSISTENT at all. CreateTask
applied the BASIC default to every task, so an ENHANCED task created without an
explicit VerifyMode read back wrong.

The default now follows TaskMode, and a VerifyMode the mode does not support is
rejected with InvalidRequestException, the only client error this API declares.
UpdateTaskRequest carries no TaskMode, so a task keeps the mode it was created
with and UpdateTask applies the same rule against the stored mode. An
unrecognized TaskMode is rejected rather than silently treated as BASIC.

* test(datasync): add the SDK compatibility test

Drives an agent, an S3 and an NFS location, both task modes and the tag round
trip through the AWS SDK v2 DataSync client, which is the one piece of real-SDK
verification the RestAssured tests do not cover. It asserts the VerifyMode
default for a BASIC and an ENHANCED task, and that an ENHANCED task rejects
POINT_IN_TIME_CONSISTENT on create and on update.

---------

Co-authored-by: lex00 <artigues.dev@gmail.com>
This commit is contained in:
lex00andlex00 authored and GitHub committed 2026-09-11 22:30:02 -04:00
1 parent e096e08690
commit 128d3ef181
22 files changed
+3049 -1

No files matched your search

@@ -0,0 +1,682 @@
package io.github.hectorvent.floci.services.datasync;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsAction;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DataSyncIntegrationTest {
private static final String TARGET = "FmrsService";
private static final String IAM_ROLE_ARN = "arn:aws:iam::000000000000:role/datasync-bucket-access";
private static final String EFS_FILESYSTEM_ARN =
"arn:aws:elasticfilesystem:us-east-1:000000000000:file-system/fs-0123456789abcdef0";
private static final String FSX_FILESYSTEM_ARN =
"arn:aws:fsx:us-east-1:000000000000:file-system/fs-0123456789abcdef0";
private static final String STORAGE_VIRTUAL_MACHINE_ARN =
"arn:aws:fsx:us-east-1:000000000000:storage-virtual-machine/fs-0123456789abcdef0/svm-0123456789abcdef0";
private static final String SUBNET_ARN = "arn:aws:ec2:us-east-1:000000000000:subnet/subnet-0123456789abcdef0";
private static final String SECURITY_GROUP_ARN =
"arn:aws:ec2:us-east-1:000000000000:security-group/sg-0123456789abcdef0";
private static String agentArn;
private static String s3LocationArn;
private static String efsLocationArn;
private static String nfsLocationArn;
private static String smbLocationArn;
private static String objectStorageLocationArn;
private static String hdfsLocationArn;
private static String azureBlobLocationArn;
private static String fsxLustreLocationArn;
private static String fsxOpenZfsLocationArn;
private static String fsxWindowsLocationArn;
private static String fsxOntapLocationArn;
private static String taskArn;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static String createLocation(String action, String body) {
return awsAction(TARGET, action, body)
.then()
.statusCode(200)
.body("LocationArn", matchesPattern("^arn:aws:datasync:[^:]+:\\d{12}:location/loc-[0-9a-f]{17}$"))
.extract().path("LocationArn");
}
private static io.restassured.response.Response describeLocation(String action, String locationArn) {
return awsAction(TARGET, action, "{\"LocationArn\": \"" + locationArn + "\"}");
}
// ---- Agents ----
@Test
@Order(1)
void createAgent() {
agentArn = awsAction(TARGET, "CreateAgent", """
{
"ActivationKey": "AAAAA-1AAAA-BB1CC-DDDDD-EEEEE",
"AgentName": "floci-agent",
"Tags": [{"Key": "team", "Value": "data-movement"}]
}
""")
.then()
.statusCode(200)
.body("AgentArn", matchesPattern("^arn:aws:datasync:[^:]+:\\d{12}:agent/agent-[0-9a-f]{17}$"))
.extract().path("AgentArn");
}
@Test
@Order(2)
void describeAgentReportsOnlineOnTheFirstRead() {
awsAction(TARGET, "DescribeAgent", "{\"AgentArn\": \"" + agentArn + "\"}")
.then()
.statusCode(200)
.body("AgentArn", equalTo(agentArn))
.body("Name", equalTo("floci-agent"))
.body("Status", equalTo("ONLINE"))
.body("EndpointType", equalTo("PUBLIC"))
.body("Platform.Version", equalTo(DataSyncService.AGENT_PLATFORM_VERSION))
.body("CreationTime", greaterThan(0.0f))
.body("LastConnectionTime", greaterThan(0.0f));
}
@Test
@Order(3)
void listAgentsIncludesTheCreatedAgent() {
awsAction(TARGET, "ListAgents", "{}")
.then()
.statusCode(200)
.body("Agents.AgentArn", hasItem(agentArn))
.body("Agents.find { it.AgentArn == '" + agentArn + "' }.Status", equalTo("ONLINE"));
}
@Test
@Order(4)
void updateAgentRenamesTheAgent() {
awsAction(TARGET, "UpdateAgent",
"{\"AgentArn\": \"" + agentArn + "\", \"Name\": \"floci-agent-renamed\"}")
.then()
.statusCode(200);
awsAction(TARGET, "DescribeAgent", "{\"AgentArn\": \"" + agentArn + "\"}")
.then()
.statusCode(200)
.body("Name", equalTo("floci-agent-renamed"));
}
@Test
@Order(5)
void listTagsForAgentReturnsTheCreateTags() {
awsAction(TARGET, "ListTagsForResource", "{\"ResourceArn\": \"" + agentArn + "\"}")
.then()
.statusCode(200)
.body("Tags[0].Key", equalTo("team"))
.body("Tags[0].Value", equalTo("data-movement"));
}
// ---- Locations ----
@Test
@Order(10)
void s3LocationRoundTrip() {
s3LocationArn = createLocation("CreateLocationS3", """
{
"S3BucketArn": "arn:aws:s3:::floci-datasync-bucket",
"Subdirectory": "/backups",
"S3Config": {"BucketAccessRoleArn": "%s"},
"Tags": [{"Key": "env", "Value": "test"}]
}
""".formatted(IAM_ROLE_ARN));
describeLocation("DescribeLocationS3", s3LocationArn)
.then()
.statusCode(200)
.body("LocationArn", equalTo(s3LocationArn))
.body("LocationUri", equalTo("s3://floci-datasync-bucket/backups"))
.body("S3StorageClass", equalTo("STANDARD"))
.body("S3Config.BucketAccessRoleArn", equalTo(IAM_ROLE_ARN))
.body("CreationTime", greaterThan(0.0f));
}
@Test
@Order(11)
void efsLocationRoundTrip() {
efsLocationArn = createLocation("CreateLocationEfs", """
{
"EfsFilesystemArn": "%s",
"Subdirectory": "/exports",
"Ec2Config": {"SubnetArn": "%s", "SecurityGroupArns": ["%s"]}
}
""".formatted(EFS_FILESYSTEM_ARN, SUBNET_ARN, SECURITY_GROUP_ARN));
describeLocation("DescribeLocationEfs", efsLocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("efs://us-east-1.fs-0123456789abcdef0/exports"))
.body("Ec2Config.SubnetArn", equalTo(SUBNET_ARN))
.body("Ec2Config.SecurityGroupArns[0]", equalTo(SECURITY_GROUP_ARN))
.body("InTransitEncryption", equalTo("NONE"));
}
@Test
@Order(12)
void nfsLocationRoundTrip() {
nfsLocationArn = createLocation("CreateLocationNfs", """
{
"Subdirectory": "/export/home",
"ServerHostname": "nfs.example.com",
"OnPremConfig": {"AgentArns": ["%s"]}
}
""".formatted(agentArn));
describeLocation("DescribeLocationNfs", nfsLocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("nfs://nfs.example.com/export/home"))
.body("OnPremConfig.AgentArns[0]", equalTo(agentArn))
.body("MountOptions.Version", equalTo("AUTOMATIC"));
}
@Test
@Order(13)
void smbLocationRoundTripDoesNotEchoThePassword() {
smbLocationArn = createLocation("CreateLocationSmb", """
{
"Subdirectory": "/share",
"ServerHostname": "smb.example.com",
"User": "floci",
"Domain": "EXAMPLE",
"Password": "sup3rs3cret",
"AgentArns": ["%s"]
}
""".formatted(agentArn));
describeLocation("DescribeLocationSmb", smbLocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("smb://smb.example.com/share"))
.body("User", equalTo("floci"))
.body("Domain", equalTo("EXAMPLE"))
.body("AuthenticationType", equalTo("NTLM"))
.body("MountOptions.Version", equalTo("AUTOMATIC"))
.body("AgentArns[0]", equalTo(agentArn))
.body("Password", nullValue());
}
@Test
@Order(14)
void objectStorageLocationRoundTripDoesNotEchoTheSecretKey() {
objectStorageLocationArn = createLocation("CreateLocationObjectStorage", """
{
"ServerHostname": "objects.example.com",
"BucketName": "floci-bucket",
"Subdirectory": "/incoming",
"AccessKey": "AKIAFLOCI",
"SecretKey": "sup3rs3cret",
"AgentArns": ["%s"]
}
""".formatted(agentArn));
describeLocation("DescribeLocationObjectStorage", objectStorageLocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("object-storage://objects.example.com/floci-bucket/incoming"))
.body("ServerProtocol", equalTo("HTTPS"))
.body("ServerPort", equalTo(443))
.body("AccessKey", equalTo("AKIAFLOCI"))
.body("SecretKey", nullValue());
}
@Test
@Order(15)
void hdfsLocationRoundTripAppliesDocumentedDefaults() {
hdfsLocationArn = createLocation("CreateLocationHdfs", """
{
"Subdirectory": "/user/hadoop",
"NameNodes": [{"Hostname": "namenode.example.com", "Port": 8020}],
"AuthenticationType": "SIMPLE",
"SimpleUser": "hadoop",
"AgentArns": ["%s"]
}
""".formatted(agentArn));
describeLocation("DescribeLocationHdfs", hdfsLocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("hdfs://namenode.example.com:8020/user/hadoop"))
.body("NameNodes[0].Hostname", equalTo("namenode.example.com"))
.body("NameNodes[0].Port", equalTo(8020))
.body("BlockSize", equalTo(134217728))
.body("ReplicationFactor", equalTo(3))
.body("QopConfiguration.RpcProtection", equalTo("PRIVACY"))
.body("QopConfiguration.DataTransferProtection", equalTo("PRIVACY"))
.body("AuthenticationType", equalTo("SIMPLE"))
.body("SimpleUser", equalTo("hadoop"));
}
@Test
@Order(16)
void azureBlobLocationRoundTrip() {
azureBlobLocationArn = createLocation("CreateLocationAzureBlob", """
{
"ContainerUrl": "https://flociaccount.blob.core.windows.net/flocicontainer",
"AuthenticationType": "SAS",
"SasConfiguration": {"Token": "sv=2021&sig=secret"},
"Subdirectory": "/data",
"AgentArns": ["%s"]
}
""".formatted(agentArn));
describeLocation("DescribeLocationAzureBlob", azureBlobLocationArn)
.then()
.statusCode(200)
.body("LocationUri",
equalTo("azure-blob://flociaccount.blob.core.windows.net/flocicontainer/data"))
.body("AuthenticationType", equalTo("SAS"))
.body("BlobType", equalTo("BLOCK"))
.body("AccessTier", equalTo("HOT"))
.body("AgentArns[0]", equalTo(agentArn))
.body("SasConfiguration", nullValue());
}
@Test
@Order(17)
void fsxLustreLocationRoundTrip() {
fsxLustreLocationArn = createLocation("CreateLocationFsxLustre", """
{
"FsxFilesystemArn": "%s",
"SecurityGroupArns": ["%s"],
"Subdirectory": "/scratch"
}
""".formatted(FSX_FILESYSTEM_ARN, SECURITY_GROUP_ARN));
describeLocation("DescribeLocationFsxLustre", fsxLustreLocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("fsxl://us-east-1.fs-0123456789abcdef0/scratch"))
.body("SecurityGroupArns[0]", equalTo(SECURITY_GROUP_ARN));
}
@Test
@Order(18)
void fsxOpenZfsLocationRoundTrip() {
fsxOpenZfsLocationArn = createLocation("CreateLocationFsxOpenZfs", """
{
"FsxFilesystemArn": "%s",
"SecurityGroupArns": ["%s"],
"Protocol": {"NFS": {"MountOptions": {"Version": "AUTOMATIC"}}},
"Subdirectory": "/fsx/folderA"
}
""".formatted(FSX_FILESYSTEM_ARN, SECURITY_GROUP_ARN));
describeLocation("DescribeLocationFsxOpenZfs", fsxOpenZfsLocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("fsxz://us-east-1.fs-0123456789abcdef0/fsx/folderA"))
.body("Protocol.NFS.MountOptions.Version", equalTo("AUTOMATIC"));
}
@Test
@Order(19)
void fsxWindowsLocationRoundTrip() {
fsxWindowsLocationArn = createLocation("CreateLocationFsxWindows", """
{
"FsxFilesystemArn": "%s",
"SecurityGroupArns": ["%s"],
"User": "floci",
"Domain": "EXAMPLE",
"Password": "sup3rs3cret",
"Subdirectory": "/share"
}
""".formatted(FSX_FILESYSTEM_ARN, SECURITY_GROUP_ARN));
describeLocation("DescribeLocationFsxWindows", fsxWindowsLocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("fsxw://us-east-1.fs-0123456789abcdef0/share"))
.body("User", equalTo("floci"))
.body("Domain", equalTo("EXAMPLE"))
.body("Password", nullValue());
}
@Test
@Order(20)
void fsxOntapLocationDerivesTheFileSystemArn() {
fsxOntapLocationArn = createLocation("CreateLocationFsxOntap", """
{
"StorageVirtualMachineArn": "%s",
"SecurityGroupArns": ["%s"],
"Protocol": {"SMB": {"User": "floci", "Domain": "EXAMPLE", "Password": "sup3rs3cret"}},
"Subdirectory": "/vol1"
}
""".formatted(STORAGE_VIRTUAL_MACHINE_ARN, SECURITY_GROUP_ARN));
describeLocation("DescribeLocationFsxOntap", fsxOntapLocationArn)
.then()
.statusCode(200)
.body("LocationUri",
equalTo("fsxn://us-east-1.fs-0123456789abcdef0.svm-0123456789abcdef0/vol1"))
.body("StorageVirtualMachineArn", equalTo(STORAGE_VIRTUAL_MACHINE_ARN))
.body("FsxFilesystemArn", equalTo(FSX_FILESYSTEM_ARN))
.body("Protocol.SMB.User", equalTo("floci"))
.body("Protocol.SMB.Password", nullValue());
}
@Test
@Order(21)
void updateLocationS3RebuildsTheLocationUri() {
awsAction(TARGET, "UpdateLocationS3", """
{
"LocationArn": "%s",
"Subdirectory": "/archive",
"S3StorageClass": "GLACIER"
}
""".formatted(s3LocationArn))
.then()
.statusCode(200);
describeLocation("DescribeLocationS3", s3LocationArn)
.then()
.statusCode(200)
.body("LocationUri", equalTo("s3://floci-datasync-bucket/archive"))
.body("S3StorageClass", equalTo("GLACIER"))
.body("S3Config.BucketAccessRoleArn", equalTo(IAM_ROLE_ARN));
}
@Test
@Order(22)
void listLocationsSeesEveryCreatedLocation() {
awsAction(TARGET, "ListLocations", "{}")
.then()
.statusCode(200)
.body("Locations.LocationArn", hasItem(s3LocationArn))
.body("Locations.LocationArn", hasItem(efsLocationArn))
.body("Locations.LocationArn", hasItem(nfsLocationArn))
.body("Locations.LocationArn", hasItem(smbLocationArn))
.body("Locations.LocationArn", hasItem(objectStorageLocationArn))
.body("Locations.LocationArn", hasItem(hdfsLocationArn))
.body("Locations.LocationArn", hasItem(azureBlobLocationArn))
.body("Locations.LocationArn", hasItem(fsxLustreLocationArn))
.body("Locations.LocationArn", hasItem(fsxOpenZfsLocationArn))
.body("Locations.LocationArn", hasItem(fsxWindowsLocationArn))
.body("Locations.LocationArn", hasItem(fsxOntapLocationArn));
}
@Test
@Order(23)
void listLocationsHonoursALocationTypeFilter() {
awsAction(TARGET, "ListLocations", """
{"Filters": [{"Name": "LocationType", "Values": ["Efs"], "Operator": "Equals"}]}
""")
.then()
.statusCode(200)
.body("Locations.LocationArn", hasItem(efsLocationArn))
.body("Locations.LocationArn", not(hasItem(s3LocationArn)));
}
@Test
@Order(24)
void describeLocationRejectsAMismatchedLocationType() {
describeLocation("DescribeLocationS3", efsLocationArn)
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
@Test
@Order(25)
void describeMissingLocationIsAnInvalidRequest() {
describeLocation("DescribeLocationS3",
"arn:aws:datasync:us-east-1:000000000000:location/loc-00000000000000000")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", containsString("is not found"));
}
@Test
@Order(26)
void createLocationRejectsAMissingRequiredMember() {
awsAction(TARGET, "CreateLocationS3",
"{\"S3Config\": {\"BucketAccessRoleArn\": \"" + IAM_ROLE_ARN + "\"}}")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", containsString("S3BucketArn"));
}
// ---- Tasks ----
@Test
@Order(30)
void createTaskReportsAvailableOnTheFirstRead() {
taskArn = awsAction(TARGET, "CreateTask", """
{
"SourceLocationArn": "%s",
"DestinationLocationArn": "%s",
"Name": "floci-task",
"Options": {"LogLevel": "TRANSFER", "VerifyMode": "NONE"},
"Tags": [{"Key": "env", "Value": "test"}]
}
""".formatted(nfsLocationArn, s3LocationArn))
.then()
.statusCode(200)
.body("TaskArn", matchesPattern("^arn:aws:datasync:[^:]+:\\d{12}:task/task-[0-9a-f]{17}$"))
.extract().path("TaskArn");
awsAction(TARGET, "DescribeTask", "{\"TaskArn\": \"" + taskArn + "\"}")
.then()
.statusCode(200)
.body("TaskArn", equalTo(taskArn))
.body("Status", equalTo("AVAILABLE"))
.body("Name", equalTo("floci-task"))
.body("TaskMode", equalTo("BASIC"))
.body("SourceLocationArn", equalTo(nfsLocationArn))
.body("DestinationLocationArn", equalTo(s3LocationArn))
.body("SourceNetworkInterfaceArns", emptyIterable())
.body("DestinationNetworkInterfaceArns", emptyIterable())
.body("Excludes", emptyIterable())
.body("Includes", emptyIterable())
.body("Options.LogLevel", equalTo("TRANSFER"))
.body("Options.VerifyMode", equalTo("NONE"))
.body("Options.OverwriteMode", equalTo("ALWAYS"))
.body("Options.PreserveDeletedFiles", equalTo("PRESERVE"))
.body("Options.TransferMode", equalTo("CHANGED"))
.body("Options.BytesPerSecond", equalTo(-1))
.body("CreationTime", greaterThan(0.0f));
}
@Test
@Order(31)
void createTaskRejectsAnUnknownLocation() {
awsAction(TARGET, "CreateTask", """
{
"SourceLocationArn": "arn:aws:datasync:us-east-1:000000000000:location/loc-00000000000000000",
"DestinationLocationArn": "%s"
}
""".formatted(s3LocationArn))
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
@Test
@Order(32)
void listTasksIncludesTheCreatedTask() {
awsAction(TARGET, "ListTasks", "{}")
.then()
.statusCode(200)
.body("Tasks.TaskArn", hasItem(taskArn))
.body("Tasks.find { it.TaskArn == '" + taskArn + "' }.Status", equalTo("AVAILABLE"));
}
@Test
@Order(33)
void updateTaskRenamesAndReschedulesTheTask() {
awsAction(TARGET, "UpdateTask", """
{
"TaskArn": "%s",
"Name": "floci-task-renamed",
"Schedule": {"ScheduleExpression": "cron(0 12 ? * SUN *)", "Status": "ENABLED"},
"Excludes": [{"FilterType": "SIMPLE_PATTERN", "Value": "/tmp"}]
}
""".formatted(taskArn))
.then()
.statusCode(200);
awsAction(TARGET, "DescribeTask", "{\"TaskArn\": \"" + taskArn + "\"}")
.then()
.statusCode(200)
.body("Name", equalTo("floci-task-renamed"))
.body("Schedule.ScheduleExpression", equalTo("cron(0 12 ? * SUN *)"))
.body("Excludes[0].FilterType", equalTo("SIMPLE_PATTERN"))
.body("Excludes[0].Value", equalTo("/tmp"));
}
@Test
@Order(34)
void taskTagRoundTrip() {
awsAction(TARGET, "TagResource", """
{"ResourceArn": "%s", "Tags": [{"Key": "owner", "Value": "platform"}]}
""".formatted(taskArn))
.then()
.statusCode(200);
awsAction(TARGET, "ListTagsForResource", "{\"ResourceArn\": \"" + taskArn + "\"}")
.then()
.statusCode(200)
.body("Tags.Key", hasItem("env"))
.body("Tags.Key", hasItem("owner"))
.body("Tags.find { it.Key == 'owner' }.Value", equalTo("platform"));
awsAction(TARGET, "UntagResource", "{\"ResourceArn\": \"" + taskArn + "\", \"Keys\": [\"env\"]}")
.then()
.statusCode(200);
awsAction(TARGET, "ListTagsForResource", "{\"ResourceArn\": \"" + taskArn + "\"}")
.then()
.statusCode(200)
.body("Tags.Key", not(hasItem("env")))
.body("Tags.Key", hasItem("owner"));
}
@Test
@Order(35)
void enhancedTaskDefaultsToOnlyFilesTransferredAndRejectsPointInTimeConsistent() {
String enhancedTaskArn = awsAction(TARGET, "CreateTask", """
{
"SourceLocationArn": "%s",
"DestinationLocationArn": "%s",
"Name": "floci-task-enhanced",
"TaskMode": "ENHANCED"
}
""".formatted(nfsLocationArn, s3LocationArn))
.then()
.statusCode(200)
.extract().path("TaskArn");
awsAction(TARGET, "DescribeTask", "{\"TaskArn\": \"" + enhancedTaskArn + "\"}")
.then()
.statusCode(200)
.body("TaskMode", equalTo("ENHANCED"))
.body("Options.VerifyMode", equalTo("ONLY_FILES_TRANSFERRED"));
awsAction(TARGET, "UpdateTask", """
{"TaskArn": "%s", "Options": {"VerifyMode": "POINT_IN_TIME_CONSISTENT"}}
""".formatted(enhancedTaskArn))
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", containsString("POINT_IN_TIME_CONSISTENT"));
awsAction(TARGET, "CreateTask", """
{
"SourceLocationArn": "%s",
"DestinationLocationArn": "%s",
"TaskMode": "ENHANCED",
"Options": {"VerifyMode": "POINT_IN_TIME_CONSISTENT"}
}
""".formatted(nfsLocationArn, s3LocationArn))
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
awsAction(TARGET, "DeleteTask", "{\"TaskArn\": \"" + enhancedTaskArn + "\"}")
.then()
.statusCode(200);
}
// ---- Data plane and teardown ----
@Test
@Order(40)
void taskExecutionOperationsAreNotEmulated() {
awsAction(TARGET, "StartTaskExecution", "{\"TaskArn\": \"" + taskArn + "\"}")
.then()
.statusCode(400)
.body("__type", equalTo("UnknownOperationException"));
}
@Test
@Order(41)
void deleteTaskRemovesIt() {
awsAction(TARGET, "DeleteTask", "{\"TaskArn\": \"" + taskArn + "\"}")
.then()
.statusCode(200);
awsAction(TARGET, "DescribeTask", "{\"TaskArn\": \"" + taskArn + "\"}")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
@Test
@Order(42)
void deleteLocationRemovesIt() {
awsAction(TARGET, "DeleteLocation", "{\"LocationArn\": \"" + s3LocationArn + "\"}")
.then()
.statusCode(200);
describeLocation("DescribeLocationS3", s3LocationArn)
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
awsAction(TARGET, "ListLocations", "{}")
.then()
.statusCode(200)
.body("Locations.LocationArn", not(hasItem(s3LocationArn)));
}
@Test
@Order(43)
void deleteAgentRemovesIt() {
awsAction(TARGET, "DeleteAgent", "{\"AgentArn\": \"" + agentArn + "\"}")
.then()
.statusCode(200);
awsAction(TARGET, "DescribeAgent", "{\"AgentArn\": \"" + agentArn + "\"}")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
}
@@ -0,0 +1,448 @@
package io.github.hectorvent.floci.services.datasync;
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.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.datasync.model.DataSyncAgent;
import io.github.hectorvent.floci.services.datasync.model.DataSyncLocation;
import io.github.hectorvent.floci.services.datasync.model.DataSyncLocationType;
import io.github.hectorvent.floci.services.datasync.model.DataSyncTask;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
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.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
class DataSyncServiceTest {
private static final String REGION = "us-east-1";
private static final String FSX_FILESYSTEM_ARN =
"arn:aws:fsx:us-east-1:000000000000:file-system/fs-0123456789abcdef0";
private static final String STORAGE_VIRTUAL_MACHINE_ARN =
"arn:aws:fsx:us-east-1:000000000000:storage-virtual-machine/fs-0123456789abcdef0/svm-0123456789abcdef0";
private final ObjectMapper mapper = new ObjectMapper();
private DataSyncService service;
@BeforeEach
void setUp() {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
// A fresh backend per call: agents, locations and tasks are three separate stores,
// and sharing one would let a location ARN resolve out of the agent store.
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
service = new DataSyncService(storageFactory, new RegionResolver(REGION, "000000000000"), mapper);
}
private JsonNode json(String body) {
try {
return mapper.readTree(body);
} catch (Exception e) {
throw new IllegalArgumentException("test fixture is not valid JSON: " + body, e);
}
}
private DataSyncLocation createLocation(DataSyncLocationType type, String body) {
return service.createLocation(type, json(body), REGION);
}
@Test
void createAgentIsOnlineAndPublicWithoutAVpcEndpoint() {
DataSyncAgent agent = service.createAgent(
json("{\"ActivationKey\": \"AAAAA-1AAAA-BB1CC-DDDDD-EEEEE\", \"AgentName\": \"floci\"}"), REGION);
assertTrue(agent.getAgentArn().startsWith("arn:aws:datasync:us-east-1:000000000000:agent/agent-"));
assertEquals(DataSyncService.AGENT_STATUS_ONLINE, agent.getStatus());
assertEquals("PUBLIC", agent.getEndpointType());
assertEquals("floci", agent.getName());
}
@Test
void createAgentWithAVpcEndpointReportsPrivateLink() {
DataSyncAgent agent = service.createAgent(json("""
{"ActivationKey": "AAAAA-1AAAA-BB1CC-DDDDD-EEEEE", "VpcEndpointId": "vpce-0123456789abcdef0"}
"""), REGION);
assertEquals("PRIVATE_LINK", agent.getEndpointType());
assertEquals("vpce-0123456789abcdef0", agent.getVpcEndpointId());
}
@Test
void createAgentWithoutAnActivationKeyIsAnInvalidRequest() {
AwsException error = assertThrows(AwsException.class,
() -> service.createAgent(json("{\"AgentName\": \"floci\"}"), REGION));
assertEquals("InvalidRequestException", error.getErrorCode());
assertTrue(error.getMessage().contains("ActivationKey"));
}
@Test
void s3LocationDerivesItsUriFromTheBucketArnAndSubdirectory() {
DataSyncLocation location = createLocation(DataSyncLocationType.S3, """
{"S3BucketArn": "arn:aws:s3:::floci-bucket", "Subdirectory": "/backups/",
"S3Config": {"BucketAccessRoleArn": "arn:aws:iam::000000000000:role/datasync"}}
""");
assertEquals("s3://floci-bucket/backups", location.getLocationUri());
assertEquals("STANDARD", location.getConfiguration().path("S3StorageClass").asText());
}
@Test
void s3LocationWithoutASubdirectoryOmitsTheTrailingSlash() {
DataSyncLocation location = createLocation(DataSyncLocationType.S3, """
{"S3BucketArn": "arn:aws:s3:::floci-bucket",
"S3Config": {"BucketAccessRoleArn": "arn:aws:iam::000000000000:role/datasync"}}
""");
assertEquals("s3://floci-bucket", location.getLocationUri());
}
@Test
void fsxOntapLocationDerivesTheFileSystemArnFromTheSvmArn() {
DataSyncLocation location = createLocation(DataSyncLocationType.FSX_ONTAP, """
{"StorageVirtualMachineArn": "%s", "SecurityGroupArns": ["sg"],
"Protocol": {"SMB": {"User": "floci", "Password": "sup3rs3cret"}}, "Subdirectory": "/vol1"}
""".formatted(STORAGE_VIRTUAL_MACHINE_ARN));
assertEquals("fsxn://us-east-1.fs-0123456789abcdef0.svm-0123456789abcdef0/vol1",
location.getLocationUri());
assertEquals(FSX_FILESYSTEM_ARN, location.getConfiguration().path("FsxFilesystemArn").asText());
}
@Test
void nestedProtocolPasswordIsStrippedBeforeTheConfigurationIsStored() {
DataSyncLocation location = createLocation(DataSyncLocationType.FSX_ONTAP, """
{"StorageVirtualMachineArn": "%s", "SecurityGroupArns": ["sg"],
"Protocol": {"SMB": {"User": "floci", "Password": "sup3rs3cret"}}}
""".formatted(STORAGE_VIRTUAL_MACHINE_ARN));
JsonNode smb = location.getConfiguration().path("Protocol").path("SMB");
assertEquals("floci", smb.path("User").asText());
assertFalse(smb.has("Password"));
}
@Test
void topLevelCredentialMembersAreStrippedBeforeTheConfigurationIsStored() {
DataSyncLocation location = createLocation(DataSyncLocationType.OBJECT_STORAGE, """
{"ServerHostname": "objects.example.com", "BucketName": "floci-bucket",
"AccessKey": "AKIAFLOCI", "SecretKey": "sup3rs3cret"}
""");
assertEquals("AKIAFLOCI", location.getConfiguration().path("AccessKey").asText());
assertFalse(location.getConfiguration().has("SecretKey"));
}
@Test
void objectStorageDefaultsToHttpsOnPort443() {
DataSyncLocation location = createLocation(DataSyncLocationType.OBJECT_STORAGE, """
{"ServerHostname": "objects.example.com", "BucketName": "floci-bucket", "Subdirectory": "/incoming"}
""");
assertEquals("object-storage://objects.example.com/floci-bucket/incoming", location.getLocationUri());
assertEquals("HTTPS", location.getConfiguration().path("ServerProtocol").asText());
assertEquals(443, location.getConfiguration().path("ServerPort").asInt());
}
@Test
void objectStorageOverHttpDefaultsToPort80() {
DataSyncLocation location = createLocation(DataSyncLocationType.OBJECT_STORAGE, """
{"ServerHostname": "objects.example.com", "BucketName": "floci-bucket", "ServerProtocol": "HTTP"}
""");
assertEquals(80, location.getConfiguration().path("ServerPort").asInt());
}
@Test
void hdfsAppliesTheDocumentedBlockSizeReplicationAndQopDefaults() {
DataSyncLocation location = createLocation(DataSyncLocationType.HDFS, """
{"NameNodes": [{"Hostname": "namenode.example.com", "Port": 8020}],
"AuthenticationType": "SIMPLE", "AgentArns": ["agent"], "Subdirectory": "/user/hadoop"}
""");
assertEquals("hdfs://namenode.example.com:8020/user/hadoop", location.getLocationUri());
JsonNode configuration = location.getConfiguration();
assertEquals(134217728, configuration.path("BlockSize").asInt());
assertEquals(3, configuration.path("ReplicationFactor").asInt());
assertEquals("PRIVACY", configuration.path("QopConfiguration").path("RpcProtection").asText());
assertEquals("PRIVACY", configuration.path("QopConfiguration").path("DataTransferProtection").asText());
}
@Test
void createLocationWithoutARequiredMemberIsAnInvalidRequest() {
AwsException error = assertThrows(AwsException.class,
() -> createLocation(DataSyncLocationType.S3,
"{\"S3Config\": {\"BucketAccessRoleArn\": \"arn:aws:iam::000000000000:role/datasync\"}}"));
assertEquals("InvalidRequestException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertTrue(error.getMessage().contains("S3BucketArn"));
}
@Test
void createLocationFsxWindowsDoesNotRequireAPassword() {
DataSyncLocation location = createLocation(DataSyncLocationType.FSX_WINDOWS, """
{"FsxFilesystemArn": "%s", "SecurityGroupArns": ["sg"], "User": "floci", "Subdirectory": "/share"}
""".formatted(FSX_FILESYSTEM_ARN));
assertEquals("fsxw://us-east-1.fs-0123456789abcdef0/share", location.getLocationUri());
}
@Test
void updateLocationMergesTheRequestAndRebuildsTheUri() {
DataSyncLocation location = createLocation(DataSyncLocationType.S3, """
{"S3BucketArn": "arn:aws:s3:::floci-bucket", "Subdirectory": "/backups",
"S3Config": {"BucketAccessRoleArn": "arn:aws:iam::000000000000:role/datasync"}}
""");
DataSyncLocation updated = service.updateLocation(DataSyncLocationType.S3, json("""
{"LocationArn": "%s", "Subdirectory": "/archive", "S3StorageClass": "GLACIER"}
""".formatted(location.getLocationArn())));
assertEquals("s3://floci-bucket/archive", updated.getLocationUri());
assertEquals("GLACIER", updated.getConfiguration().path("S3StorageClass").asText());
assertEquals("arn:aws:iam::000000000000:role/datasync",
updated.getConfiguration().path("S3Config").path("BucketAccessRoleArn").asText());
}
@Test
void describingALocationAsTheWrongTypeIsAnInvalidRequest() {
DataSyncLocation location = createLocation(DataSyncLocationType.NFS, """
{"Subdirectory": "/export", "ServerHostname": "nfs.example.com",
"OnPremConfig": {"AgentArns": ["agent"]}}
""");
AwsException error = assertThrows(AwsException.class,
() -> service.getLocation(location.getLocationArn(), DataSyncLocationType.S3));
assertEquals("InvalidRequestException", error.getErrorCode());
}
@Test
void createTaskIsAvailableAndMergesTheRequestedOptionsOverTheDefaults() {
DataSyncLocation source = createLocation(DataSyncLocationType.NFS, """
{"Subdirectory": "/export", "ServerHostname": "nfs.example.com",
"OnPremConfig": {"AgentArns": ["agent"]}}
""");
DataSyncLocation destination = createLocation(DataSyncLocationType.S3, """
{"S3BucketArn": "arn:aws:s3:::floci-bucket",
"S3Config": {"BucketAccessRoleArn": "arn:aws:iam::000000000000:role/datasync"}}
""");
DataSyncTask task = service.createTask(json("""
{"SourceLocationArn": "%s", "DestinationLocationArn": "%s", "Name": "nightly",
"Options": {"LogLevel": "TRANSFER", "VerifyMode": "NONE"}}
""".formatted(source.getLocationArn(), destination.getLocationArn())), REGION);
assertEquals(DataSyncService.TASK_STATUS_AVAILABLE, task.getStatus());
assertEquals(DataSyncService.DEFAULT_TASK_MODE, task.getTaskMode());
assertEquals("TRANSFER", task.getOptions().path("LogLevel").asText());
assertEquals("NONE", task.getOptions().path("VerifyMode").asText());
assertEquals("ALWAYS", task.getOptions().path("OverwriteMode").asText());
assertEquals(-1L, task.getOptions().path("BytesPerSecond").asLong());
}
@Test
void createTaskAgainstAnUnknownLocationIsAnInvalidRequest() {
AwsException error = assertThrows(AwsException.class, () -> service.createTask(json("""
{"SourceLocationArn": "arn:aws:datasync:us-east-1:000000000000:location/loc-00000000000000000",
"DestinationLocationArn": "arn:aws:datasync:us-east-1:000000000000:location/loc-00000000000000001"}
"""), REGION));
assertEquals("InvalidRequestException", error.getErrorCode());
}
private JsonNode taskRequest(String extraMembers) {
DataSyncLocation source = createLocation(DataSyncLocationType.NFS, """
{"Subdirectory": "/export", "ServerHostname": "nfs.example.com",
"OnPremConfig": {"AgentArns": ["agent"]}}
""");
DataSyncLocation destination = createLocation(DataSyncLocationType.S3, """
{"S3BucketArn": "arn:aws:s3:::floci-bucket",
"S3Config": {"BucketAccessRoleArn": "arn:aws:iam::000000000000:role/datasync"}}
""");
return json("""
{"SourceLocationArn": "%s", "DestinationLocationArn": "%s", "Name": "nightly"%s}
""".formatted(source.getLocationArn(), destination.getLocationArn(), extraMembers));
}
@Test
void createTaskWithoutATaskModeIsBasicAndVerifiesPointInTime() {
DataSyncTask task = service.createTask(taskRequest(""), REGION);
assertEquals(DataSyncService.DEFAULT_TASK_MODE, task.getTaskMode());
assertEquals(DataSyncService.VERIFY_MODE_POINT_IN_TIME_CONSISTENT,
task.getOptions().path("VerifyMode").asText());
}
@Test
void createBasicTaskDefaultsToPointInTimeConsistentVerification() {
DataSyncTask task = service.createTask(taskRequest(", \"TaskMode\": \"BASIC\""), REGION);
assertEquals("BASIC", task.getTaskMode());
assertEquals(DataSyncService.VERIFY_MODE_POINT_IN_TIME_CONSISTENT,
task.getOptions().path("VerifyMode").asText());
}
@Test
void createEnhancedTaskDefaultsToOnlyFilesTransferredVerification() {
DataSyncTask task = service.createTask(taskRequest(", \"TaskMode\": \"ENHANCED\""), REGION);
assertEquals(DataSyncService.TASK_MODE_ENHANCED, task.getTaskMode());
assertEquals(DataSyncService.VERIFY_MODE_ONLY_FILES_TRANSFERRED,
task.getOptions().path("VerifyMode").asText());
}
@Test
void createBasicTaskKeepsAnExplicitVerifyMode() {
DataSyncTask task = service.createTask(
taskRequest(", \"Options\": {\"VerifyMode\": \"ONLY_FILES_TRANSFERRED\"}"), REGION);
assertEquals(DataSyncService.VERIFY_MODE_ONLY_FILES_TRANSFERRED,
task.getOptions().path("VerifyMode").asText());
}
@Test
void createEnhancedTaskKeepsAnExplicitVerifyModeItSupports() {
DataSyncTask task = service.createTask(taskRequest(
", \"TaskMode\": \"ENHANCED\", \"Options\": {\"VerifyMode\": \"NONE\"}"), REGION);
assertEquals("NONE", task.getOptions().path("VerifyMode").asText());
}
@Test
void createEnhancedTaskRejectsPointInTimeConsistentVerification() {
JsonNode request = taskRequest(
", \"TaskMode\": \"ENHANCED\", \"Options\": {\"VerifyMode\": \"POINT_IN_TIME_CONSISTENT\"}");
AwsException error = assertThrows(AwsException.class, () -> service.createTask(request, REGION));
assertEquals("InvalidRequestException", error.getErrorCode());
assertTrue(error.getMessage().contains("POINT_IN_TIME_CONSISTENT"), error.getMessage());
}
@Test
void createTaskRejectsAnUnknownTaskMode() {
JsonNode request = taskRequest(", \"TaskMode\": \"TURBO\"");
AwsException error = assertThrows(AwsException.class, () -> service.createTask(request, REGION));
assertEquals("InvalidRequestException", error.getErrorCode());
}
@Test
void updateTaskKeepsTheVerifyModeDefaultOfTheModeTheTaskWasCreatedWith() {
DataSyncTask task = service.createTask(taskRequest(", \"TaskMode\": \"ENHANCED\""), REGION);
DataSyncTask updated = service.updateTask(json("""
{"TaskArn": "%s", "Options": {"LogLevel": "TRANSFER"}}
""".formatted(task.getTaskArn())));
assertEquals(DataSyncService.TASK_MODE_ENHANCED, updated.getTaskMode());
assertEquals(DataSyncService.VERIFY_MODE_ONLY_FILES_TRANSFERRED,
updated.getOptions().path("VerifyMode").asText());
}
@Test
void updateTaskRejectsAVerifyModeTheStoredTaskModeDoesNotSupport() {
DataSyncTask task = service.createTask(taskRequest(", \"TaskMode\": \"ENHANCED\""), REGION);
JsonNode request = json("""
{"TaskArn": "%s", "Options": {"VerifyMode": "POINT_IN_TIME_CONSISTENT"}}
""".formatted(task.getTaskArn()));
AwsException error = assertThrows(AwsException.class, () -> service.updateTask(request));
assertEquals("InvalidRequestException", error.getErrorCode());
}
@Test
void listLocationsFiltersByLocationType() {
DataSyncLocation nfs = createLocation(DataSyncLocationType.NFS, """
{"Subdirectory": "/export", "ServerHostname": "nfs.example.com",
"OnPremConfig": {"AgentArns": ["agent"]}}
""");
createLocation(DataSyncLocationType.S3, """
{"S3BucketArn": "arn:aws:s3:::floci-bucket",
"S3Config": {"BucketAccessRoleArn": "arn:aws:iam::000000000000:role/datasync"}}
""");
var page = service.listLocations(
json("[{\"Name\": \"LocationType\", \"Values\": [\"Nfs\"], \"Operator\": \"Equals\"}]"), null, 0);
assertEquals(List.of(nfs.getLocationArn()),
page.items().stream().map(DataSyncLocation::getLocationArn).toList());
assertNull(page.nextToken());
}
@Test
void listLocationsRejectsAnUnknownFilterName() {
createLocation(DataSyncLocationType.S3, """
{"S3BucketArn": "arn:aws:s3:::floci-bucket",
"S3Config": {"BucketAccessRoleArn": "arn:aws:iam::000000000000:role/datasync"}}
""");
AwsException error = assertThrows(AwsException.class, () -> service.listLocations(
json("[{\"Name\": \"Nope\", \"Values\": [\"x\"]}]"), null, 0));
assertEquals("InvalidRequestException", error.getErrorCode());
}
@Test
void listAgentsPagesOnMaxResultsAndResumesFromTheNextToken() {
for (int i = 0; i < 3; i++) {
service.createAgent(json("{\"ActivationKey\": \"AAAAA-1AAAA-BB1CC-DDDDD-EEEEE\"}"), REGION);
}
var first = service.listAgents(null, 2);
assertEquals(2, first.items().size());
assertEquals(first.items().get(1).getAgentArn(), first.nextToken());
var second = service.listAgents(first.nextToken(), 2);
assertEquals(1, second.items().size());
assertNull(second.nextToken());
}
@Test
void tagsSurviveTheirCreateAndRoundTripThroughTagAndUntag() {
DataSyncAgent agent = service.createAgent(json("""
{"ActivationKey": "AAAAA-1AAAA-BB1CC-DDDDD-EEEEE",
"Tags": [{"Key": "env", "Value": "test"}]}
"""), REGION);
assertEquals(Map.of("env", "test"), service.listTagsForResource(agent.getAgentArn()));
service.tagResource(agent.getAgentArn(), Map.of("owner", "platform"));
assertEquals("platform", service.listTagsForResource(agent.getAgentArn()).get("owner"));
service.untagResource(agent.getAgentArn(), List.of("env"));
assertEquals(Map.of("owner", "platform"), service.listTagsForResource(agent.getAgentArn()));
}
@Test
void taggingAnUnknownResourceIsAnInvalidRequest() {
AwsException error = assertThrows(AwsException.class, () -> service.listTagsForResource(
"arn:aws:datasync:us-east-1:000000000000:task/task-00000000000000000"));
assertEquals("InvalidRequestException", error.getErrorCode());
}
@Test
void deleteAgentRemovesItFromTheStore() {
DataSyncAgent agent = service.createAgent(
json("{\"ActivationKey\": \"AAAAA-1AAAA-BB1CC-DDDDD-EEEEE\"}"), REGION);
service.deleteAgent(agent.getAgentArn());
assertThrows(AwsException.class, () -> service.getAgent(agent.getAgentArn()));
}
}