feat(dms): import, describe and delete certificates (#10159)

This commit is contained in:
Maddog2050 authored and GitHub committed 2026-12-04 20:36:18 -04:00
1 parent b655354ead
commit d9bb151b22
9 files changed
+601 -23

No files matched your search

@@ -1,15 +1,20 @@
package com.floci.test;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.databasemigration.DatabaseMigrationClient;
import software.amazon.awssdk.services.databasemigration.model.Certificate;
import software.amazon.awssdk.services.databasemigration.model.DatabaseMigrationException;
import software.amazon.awssdk.services.databasemigration.model.DescribeReplicationSubnetGroupsResponse;
import software.amazon.awssdk.services.databasemigration.model.DmsSslModeValue;
import software.amazon.awssdk.services.databasemigration.model.ReplicationEndpointTypeValue;
import software.amazon.awssdk.services.databasemigration.model.ReplicationSubnetGroup;
import software.amazon.awssdk.services.databasemigration.model.Tag;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Subnet;
import software.amazon.awssdk.services.sts.StsClient;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -17,6 +22,7 @@ import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -25,6 +31,29 @@ class DmsTest {
private static final String GROUP_ID = "sdk-compat-subnet-group";
private static final String PAGED_GROUP_PREFIX = "sdk-compat-page-";
private static final String CONTROL_CHAR_GROUP_ID = "sdk-compat-control-char";
private static final String CERTIFICATE_ID = "sdk-compat-certificate";
private static final String WALLET_ID = "sdk-compat-wallet";
private static final String CERTIFICATE_ENDPOINT_ID = "sdk-compat-certificate-target";
/** Self-signed RSA 2048 / SHA-256, valid from 2026-12-04T09:52:48Z to 2126-11-10T09:52:48Z. */
private static final String CERTIFICATE_PEM = String.join("\n",
"-----BEGIN CERTIFICATE-----",
"MIIC9DCCAdygAwIBAgIUfzabzD8tJ09yniczWJ44kUZYWkAwDQYJKoZIhvcNAQEL",
"BQAwGTEXMBUGA1UEAwwOZmxvY2ktZG1zLXRlc3QwIBcNMjYxMjA0MDk1MjQ4WhgP",
"MjEyNjExMTAwOTUyNDhaMBkxFzAVBgNVBAMMDmZsb2NpLWRtcy10ZXN0MIIBIjAN",
"BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwEHVZstYNZkxX7NTJlTVtN2nW+zH",
"JVBBatmvj1zTABrltJze1Ue1qSkWQt1Tr2+YAxM74cGj4x+f8DVjCjv1apWylaZw",
"rVrTSly7SNC0LUXcj1GBmyblNHlQADrgMN8gG0hvjcr3cTlBgofNVAcMjWozCr0B",
"DCH5mS0lYK+Ue8F96xgkhuIIMD23G/eK9iFi6Iglq9y7kmLx/51Qq8dX0v7KmSWe",
"fUjfvZYUfTe+1wheE0w7DqxOx7NxmtwbpdMV8MauHD8mJpOBTIb/Se684POwm2n+",
"bKUe0fFtolePb84p5E5ygFokpavBJvFYZkNGwST9GQjBmTHuhh1jXG2pUQIDAQAB",
"ozIwMDAdBgNVHQ4EFgQUxsp1n5i+NT4QZYrTjvM/i97p+qswDwYDVR0TAQH/BAUw",
"AwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAG9zQOyfzKTQe8JhySyrVleUdtiIcwwfL",
"92DVu0HPciz5stlULtPuc40Y2kpIwWjCkFA+gP26W/h9tEYL0nMoKEYoD8Rnxuw+",
"8GXZrMI2cGYTXuberP5vTnRmcUUuyjVx4Ewd0FhZKFl9tlkdDUWAfyG0nN1b8yGC",
"TDohLdOgEQBkpvwwhi/liTJZgGd2IDums1E2wkgvOnYWxAZwVzECFbLJPrRvhCfu",
"eJEDR/wl9qt+TI8+F3R+6WOqdlG1gy8gEtxH/q2Gpii/6oM1sig8Q/XUlKIdEQ9T",
"WjMC6tpZFTPj5/7onCJQx/lu6aM5rGd8w+5yDDXlRJok3kXIHzBLMw==",
"-----END CERTIFICATE-----") + "\n";
@Test
void replicationSubnetGroupLifecycleUsesAwsSdkWireContract() {
@@ -157,6 +186,84 @@ class DmsTest {
}
}
/**
* The SDK parses every Certificate timestamp strictly, so this also checks the epoch-seconds
* format of ValidFromDate, ValidToDate and CertificateCreationDate.
*/
@Test
void certificateLifecycleUsesAwsSdkWireContract() {
try (DatabaseMigrationClient dms = TestFixtures.databaseMigrationClient()) {
Certificate imported = dms.importCertificate(request -> request
.certificateIdentifier(CERTIFICATE_ID)
.certificatePem(CERTIFICATE_PEM)
.tags(tag -> tag.key("env").value("test"))).certificate();
String arn = imported.certificateArn();
String endpointArn = null;
try {
assertEquals(CERTIFICATE_ID, imported.certificateIdentifier());
assertEquals(Instant.parse("2026-12-04T09:52:48Z"), imported.validFromDate());
assertEquals(Instant.parse("2126-11-10T09:52:48Z"), imported.validToDate());
assertEquals("SHA256withRSA", imported.signingAlgorithm());
assertEquals(2048, imported.keyLength());
assertEquals(callerAccountId(), imported.certificateOwner());
assertNotNull(imported.certificateCreationDate());
List<Certificate> described = dms.describeCertificatesPaginator(request -> request
.filters(filter -> filter.name("certificate-id").values(CERTIFICATE_ID)))
.stream().flatMap(page -> page.certificates().stream()).toList();
assertEquals(1, described.size());
assertEquals(arn, described.get(0).certificateArn());
assertEquals(CERTIFICATE_PEM, described.get(0).certificatePem());
assertEquals(Map.of("env", "test"), tagsOf(dms, arn));
endpointArn = dms.createEndpoint(request -> request
.endpointIdentifier(CERTIFICATE_ENDPOINT_ID)
.endpointType(ReplicationEndpointTypeValue.TARGET)
.engineName("docdb")
.sslMode(DmsSslModeValue.VERIFY_FULL)
.certificateArn(arn)).endpoint().endpointArn();
DatabaseMigrationException inUse = assertThrows(DatabaseMigrationException.class,
() -> dms.deleteCertificate(request -> request.certificateArn(arn)));
assertEquals("InvalidResourceStateFault", inUse.awsErrorDetails().errorCode());
} finally {
if (endpointArn != null) {
String endpoint = endpointArn;
dms.deleteEndpoint(request -> request.endpointArn(endpoint));
}
dms.deleteCertificate(request -> request.certificateArn(arn));
}
DatabaseMigrationException deleted = assertThrows(DatabaseMigrationException.class,
() -> dms.describeCertificates(request -> request
.filters(filter -> filter.name("certificate-id").values(CERTIFICATE_ID))));
assertEquals("ResourceNotFoundFault", deleted.awsErrorDetails().errorCode());
}
}
@Test
void importCertificateRoundTripsAWalletAndRejectsAnInvalidPem() {
try (DatabaseMigrationClient dms = TestFixtures.databaseMigrationClient()) {
SdkBytes wallet = SdkBytes.fromByteArray(new byte[] {1, 2, 3, 4});
String arn = dms.importCertificate(request -> request
.certificateIdentifier(WALLET_ID)
.certificateWallet(wallet)).certificate().certificateArn();
try {
Certificate described = dms.describeCertificates(request -> request
.filters(filter -> filter.name("certificate-arn").values(arn)))
.certificates().get(0);
assertEquals(wallet, described.certificateWallet());
} finally {
dms.deleteCertificate(request -> request.certificateArn(arn));
}
DatabaseMigrationException invalid = assertThrows(DatabaseMigrationException.class,
() -> dms.importCertificate(request -> request
.certificateIdentifier(WALLET_ID)
.certificatePem("not a certificate")));
assertEquals("InvalidCertificateFault", invalid.awsErrorDetails().errorCode());
}
}
/**
* DMS does not return the subnet group's ARN, so the tagging calls need it built the way the
* Terraform provider builds it. Read the account from STS rather than hardcoding the default.
+26 -6
View File
@@ -6,7 +6,7 @@
Floci emulates the replication subnet group, endpoint, replication instance and
replication task lifecycles, which is what `aws_dms_replication_subnet_group`,
`aws_dms_endpoint`, `aws_dms_s3_endpoint`, `aws_dms_replication_instance` and
`aws_dms_replication_task` need to plan, apply and destroy. Subnets are resolved against
`aws_dms_replication_task` and `aws_dms_certificate` need to plan, apply and destroy. Subnets are resolved against
the emulated EC2 service, so the VPC and Availability Zones a group reports are the ones
those subnets actually have. No data is migrated: the resources are control-plane state.
@@ -35,6 +35,9 @@ those subnets actually have. No data is migrated: the resources are control-plan
| `DeleteReplicationTask` | Deletes a replication task that is not running. |
| `StartReplicationTask` | Moves a task to `running`. |
| `StopReplicationTask` | Moves a running task to `stopped`. |
| `ImportCertificate` | Imports a PEM certificate or an Oracle wallet. |
| `DescribeCertificates` | Lists certificates, filtered by `certificate-arn` or `certificate-id`. |
| `DeleteCertificate` | Deletes a certificate that no endpoint uses. |
<!-- floci:actions:end -->
## Behaviour
@@ -76,10 +79,10 @@ those subnets actually have. No data is migrated: the resources are control-plan
not a serialization one.
- Groups are scoped per account and Region and persist through `StorageFactory`.
### Endpoints, replication instances and replication tasks
### Endpoints, replication instances, replication tasks and certificates
- Each resource gets an ARN of the form `arn:aws:dms:<region>:<account>:<type>:<id>`, where
`<type>` is `endpoint`, `rep` or `task` and `<id>` is 26 characters of the base32
`<type>` is `endpoint`, `rep`, `task` or `cert` and `<id>` is 26 characters of the base32
alphabet, or the request's `ResourceIdentifier` when one is given. Update and delete
calls address the resource by that ARN.
- Identifiers must begin with a letter, contain only ASCII letters, digits and hyphens,
@@ -112,6 +115,17 @@ those subnets actually have. No data is migrated: the resources are control-plan
Stopping a task that is not running returns `InvalidResourceStateFault` with "is
currently not running", the message the Terraform provider treats as already stopped.
Modifying or deleting a running task returns `InvalidResourceStateFault`.
- **Certificates** are imported from `CertificatePem` or `CertificateWallet`; a request with
neither returns `InvalidParameterValueException`. A PEM is parsed as an X.509 certificate,
so `ValidFromDate`, `ValidToDate` and `SigningAlgorithm` are the certificate's own, and
`KeyLength` is reported for an RSA key only, as AWS does. A PEM that holds no certificate,
a blank one included, returns `InvalidCertificateFault`. For a bundle, the first
certificate is the one described. A wallet is stored and returned as sent; given both a
PEM and a wallet, AWS keeps only the PEM, and so does Floci. `CertificateOwner` is the
caller's account. Deleting a certificate that an endpoint's `CertificateArn` names returns
`InvalidResourceStateFault`, and `DeleteCertificate` given anything other than a
certificate ARN returns `InvalidParameterValueException`. These behaviours were checked
against a live AWS account.
- Deleting an endpoint or instance that a task references, or a subnet group that an
instance uses, returns `InvalidResourceStateFault`. A delete returns the resource with
status `deleting`, and it is gone from the next describe.
@@ -122,7 +136,7 @@ those subnets actually have. No data is migrated: the resources are control-plan
the resource's ARN. For a subnet group that is
`arn:aws:dms:<region>:<account>:subgrp:<identifier>`; DMS does not return that ARN from
`DescribeReplicationSubnetGroups`, so Terraform builds it client side and Floci parses it
back the same way. Endpoints, instances and tasks are tagged through the ARN their create
back the same way. Endpoints, instances, tasks and certificates are tagged through the ARN their create
returned.
- `AddTagsToResource` merges by key, so re-tagging an existing key overwrites its value.
@@ -154,7 +168,7 @@ holds, such as the new name a modify gives, is checked on the ARN it would give.
out an optional ARN, such as a `CreateEndpoint` with no `CertificateArn`, names the certificate DMS
uses for one naming none, and DMS has none; a replication instance whose create names no subnet
group is checked on the account's `default` subnet group, which DMS puts it in. A condition on
`aws:ResourceTag` reads the tags of an endpoint, an instance, a task or a subnet group.
`aws:ResourceTag` reads the tags of an endpoint, an instance, a task, a certificate or a subnet group.
## Limitations
@@ -170,9 +184,15 @@ group is checked on the account's `default` subnet group, which DMS puts it in.
`CdcStopPosition` are stored by create and modify, and ignored by `StartReplicationTask`.
- **Not implemented:** `TestConnection`, `DescribeConnections`, `MoveReplicationTask`,
`DescribeEndpointTypes`, `DescribeOrderableReplicationInstances`, replication configs
(`aws_dms_replication_config`, serverless DMS), event subscriptions, certificates and the
(`aws_dms_replication_config`, serverless DMS), event subscriptions and the
`WithoutSettings` flag of `DescribeReplicationTasks`.
- **No `ModifyReplicationSubnetGroup`.** A subnet change has to be a delete and recreate.
- **Certificates are X.509 only.** AWS also accepts a PEM holding an encrypted private key
(`-----BEGIN ENCRYPTED PRIVATE KEY-----`); Floci returns `InvalidCertificateFault` for it.
- **An endpoint's `CertificateArn` is not checked.** AWS rejects a `CreateEndpoint` naming a
certificate that does not exist with `InvalidParameterValueException`; Floci accepts any
value, as it did before certificates could be imported, so existing setups that name a
placeholder ARN keep working.
See the [AWS DMS API Reference](https://docs.aws.amazon.com/dms/latest/APIReference/Welcome.html).
+1 -1
View File
@@ -96,7 +96,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Lake Formation](lakeformation.md) | `POST /<Action>` | REST JSON | 17 |
| [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 |
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 |
| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 |
| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 23 |
| [QuickSight](quicksight.md) | `/accounts/{AwsAccountId}/...` | REST JSON, metadata only | 26 |
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 65 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 |
@@ -91,6 +91,12 @@ public class DmsJsonHandler {
service.startReplicationTask(request, region).getAttributes());
case "StopReplicationTask" -> single("ReplicationTask",
service.stopReplicationTask(request, region).getAttributes());
case "ImportCertificate" -> single("Certificate",
service.importCertificate(request, region).getAttributes());
case "DescribeCertificates" -> page("Certificates",
service.describeCertificates(request, region), DmsResource::getAttributes);
case "DeleteCertificate" -> single("Certificate",
service.deleteCertificate(request, region).getAttributes());
default -> null;
};
}
@@ -26,9 +26,16 @@ import tools.jackson.databind.node.ArrayNode;
import tools.jackson.databind.node.JsonNodeFactory;
import tools.jackson.databind.node.ObjectNode;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
@@ -96,6 +103,7 @@ public class DmsService implements Resettable {
private final Kind endpoints;
private final Kind instances;
private final Kind tasks;
private final Kind certificates;
private final Ec2Service ec2Service;
private final RegionResolver regionResolver;
@@ -125,6 +133,11 @@ public class DmsService implements Resettable {
"migration-type", List.of("MigrationType"),
"endpoint-arn", List.of("SourceEndpointArn", "TargetEndpointArn"),
"replication-instance-arn", List.of("ReplicationInstanceArn")));
this.certificates = new Kind("Certificate",
storageFactory.create("dms", "dms-certificates.json", type),
"cert", "CertificateIdentifier", "CertificateArn", 255, false,
Map.of("certificate-arn", List.of("CertificateArn"),
"certificate-id", List.of("CertificateIdentifier")));
this.ec2Service = ec2Service;
this.regionResolver = regionResolver;
}
@@ -377,6 +390,98 @@ public class DmsService implements Resettable {
return save(found, attributes);
}
// ---------------------------------------------------------------- certificates
/**
* A PEM is parsed as DMS parses it: what it reports comes from the first certificate in the
* file, and a PEM holding none, a blank one included, is {@code InvalidCertificateFault}. A
* wallet is opaque and stored as sent, but only without a PEM: given both, DMS keeps the PEM.
*/
public synchronized DmsResource importCertificate(JsonNode request, String region) {
String identifier = requireResourceIdentifier(certificates, request);
String pem = text(request, "CertificatePem");
String wallet = text(request, "CertificateWallet");
boolean hasPem = pem != null && !pem.isEmpty();
boolean hasWallet = wallet != null && !wallet.isEmpty();
if (!hasPem && !hasWallet) {
throw invalidParameter("Please provide a value for either for CertificatePem or for CertificateWallet.");
}
if (hasWallet) {
try {
Base64.getDecoder().decode(wallet);
} catch (IllegalArgumentException e) {
throw serialization("CertificateWallet must be base64-encoded binary data.");
}
}
ObjectNode attributes = JsonNodeFactory.instance.objectNode();
attributes.put("CertificateCreationDate", now());
attributes.put("CertificateOwner", regionResolver.getAccountId());
if (hasPem) {
attributes.put("CertificatePem", pem);
describeX509(attributes, pem);
} else {
attributes.put("CertificateWallet", wallet);
}
putText(attributes, request, "KmsKeyId");
return create(certificates, region, identifier, attributes, request);
}
public PaginatedResult<DmsResource> describeCertificates(JsonNode request, String region) {
return describe(certificates, request, region, "No Certificates found matching provided filters");
}
/** A value that is not a certificate ARN is a parameter error here, not the not-found other deletes answer. */
public synchronized DmsResource deleteCertificate(JsonNode request, String region) {
String requested = text(request, certificates.arnMember());
if (requested != null && !requested.isBlank() && !isCertificateArn(requested)) {
throw invalidParameter("Invalid value " + requested + " for CertificateArn");
}
Found found;
try {
found = requireByArn(certificates, request, certificates.arnMember(), region);
} catch (AwsException e) {
if ("ResourceNotFoundFault".equals(e.getErrorCode())) {
throw new AwsException("ResourceNotFoundFault", "Certificate for " + requested + " not found.", 400);
}
throw e;
}
String arn = arnOf(certificates, found.resource());
if (regionScan(endpoints, region).stream().anyMatch(endpoint -> arn.equals(member(endpoint, "CertificateArn")))) {
throw invalidState("Certificate " + arn + " is being used for one or more endpoints.");
}
return remove(found);
}
private boolean isCertificateArn(String value) {
try {
AwsArnUtils.Arn arn = AwsArnUtils.parse(value);
return "dms".equals(arn.service()) && arn.resource().startsWith(certificates.arnType() + ":");
} catch (IllegalArgumentException expected) {
// Not an ARN at all, which DMS rejects as an invalid CertificateArn value too.
return false;
}
}
private static void describeX509(ObjectNode attributes, String pem) {
X509Certificate certificate;
try {
certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
.generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));
} catch (CertificateException | ClassCastException e) {
throw new AwsException("InvalidCertificateFault", ".PEM encoded file should be either a valid CA or"
+ " Public Key Certificate or Private Key Certificate", 400);
}
attributes.put("ValidFromDate", EpochSeconds.fromInstant(certificate.getNotBefore().toInstant()));
attributes.put("ValidToDate", EpochSeconds.fromInstant(certificate.getNotAfter().toInstant()));
attributes.put("SigningAlgorithm", certificate.getSigAlgName());
// DMS reports a key length for an RSA key only; an EC certificate has none.
if (certificate.getPublicKey() instanceof RSAPublicKey rsa) {
attributes.put("KeyLength", rsa.getModulus().bitLength());
}
}
// ---------------------------------------------------------------- replication subnet groups
public synchronized ReplicationSubnetGroup createReplicationSubnetGroup(JsonNode request, String region) {
String identifier = requireIdentifier(request);
String description = requireDescription(request);
@@ -455,11 +560,12 @@ public class DmsService implements Resettable {
}
/**
* The ARN of the caller's endpoint, replication instance, replication task or replication subnet group in
* {@code region} that {@code value} names, its identifier or the ARN DMS gave it, read in place; empty for another
* type or a value naming none. An endpoint's, an instance's or a task's ARN ends in the id DMS minted, not in its
* identifier, so a request naming one by its identifier is checked on the ARN this finds; a subnet group's ends in
* its identifier. A resource stored before keys carried the account is the default account's and is found too.
* The ARN of the caller's endpoint, replication instance, replication task, certificate or replication subnet group
* in {@code region} that {@code value} names, its identifier or the ARN DMS gave it, read in place; empty for another
* type or a value naming none. An endpoint's, an instance's, a task's or a certificate's ARN ends in the id DMS
* minted, not in its identifier, so a request naming one by its identifier is checked on the ARN this finds; a
* subnet group's ends in its identifier. A resource stored before keys carried the account is the default
* account's and is found too.
*/
public synchronized Optional<String> storedArn(String type, String value, String region) {
if ("ReplicationSubnetGroup".equals(type)) {
@@ -473,6 +579,7 @@ public class DmsService implements Resettable {
case "Endpoint" -> endpoints;
case "ReplicationInstance" -> instances;
case "ReplicationTask" -> tasks;
case "Certificate" -> certificates;
default -> null;
};
if (kind == null) {
@@ -493,8 +600,8 @@ public class DmsService implements Resettable {
}
/**
* The tags of the endpoint, replication instance, replication task or replication subnet group the ARN names, in
* the account and Region it names, the ones {@code ListTagsForResource} reads, read in place and copied under the
* The tags of the endpoint, replication instance, replication task, certificate or replication subnet group the ARN
* names, in the account and Region it names, the ones {@code ListTagsForResource} reads, read in place and copied under the
* monitor DMS's tag changes hold; empty for an ARN of another account, of a kind DMS holds none of, or naming no
* resource it holds. The lookups the handlers make move a pre-multi-account entry into the caller's account, which
* a read made before the request is allowed must not do.
@@ -515,7 +622,7 @@ public class DmsService implements Resettable {
tags = AccountAwareStorageBackend.readInAccount(subnetGroups, account,
storageKey(region, parsed[1].toLowerCase(Locale.ROOT))).map(ReplicationSubnetGroup::getTags);
} else {
tags = Stream.of(endpoints, instances, tasks).filter(kind -> kind.arnType().equals(parsed[0])).findFirst()
tags = Stream.of(endpoints, instances, tasks, certificates).filter(kind -> kind.arnType().equals(parsed[0])).findFirst()
.flatMap(kind -> AccountAwareStorageBackend.readInAccount(kind.store(), account,
storageKey(region, parsed[1])))
.map(DmsResource::getTags);
@@ -549,6 +656,7 @@ public class DmsService implements Resettable {
endpoints.store().clear();
instances.store().clear();
tasks.store().clear();
certificates.store().clear();
}
// ---------------------------------------------------------------- shared resource plumbing
@@ -596,6 +704,10 @@ public class DmsService implements Resettable {
* treat as gone; an unfiltered describe of nothing is an empty list.
*/
private PaginatedResult<DmsResource> describe(Kind kind, JsonNode request, String region) {
return describe(kind, request, region, "No " + kind.label() + " found matching provided filters.");
}
private PaginatedResult<DmsResource> describe(Kind kind, JsonNode request, String region, String noMatch) {
Integer maxRecords = maxRecords(request);
String marker = text(request, "Marker");
Map<String, List<String>> filters = filters(request, kind.filters().keySet());
@@ -607,8 +719,7 @@ public class DmsService implements Resettable {
.anyMatch(value::equalsIgnoreCase))))
.toList();
if (!filters.isEmpty() && matching.isEmpty()) {
throw new AwsException("ResourceNotFoundFault",
"No " + kind.label() + " found matching provided filters.", 400);
throw new AwsException("ResourceNotFoundFault", noMatch, 400);
}
return Pagination.paginate(matching, resource -> member(resource, kind.idMember()),
maxRecords, marker, DEFAULT_MAX_RECORDS, MAXIMUM_MAX_RECORDS, "InvalidParameterValueException",
@@ -667,7 +778,7 @@ public class DmsService implements Resettable {
}
private Kind kindForArnType(String arnType, String resourceArn) {
for (Kind kind : List.of(endpoints, instances, tasks)) {
for (Kind kind : List.of(endpoints, instances, tasks, certificates)) {
if (kind.arnType().equals(arnType)) {
return kind;
}
@@ -12,7 +12,7 @@ import java.util.Optional;
/**
* What IAM asks DMS of the resources a request names: the tags it keeps on an endpoint, a replication instance, a
* replication task or a replication subnet group, which the request-resources table's resource-tag keys for those types
* replication task, a certificate or a replication subnet group, which the request-resources table's resource-tag keys for those types
* take as their values ({@code aws:ResourceTag/<key>}).
*/
@ApplicationScoped
@@ -33,9 +33,9 @@ public class DmsStoredResourceArns implements StoredResourceArns {
}
/**
* The caller's endpoint, replication instance, replication task or replication subnet group a request names by its
* identifier or its ARN, as DMS stores it: an endpoint's, an instance's or a task's ARN ends in the id DMS minted,
* not in the identifier a request may name it by.
* The caller's endpoint, replication instance, replication task, certificate or replication subnet group a request
* names by its identifier or its ARN, as DMS stores it: an endpoint's, an instance's, a task's or a certificate's ARN
* ends in the id DMS minted, not in the identifier a request may name it by.
*/
@Override
public Optional<String> find(String type, List<String> names, String region) {
@@ -497,6 +497,107 @@ class DmsLifecycleIntegrationTest {
delete("DeleteEndpoint", "EndpointArn", source);
}
@Test
void certificateLifecycleIsReadableThroughDescribe() {
String arn = dms("ImportCertificate")
.body("{\"CertificateIdentifier\":\"lc-cert\",\"CertificatePem\":" + jsonString(DmsTestCertificate.PEM)
+ ",\"Tags\":[{\"Key\":\"env\",\"Value\":\"test\"}]}")
.when().post("/")
.then()
.statusCode(200)
.body("Certificate.CertificateIdentifier", equalTo("lc-cert"))
.body("Certificate.CertificateArn", matchesPattern(
"arn:aws:dms:us-east-1:" + ACCOUNT_ID + ":cert:[A-Z2-7]{26}"))
.body("Certificate.CertificateOwner", equalTo(ACCOUNT_ID))
.body("Certificate.SigningAlgorithm", equalTo(DmsTestCertificate.SIGNING_ALGORITHM))
.body("Certificate.KeyLength", equalTo(DmsTestCertificate.KEY_LENGTH))
.body("Certificate.ValidFromDate", notNullValue())
.body("Certificate.ValidToDate", notNullValue())
.body("Certificate.CertificateCreationDate", notNullValue())
.extract().path("Certificate.CertificateArn");
describe("DescribeCertificates", "certificate-id", "lc-cert")
.body("Certificates", hasSize(1))
.body("Certificates[0].CertificateArn", equalTo(arn))
.body("Certificates[0].CertificatePem", equalTo(DmsTestCertificate.PEM));
describe("DescribeCertificates", "certificate-arn", arn)
.body("Certificates[0].CertificateIdentifier", equalTo("lc-cert"));
dms("ListTagsForResource")
.body("{\"ResourceArn\":\"" + arn + "\"}")
.when().post("/")
.then()
.statusCode(200)
.body("TagList[0].Key", equalTo("env"))
.body("TagList[0].Value", equalTo("test"));
dms("ImportCertificate")
.body("{\"CertificateIdentifier\":\"lc-cert\",\"CertificatePem\":"
+ jsonString(DmsTestCertificate.PEM) + "}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceAlreadyExistsFault"));
String endpoint = createEndpoint("lc-cert-ep", "source", ",\"CertificateArn\":\"" + arn + "\"");
dms("DeleteCertificate")
.body("{\"CertificateArn\":\"" + arn + "\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidResourceStateFault"));
delete("DeleteEndpoint", "EndpointArn", endpoint);
dms("DeleteCertificate")
.body("{\"CertificateArn\":\"" + arn + "\"}")
.when().post("/")
.then()
.statusCode(200)
.body("Certificate.CertificateIdentifier", equalTo("lc-cert"));
dms("DescribeCertificates")
.body("{\"Filters\":[{\"Name\":\"certificate-id\",\"Values\":[\"lc-cert\"]}]}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundFault"));
}
@Test
void certificateWalletIsStoredAsSent() {
String arn = dms("ImportCertificate")
.body("{\"CertificateIdentifier\":\"lc-wallet\",\"CertificateWallet\":\"AQIDBA==\"}")
.when().post("/")
.then()
.statusCode(200)
.body("Certificate.CertificateWallet", equalTo("AQIDBA=="))
.body("Certificate", not(hasKey("CertificatePem")))
.extract().path("Certificate.CertificateArn");
delete("DeleteCertificate", "CertificateArn", arn);
}
@Test
void certificateImportRejectsInvalidInput() {
dms("ImportCertificate")
.body("{\"CertificateIdentifier\":\"lc-bad-pem\",\"CertificatePem\":\"not a certificate\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidCertificateFault"));
dms("ImportCertificate")
.body("{\"CertificateIdentifier\":\"lc-no-content\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
dms("ImportCertificate")
.body("{\"CertificateIdentifier\":\"1-bad\",\"CertificatePem\":"
+ jsonString(DmsTestCertificate.PEM) + "}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
private static String mappings(String schema) {
return "{\"rules\":[{\"rule-type\":\"selection\",\"rule-id\":\"1\",\"rule-name\":\"1\","
+ "\"object-locator\":{\"schema-name\":\"" + schema + "\",\"table-name\":\"%\"},"
@@ -504,7 +605,7 @@ class DmsLifecycleIntegrationTest {
}
private static String jsonString(String value) {
return "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
return "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"";
}
private static String createEndpoint(String identifier, String type, String extraMembers) {
@@ -14,6 +14,7 @@ import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Subnet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.node.ArrayNode;
@@ -772,6 +773,189 @@ class DmsServiceTest {
assertEquals(Map.of(), service.storedTags("not-an-arn"));
}
@Test
void importCertificateReportsWhatThePemHolds() {
ObjectNode request = certificateRequest("ca-bundle");
request.putArray("Tags").addObject().put("Key", "team").put("Value", "data");
ObjectNode imported = service.importCertificate(request, REGION).getAttributes();
assertEquals("ca-bundle", imported.path("CertificateIdentifier").asString());
assertTrue(imported.path("CertificateArn").asString()
.matches("arn:aws:dms:" + REGION + ":" + ACCOUNT_ID + ":cert:[A-Z2-7]{26}"));
assertEquals(ACCOUNT_ID, imported.path("CertificateOwner").asString());
assertEquals(DmsTestCertificate.PEM, imported.path("CertificatePem").asString());
assertEquals(DmsTestCertificate.NOT_BEFORE.getEpochSecond(), imported.path("ValidFromDate").asDouble());
assertEquals(DmsTestCertificate.NOT_AFTER.getEpochSecond(), imported.path("ValidToDate").asDouble());
assertEquals(DmsTestCertificate.SIGNING_ALGORITHM, imported.path("SigningAlgorithm").asString());
assertEquals(DmsTestCertificate.KEY_LENGTH, imported.path("KeyLength").asInt());
assertTrue(imported.path("CertificateCreationDate").isNumber());
assertEquals(Map.of("team", "data"), service.storedTags(imported.path("CertificateArn").asString()));
}
@Test
void importCertificateStoresAWalletAsSent() {
ObjectNode request = mapper.createObjectNode().put("CertificateIdentifier", "oracle-wallet")
.put("CertificateWallet", "AQIDBA==");
ObjectNode imported = service.importCertificate(request, REGION).getAttributes();
assertEquals("AQIDBA==", imported.path("CertificateWallet").asString());
assertTrue(imported.path("CertificatePem").isMissingNode());
assertTrue(imported.path("ValidFromDate").isMissingNode());
}
@Test
void importCertificateReportsNoKeyLengthForAnEcKey() {
ObjectNode imported = service.importCertificate(mapper.createObjectNode()
.put("CertificateIdentifier", "ec-cert").put("CertificatePem", DmsTestCertificate.EC_PEM), REGION)
.getAttributes();
assertEquals(DmsTestCertificate.EC_SIGNING_ALGORITHM, imported.path("SigningAlgorithm").asString());
assertTrue(imported.path("ValidToDate").isNumber());
assertTrue(imported.path("KeyLength").isMissingNode());
}
@Test
void importCertificateDescribesTheFirstCertificateOfABundle() {
ObjectNode imported = service.importCertificate(mapper.createObjectNode()
.put("CertificateIdentifier", "bundle")
.put("CertificatePem", DmsTestCertificate.EC_PEM + DmsTestCertificate.PEM), REGION).getAttributes();
assertEquals(DmsTestCertificate.EC_SIGNING_ALGORITHM, imported.path("SigningAlgorithm").asString());
assertEquals(DmsTestCertificate.EC_PEM + DmsTestCertificate.PEM, imported.path("CertificatePem").asString());
}
@Test
void importCertificateGivenAPemAndAWalletKeepsOnlyThePem() {
ObjectNode imported = service.importCertificate(certificateRequest("pem-and-wallet")
.put("CertificateWallet", "AQIDBA=="), REGION).getAttributes();
assertEquals(DmsTestCertificate.PEM, imported.path("CertificatePem").asString());
assertEquals(DmsTestCertificate.KEY_LENGTH, imported.path("KeyLength").asInt());
assertTrue(imported.path("CertificateWallet").isMissingNode());
}
@Test
void importCertificateRejectsInvalidRequests() {
assertFault("InvalidCertificateFault", () -> service.importCertificate(mapper.createObjectNode()
.put("CertificateIdentifier", "not-x509").put("CertificatePem", "not a certificate"), REGION));
assertFault("InvalidParameterValueException", () -> service.importCertificate(mapper.createObjectNode()
.put("CertificateIdentifier", "no-content"), REGION));
assertFault("InvalidCertificateFault", () -> service.importCertificate(mapper.createObjectNode()
.put("CertificateIdentifier", "blank-pem").put("CertificatePem", " \n"), REGION));
assertFault("SerializationException", () -> service.importCertificate(mapper.createObjectNode()
.put("CertificateIdentifier", "bad-wallet").put("CertificateWallet", "not base64!"), REGION));
assertFault("InvalidParameterValueException",
() -> service.importCertificate(certificateRequest("ends-with-"), REGION));
assertFault("InvalidParameterValueException",
() -> service.importCertificate(certificateRequest("two--hyphens"), REGION));
service.importCertificate(certificateRequest("duplicate"), REGION);
assertFault("ResourceAlreadyExistsFault",
() -> service.importCertificate(certificateRequest("duplicate"), REGION));
}
@Test
void describeCertificatesFiltersByIdentifierAndArn() {
String first = certificateArn(service.importCertificate(certificateRequest("cert-a"), REGION));
service.importCertificate(certificateRequest("cert-b"), REGION);
assertEquals(List.of("cert-a", "cert-b"), certificateIds(mapper.createObjectNode()));
assertEquals(List.of("cert-b"), certificateIds(certificateFilter("certificate-id", "cert-b")));
assertEquals(List.of("cert-a"), certificateIds(certificateFilter("certificate-arn", first)));
assertEquals("No Certificates found matching provided filters", assertFault("ResourceNotFoundFault",
() -> service.describeCertificates(certificateFilter("certificate-id", "cert-c"), REGION))
.getMessage());
assertFault("InvalidParameterValueException",
() -> service.describeCertificates(certificateFilter("certificate-owner", ACCOUNT_ID), REGION));
assertEquals(List.of(), service.describeCertificates(mapper.createObjectNode(), "eu-west-1").items());
}
@Test
void deleteCertificateRefusesOneAnEndpointUses() {
String arn = certificateArn(service.importCertificate(certificateRequest("in-use"), REGION));
String endpoint = service.createEndpoint(mapper.createObjectNode().put("EndpointIdentifier", "docdb-target")
.put("EndpointType", "target").put("EngineName", "docdb").put("CertificateArn", arn), REGION)
.getAttributes().path("EndpointArn").asString();
ObjectNode delete = mapper.createObjectNode().put("CertificateArn", arn);
assertFault("InvalidResourceStateFault", () -> service.deleteCertificate(delete, REGION));
service.deleteEndpoint(mapper.createObjectNode().put("EndpointArn", endpoint), REGION);
assertEquals("in-use", service.deleteCertificate(delete, REGION).getAttributes()
.path("CertificateIdentifier").asString());
assertEquals(List.of(), service.describeCertificates(mapper.createObjectNode(), REGION).items());
assertEquals(Map.of(), service.storedTags(arn));
assertEquals("Certificate for " + arn + " not found.",
assertFault("ResourceNotFoundFault", () -> service.deleteCertificate(delete, REGION)).getMessage());
}
@Test
void certificateNotFoundMessagesLeaveOtherKindsUnchanged() {
ObjectNode filter = mapper.createObjectNode();
filter.putArray("Filters").addObject().put("Name", "endpoint-id").putArray("Values").add("missing");
assertEquals("No Endpoint found matching provided filters.", assertFault("ResourceNotFoundFault",
() -> service.describeEndpoints(filter, REGION)).getMessage());
String missing = "arn:aws:dms:" + REGION + ":" + ACCOUNT_ID + ":endpoint:MISSING";
assertEquals("Resource " + missing + " not found.", assertFault("ResourceNotFoundFault",
() -> service.deleteEndpoint(mapper.createObjectNode().put("EndpointArn", missing), REGION))
.getMessage());
}
@Test
void deleteCertificateRejectsAnArnOfAnotherKind() {
String endpoint = service.createEndpoint(mapper.createObjectNode().put("EndpointIdentifier", "src")
.put("EndpointType", "source").put("EngineName", "mysql"), REGION)
.getAttributes().path("EndpointArn").asString();
assertFault("InvalidParameterValueException", () -> service.deleteCertificate(
mapper.createObjectNode().put("CertificateArn", endpoint), REGION));
assertFault("InvalidParameterValueException", () -> service.deleteCertificate(
mapper.createObjectNode().put("CertificateArn", "not-an-arn"), REGION));
assertFault("InvalidParameterValueException",
() -> service.deleteCertificate(mapper.createObjectNode(), REGION));
}
@Test
void storedArnFindsACertificateByItsIdentifierOrItsArn() {
String arn = certificateArn(service.importCertificate(certificateRequest("iam-cert"), REGION));
assertEquals(Optional.of(arn), service.storedArn("Certificate", "iam-cert", REGION));
assertEquals(Optional.of(arn), service.storedArn("Certificate", arn, REGION));
assertEquals(Optional.empty(), service.storedArn("Certificate", "iam-cert", "eu-west-1"));
assertEquals(Optional.empty(), service.storedArn("Endpoint", "iam-cert", REGION));
}
private ObjectNode certificateRequest(String identifier) {
return mapper.createObjectNode().put("CertificateIdentifier", identifier)
.put("CertificatePem", DmsTestCertificate.PEM);
}
private ObjectNode certificateFilter(String name, String value) {
ObjectNode request = mapper.createObjectNode();
ObjectNode filter = request.putArray("Filters").addObject().put("Name", name);
filter.putArray("Values").add(value);
return request;
}
private List<String> certificateIds(ObjectNode request) {
return service.describeCertificates(request, REGION).items().stream()
.map(certificate -> certificate.getAttributes().path("CertificateIdentifier").asString())
.toList();
}
private static String certificateArn(DmsResource certificate) {
return certificate.getAttributes().path("CertificateArn").asString();
}
private static AwsException assertFault(String code, Executable call) {
AwsException fault = assertThrows(AwsException.class, call);
assertEquals(code, fault.getErrorCode());
return fault;
}
/**
* An endpoint stored before keys carried the account is the default account's: IAM finds it under its identifier,
* as the handlers load it, and leaves it under its key.
@@ -0,0 +1,49 @@
package io.floci.aws.services.dms;
import java.time.Instant;
/** Self-signed X.509 certificates the DMS tests import, and what DMS reports for them. */
final class DmsTestCertificate {
/** A self-signed RSA 2048 / SHA-256 certificate. */
static final String PEM = String.join("\n",
"-----BEGIN CERTIFICATE-----",
"MIIC9DCCAdygAwIBAgIUfzabzD8tJ09yniczWJ44kUZYWkAwDQYJKoZIhvcNAQEL",
"BQAwGTEXMBUGA1UEAwwOZmxvY2ktZG1zLXRlc3QwIBcNMjYxMjA0MDk1MjQ4WhgP",
"MjEyNjExMTAwOTUyNDhaMBkxFzAVBgNVBAMMDmZsb2NpLWRtcy10ZXN0MIIBIjAN",
"BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwEHVZstYNZkxX7NTJlTVtN2nW+zH",
"JVBBatmvj1zTABrltJze1Ue1qSkWQt1Tr2+YAxM74cGj4x+f8DVjCjv1apWylaZw",
"rVrTSly7SNC0LUXcj1GBmyblNHlQADrgMN8gG0hvjcr3cTlBgofNVAcMjWozCr0B",
"DCH5mS0lYK+Ue8F96xgkhuIIMD23G/eK9iFi6Iglq9y7kmLx/51Qq8dX0v7KmSWe",
"fUjfvZYUfTe+1wheE0w7DqxOx7NxmtwbpdMV8MauHD8mJpOBTIb/Se684POwm2n+",
"bKUe0fFtolePb84p5E5ygFokpavBJvFYZkNGwST9GQjBmTHuhh1jXG2pUQIDAQAB",
"ozIwMDAdBgNVHQ4EFgQUxsp1n5i+NT4QZYrTjvM/i97p+qswDwYDVR0TAQH/BAUw",
"AwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAG9zQOyfzKTQe8JhySyrVleUdtiIcwwfL",
"92DVu0HPciz5stlULtPuc40Y2kpIwWjCkFA+gP26W/h9tEYL0nMoKEYoD8Rnxuw+",
"8GXZrMI2cGYTXuberP5vTnRmcUUuyjVx4Ewd0FhZKFl9tlkdDUWAfyG0nN1b8yGC",
"TDohLdOgEQBkpvwwhi/liTJZgGd2IDums1E2wkgvOnYWxAZwVzECFbLJPrRvhCfu",
"eJEDR/wl9qt+TI8+F3R+6WOqdlG1gy8gEtxH/q2Gpii/6oM1sig8Q/XUlKIdEQ9T",
"WjMC6tpZFTPj5/7onCJQx/lu6aM5rGd8w+5yDDXlRJok3kXIHzBLMw==",
"-----END CERTIFICATE-----") + "\n";
static final Instant NOT_BEFORE = Instant.parse("2026-12-04T09:52:48Z");
static final Instant NOT_AFTER = Instant.parse("2126-11-10T09:52:48Z");
static final String SIGNING_ALGORITHM = "SHA256withRSA";
static final int KEY_LENGTH = 2048;
/** A self-signed EC P-256 / SHA-256 certificate: DMS reports no key length for an EC key. */
static final String EC_PEM = String.join("\n",
"-----BEGIN CERTIFICATE-----",
"MIIBbjCCARSgAwIBAgIUA/SuCpO79dm2jSdeejhMwB0ae28wCgYIKoZIzj0EAwIw",
"HDEaMBgGA1UEAwwRZmxvY2ktZG1zLXRlc3QtZWMwIBcNMjYxMjA0MTE1OTQxWhgP",
"MjEyNjExMTAxMTU5NDFaMBwxGjAYBgNVBAMMEWZsb2NpLWRtcy10ZXN0LWVjMFkw",
"EwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEs07ubTh6WSQILE68ZxKdxMUUb9R4l45N",
"ngvFH8QbDVP+Tpf2uTTY5zeUxAs6HQwa8V3mt46VI+a87qV/mvYbhKMyMDAwHQYD",
"VR0OBBYEFOSC6l2SekyPVtjmNCJAV0/EMdACMA8GA1UdEwEB/wQFMAMBAf8wCgYI",
"KoZIzj0EAwIDSAAwRQIgCI9CgjzQTp0c0VjHSUKVcfq9drcGZRAuCr7SYGzwLj8C",
"IQDaB+8eH1w9kLjOiXCwc4k+2pFTFR5wugaQ66PiW9ijUA==",
"-----END CERTIFICATE-----") + "\n";
static final String EC_SIGNING_ALGORITHM = "SHA256withECDSA";
private DmsTestCertificate() {
}
}