feat(rds): DescribeCertificates, ModifyCertificates and an instance's CA certificate (#6106)

* feat(rds): DescribeCertificates, ModifyCertificates and an instance's CA certificate

DescribeCertificates lists the Region's RDS certificate authorities with the
thumbprint and validity AWS reports, vendored from the certificate bundles AWS
publishes by tools/aws/regen_rds_ca_certificates.py, and pages them.
ModifyCertificates sets or removes the account's default for new instances.
CreateDBInstance, ModifyDBInstance, the two instance restores and
CreateDBInstanceReadReplica take CACertificateIdentifier, and instances report
it with CertificateDetails. AWS::RDS::DBInstance takes the property and
resolves the two CertificateDetails attributes. The identifier is metadata:
the auth proxy keeps presenting Floci's own CA.

Closes #5806

* fix(rds): follow the user guide on CAs and leave a blank CA alone

- An instance stored without a CA reports rds-ca-rsa2048-g1, since an
  override applies only to instances created after it.
- ap-south-1, ap-southeast-4, ca-west-1, eu-central-2, eu-south-2 and
  il-central-1 offer only rds-ca-rsa2048-g1, as the user guide says.
- A blank CACertificateIdentifier on modify leaves the instance's CA.
- --download skips a Region only on 403 or 404 and exits 1 on other
  failures.
- Reuse regionFromArn, add a createDbInstance stub helper and import
  Executable in the tests.
This commit is contained in:
David authored and GitHub committed 2026-10-26 09:29:56 -04:00
1 parent 3438a00daf
commit ec21cf38c7
21 files changed
+1917 -54

No files matched your search

+9
View File
@@ -25,6 +25,8 @@
# by tools/aws/regen_ecs_shapes.py.
# src/main/resources/aws/ecr-request-shapes.json, the ECR request constraints, is generated
# from botocore's ECR model by tools/aws/regen_ecr_shapes.py.
# src/main/resources/aws/rds-ca-certificates.json, each Region's RDS certificate authorities, is
# generated from the certificate bundles AWS publishes by tools/aws/regen_rds_ca_certificates.py.
# src/main/resources/aws/iam-request-shapes.json, the IAM request constraints of the operations
# read from the model, is generated from botocore's IAM model by tools/aws/regen_iam_shapes.py.
# src/main/resources/aws/emr-serverless-shapes.json, the shapes the Step Functions emr-serverless
@@ -228,6 +230,7 @@ slr-test: ## Run the service-linked role tooling's unit tests
aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-policy catalog from local/aws (commit the result)
$(PYTHON) tools/aws/regen_partitions.py
$(PYTHON) tools/aws/regen_region_facts.py
$(PYTHON) tools/aws/regen_rds_ca_certificates.py
$(PYTHON) tools/aws/regen_dynamodb_shapes.py
$(PYTHON) tools/aws/regen_redshift_serverless_shapes.py
$(PYTHON) tools/aws/regen_resource_groups_shapes.py
@@ -255,6 +258,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
echo " Run 'make aws-data-sync' with local/aws checked out and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_rds_ca_certificates.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/rds-ca-certificates.json is out of date or malformed."; \
echo " Run 'tools/aws/regen_rds_ca_certificates.py --download', then 'make aws-data-sync', and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_dynamodb_shapes.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/dynamodb-request-shapes.json is out of date."; \
@@ -385,6 +385,38 @@ teardown() {
assert_output --partial 'true'
}
@test "rds: certificates list, an override applies to a new instance and is removed" {
run aws_cmd rds describe-certificates --certificate-identifier rds-ca-rsa2048-g1
assert_success
[ "$(json_get "$output" '.Certificates[0].CertificateType')" = "CA" ]
[ "$(json_get "$output" '.DefaultCertificateForNewLaunches')" = "rds-ca-rsa2048-g1" ]
run aws_cmd rds modify-certificates --certificate-identifier rds-ca-ecc384-g1
assert_success
[ "$(json_get "$output" '.Certificate.CustomerOverride')" = "true" ]
run aws_cmd rds create-db-instance --db-instance-identifier "$DB_ID" --engine postgres \
--db-instance-class db.t3.micro --allocated-storage 10
status_create=$status
create_output=$output
run aws_cmd rds modify-certificates --remove-customer-override
assert_success
[ "$status_create" -eq 0 ]
[ "$(json_get "$create_output" '.DBInstance.CACertificateIdentifier')" = "rds-ca-ecc384-g1" ]
run aws_cmd rds modify-db-instance --db-instance-identifier "$DB_ID" \
--ca-certificate-identifier rds-ca-rsa4096-g1 --apply-immediately
assert_success
run aws_cmd rds describe-db-instances --db-instance-identifier "$DB_ID" \
--query 'DBInstances[0].CertificateDetails.CAIdentifier' --output text
assert_success
assert_output 'rds-ca-rsa4096-g1'
run aws_cmd rds describe-certificates --certificate-identifier rds-ca-2019
assert_failure
assert_output --partial 'CertificateNotFound'
}
@test "rds: a KmsKeyId that names no key is refused as on AWS" {
run aws_cmd rds create-db-instance \
--db-instance-identifier "$DB_ID" \
@@ -10,6 +10,8 @@ import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeSubnetsResponse;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.Certificate;
import software.amazon.awssdk.services.rds.model.CertificateNotFoundException;
import software.amazon.awssdk.services.rds.model.ConnectionPoolConfigurationInfo;
import software.amazon.awssdk.services.rds.model.CreateDbClusterEndpointResponse;
import software.amazon.awssdk.services.rds.model.CreateDbClusterResponse;
@@ -40,6 +42,7 @@ import software.amazon.awssdk.services.rds.model.DbLogFileNotFoundException;
import software.amazon.awssdk.services.rds.model.DbProxyEndpointNotFoundException;
import software.amazon.awssdk.services.rds.model.DbSnapshotAlreadyExistsException;
import software.amazon.awssdk.services.rds.model.DbSnapshotNotFoundException;
import software.amazon.awssdk.services.rds.model.DescribeCertificatesResponse;
import software.amazon.awssdk.services.rds.model.DescribeDBLogFilesDetails;
import software.amazon.awssdk.services.rds.model.DescribeDbProxiesResponse;
import software.amazon.awssdk.services.rds.model.DescribeDbProxyEndpointsResponse;
@@ -877,6 +880,45 @@ class RdsControlPlaneTest {
}
}
@Test
@DisplayName("Certificates: list the CAs, override the default and set an instance's CA")
void sdkRoundTripsCertificates() {
String instanceName = TestFixtures.uniqueName("rds-ca");
try {
DescribeCertificatesResponse listed = rds.describeCertificates(b -> {});
assertThat(listed.defaultCertificateForNewLaunches()).isEqualTo("rds-ca-rsa2048-g1");
assertThat(listed.certificates()).extracting(Certificate::certificateIdentifier)
.containsExactly("rds-ca-ecc384-g1", "rds-ca-rsa2048-g1", "rds-ca-rsa4096-g1");
assertThat(listed.certificates()).allSatisfy(c -> {
assertThat(c.certificateType()).isEqualTo("CA");
assertThat(c.thumbprint()).matches("[0-9a-f]{40}");
assertThat(c.validTill()).isAfter(c.validFrom());
assertThat(c.certificateArn()).endsWith("::cert:" + c.certificateIdentifier());
});
assertThatThrownBy(() -> rds.describeCertificates(b -> b.certificateIdentifier("rds-ca-2019")))
.isInstanceOf(CertificateNotFoundException.class);
Certificate override = rds.modifyCertificates(b -> b.certificateIdentifier("rds-ca-ecc384-g1"))
.certificate();
assertThat(override.customerOverride()).isTrue();
assertThat(override.customerOverrideValidTill()).isEqualTo(override.validTill());
DBInstance created = createDbInstance(rds, instanceName, "ca-secret").dbInstance();
assertThat(created.caCertificateIdentifier()).isEqualTo("rds-ca-ecc384-g1");
assertThat(created.certificateDetails().caIdentifier()).isEqualTo("rds-ca-ecc384-g1");
assertThat(created.certificateDetails().validTill()).isEqualTo(override.validTill());
rds.modifyDBInstance(b -> b.dbInstanceIdentifier(instanceName)
.caCertificateIdentifier("rds-ca-rsa4096-g1").applyImmediately(true));
assertThat(rds.describeDBInstances(b -> b.dbInstanceIdentifier(instanceName)).dbInstances().get(0)
.caCertificateIdentifier()).isEqualTo("rds-ca-rsa4096-g1");
} finally {
rds.modifyCertificates(b -> b.removeCustomerOverride(true));
deleteDbInstance(rds, instanceName);
}
assertThat(rds.describeCertificates(b -> {}).defaultCertificateForNewLaunches())
.isEqualTo("rds-ca-rsa2048-g1");
}
@Test
@DisplayName("IAM role associations: add, describe and remove for a cluster and an instance")
void sdkRoundTripsIamRoleAssociations() {
+1 -1
View File
@@ -64,7 +64,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 32 |
| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 |
| [Aurora DSQL](dsql.md) | `/cluster`, `/cluster/{identifier}`, `/cluster/{identifier}/policy` + TLS endpoint | REST JSON + wire | 9 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 109 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 111 |
| [RDS Data API](rds-data.md) | `/Execute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 4 |
| [Timestream for InfluxDB](timestream-influxdb.md) | `POST /` + `X-Amz-Target: AmazonTimestreamInfluxDB.*` + InfluxDB container | JSON 1.0 + InfluxDB HTTP | 24 |
| [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 8 |
+37
View File
@@ -69,6 +69,8 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou
| `DescribeValidDBInstanceModifications` | Return the storage an instance can move to: its type and the sizes a modify stores as asked |
| `DescribeOrderableDBInstanceOptions` | List the orderable engine, version and instance class combinations from the engine catalogue; see [Engine catalogue](#engine-catalogue) |
| `DescribeEvents` | - |
| `DescribeCertificates` | List the Region's RDS certificate authorities and the one new instances get; see [Certificate authorities](#certificate-authorities) |
| `ModifyCertificates` | Set or remove the account's default certificate authority for new instances |
| `CreateEventSubscription` | Create an event notification subscription (stored, nothing is published) |
| `DescribeEventSubscriptions` | List subscriptions, or the one the request names |
| `ModifyEventSubscription` | Update the members the request names |
@@ -1005,6 +1007,41 @@ connecting with a token is not yet emulated for MySQL: unlike PostgreSQL, which
password in cleartext, MySQL sends a scramble, so the proxy would have to drive the
`mysql_clear_password` auth switch that real RDS triggers before it could see a token to validate.
## Certificate authorities
`DescribeCertificates` lists the Region's RDS certificate authorities, `rds-ca-rsa2048-g1`,
`rds-ca-rsa4096-g1` and `rds-ca-ecc384-g1`, with the thumbprint and validity AWS reports. They are
vendored from the certificate bundles AWS publishes for each Region of the `aws` partition by
`tools/aws/regen_rds_ca_certificates.py`. As the user guide says, ap-south-1, ap-southeast-4,
ca-west-1, eu-central-2, eu-south-2 and il-central-1 offer only `rds-ca-rsa2048-g1`, though their
bundles carry all three. A Region with no vendored entry, such as a GovCloud, China or custom one,
reports us-east-1's certificates under its own ARN.
- `CertificateIdentifier` filters, without regard to case, and an unknown one is
`CertificateNotFound`. `MaxRecords` (20 to 100) and `Marker` page the list. `Filters` is not taken,
since the API reference says it isn't supported.
- `DefaultCertificateForNewLaunches` is `rds-ca-rsa2048-g1` until `ModifyCertificates` sets an
override for the account and Region. The overriding certificate then reports `CustomerOverride`
true and its `CustomerOverrideValidTill`. `RemoveCustomerOverride` puts RDS's default back.
Sending both members, or neither, is `InvalidParameterCombination`. AWS doesn't document what it does here, so
this behavior is a guess.
- `CreateDBInstance`, `RestoreDBInstanceFromDBSnapshot`, `RestoreDBInstanceToPointInTime`,
`CreateDBInstanceReadReplica` and `ModifyDBInstance` take `CACertificateIdentifier`. An instance
given none gets the account's default when it is created. An unknown identifier is
`CertificateNotFound`. A modify changes it at once, as Floci applies every modification
immediately, and a blank value leaves it as it was. `CertificateRotationRestart` is accepted and
has no effect.
- Instances report `CACertificateIdentifier` and `CertificateDetails` (`CAIdentifier`, with the
CA's `ValidTill`, as Floci keeps no per-instance server certificate). An instance stored before
this was recorded reports `rds-ca-rsa2048-g1`, since an override applies only to instances
created after it. `AWS::RDS::DBInstance` takes
`CACertificateIdentifier` and resolves `CertificateDetails.CAIdentifier` and
`CertificateDetails.ValidTill` in `Fn::GetAtt`.
The identifier is metadata: the auth proxy presents a certificate from Floci's own CA whatever
the instance names, so clients trust Floci's CA (see [TLS / SSL](#tls-ssl)), not AWS's bundle.
Multi-AZ DB clusters do not take `CACertificateIdentifier` yet.
## TLS / SSL
The RDS auth proxy terminates TLS itself (the backend container stays plaintext). It presents
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings;
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbProxy;
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
@@ -349,12 +350,15 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
}
DbInstance instance = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbInstance);
boolean created = instance == null;
String caCertificate = resolveOptional(props, "CACertificateIdentifier", engine);
if (instance != null) {
// A null region keeps the default-region lookup sameNameExistingResource made.
instance = rdsService.modifyDbInstance(
id,
resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true),
parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine),
resolveOptional(props, "DBSubnetGroupName", engine));
resolveOptional(props, "DBSubnetGroupName", engine), null, null, null, null,
DbInstanceSettings.unchanged().withCaCertificateIdentifier(caCertificate));
} else {
instance = rdsService.createDbInstance(
id,
@@ -369,7 +373,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
resolveOptional(props, "DBParameterGroupName", engine),
resolveOptional(props, "DBSubnetGroupName", engine),
resolveOptional(props, "DBClusterIdentifier", engine),
null, false, false, null, Map.of(), region);
null, false, false, null, Map.of(), List.of(), null, region, true,
DbInstanceSettings.defaults().withCaCertificateIdentifier(caCertificate));
}
// The roles go on before a renamed instance's predecessor is deleted, so a refused list
// deletes only the new instance and the stack still has the old one to roll back to.
@@ -389,6 +394,11 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
if (instance.getDbiResourceId() != null) {
r.getAttributes().put("DbiResourceId", instance.getDbiResourceId());
}
RdsService.InstanceCertificate ca = rdsService.instanceCertificate(instance);
r.getAttributes().put("CertificateDetails.CAIdentifier", ca.caIdentifier());
if (ca.validTill() != null) {
r.getAttributes().put("CertificateDetails.ValidTill", ca.validTill().toString());
}
}
/**
@@ -0,0 +1,64 @@
package io.github.hectorvent.floci.services.rds;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.VendoredResources;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Each Region's RDS certificate authorities as {@code DescribeCertificates} reports them, vendored in
* {@code aws/rds-ca-certificates.json} by {@code tools/aws/regen_rds_ca_certificates.py} from the
* certificate bundles AWS publishes. A Region with no vendored entry, such as a custom one, uses
* us-east-1's.
*/
final class RdsCaCertificates {
/** The CA AWS gives a new instance when the account sets no override. */
static final String DEFAULT_FOR_NEW_LAUNCHES = "rds-ca-rsa2048-g1";
// The vendored file always has this entry (parse refuses one without it).
private static final String FALLBACK_REGION = "us-east-1"; // partition-literal: a key into the vendored data
private static final Map<String, List<CaCertificate>> BY_REGION = VendoredResources.read(
"aws/rds-ca-certificates.json", "RDS CA certificates", in -> parse(new ObjectMapper().readTree(in)));
record CaCertificate(String identifier, String thumbprint, Instant validFrom, Instant validTill) {}
private RdsCaCertificates() {
}
/** The Region's CAs in identifier order. */
static List<CaCertificate> forRegion(String region) {
List<CaCertificate> certificates = BY_REGION.get(region);
return certificates != null ? certificates : BY_REGION.get(FALLBACK_REGION);
}
/** The Region's CA named {@code identifier}, which AWS matches without regard to case. */
static Optional<CaCertificate> find(String region, String identifier) {
return forRegion(region).stream()
.filter(certificate -> certificate.identifier().equalsIgnoreCase(identifier))
.findFirst();
}
private static Map<String, List<CaCertificate>> parse(JsonNode doc) {
Map<String, List<CaCertificate>> byRegion = new LinkedHashMap<>();
for (Map.Entry<String, JsonNode> region : doc.path("regions").properties()) {
List<CaCertificate> certificates = new ArrayList<>();
for (JsonNode certificate : region.getValue()) {
certificates.add(new CaCertificate(certificate.path("certificateIdentifier").asText(),
certificate.path("thumbprint").asText(),
Instant.parse(certificate.path("validFrom").asText()),
Instant.parse(certificate.path("validTill").asText())));
}
byRegion.put(region.getKey(), List.copyOf(certificates));
}
if (!byRegion.containsKey(FALLBACK_REGION)) {
throw new IllegalStateException("aws/rds-ca-certificates.json has no " + FALLBACK_REGION + " entry");
}
return Map.copyOf(byRegion);
}
}
@@ -111,6 +111,8 @@ public class RdsQueryHandler {
case "DescribeValidDBInstanceModifications" -> handleDescribeValidDbInstanceModifications(params, region);
case "DescribeOrderableDBInstanceOptions" -> handleDescribeOrderableDbInstanceOptions(params);
case "DescribeEvents" -> handleDescribeEvents(params, region);
case "DescribeCertificates" -> handleDescribeCertificates(params, region);
case "ModifyCertificates" -> handleModifyCertificates(params, region);
case "CreateEventSubscription" -> handleCreateEventSubscription(params, region);
case "DescribeEventSubscriptions" -> handleDescribeEventSubscriptions(params, region);
case "ModifyEventSubscription" -> handleModifyEventSubscription(params, region);
@@ -624,6 +626,45 @@ public class RdsQueryHandler {
return xml.end("EventSubscription").build();
}
private Response handleDescribeCertificates(MultivaluedMap<String, String> params, String region) {
RdsService.CertificatePage page = service.describeCertificates(region, params.getFirst("CertificateIdentifier"),
parseOptionalInt(params.getFirst("MaxRecords")), params.getFirst("Marker"));
XmlBuilder xml = new XmlBuilder()
.elem("DefaultCertificateForNewLaunches", page.defaultForNewLaunches())
.start("Certificates");
for (RdsService.Certificate certificate : page.certificates()) {
certificateXml(xml, certificate);
}
xml.end("Certificates");
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("DescribeCertificates", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleModifyCertificates(MultivaluedMap<String, String> params, String region) {
RdsService.Certificate certificate = service.modifyCertificates(region,
params.getFirst("CertificateIdentifier"), parseOptionalBoolean(params, "RemoveCustomerOverride"));
XmlBuilder xml = new XmlBuilder();
certificateXml(xml, certificate);
return Response.ok(AwsQueryResponse.envelope("ModifyCertificates", AwsNamespaces.RDS, xml.build())).build();
}
private static void certificateXml(XmlBuilder xml, RdsService.Certificate certificate) {
xml.start("Certificate")
.elem("CertificateIdentifier", certificate.certificateIdentifier())
.elem("CertificateType", "CA")
.elem("Thumbprint", certificate.thumbprint())
.elem("ValidFrom", certificate.validFrom().toString())
.elem("ValidTill", certificate.validTill().toString())
.elem("CertificateArn", certificate.certificateArn())
.elem("CustomerOverride", certificate.customerOverride());
if (certificate.customerOverrideValidTill() != null) {
xml.elem("CustomerOverrideValidTill", certificate.customerOverrideValidTill().toString());
}
xml.end("Certificate");
}
private Response handleDescribeEvents(MultivaluedMap<String, String> params, String region) {
String sourceIdentifier = params.getFirst("SourceIdentifier");
String sourceType = params.getFirst("SourceType");
@@ -812,7 +853,8 @@ public class RdsQueryHandler {
includeEncryption ? cloudwatchLogsExports(params) : null,
includeEncryption ? null : cloudwatchLogsExportChanges(params),
optionalInt(params.getFirst("MaxAllocatedStorage")),
params.getFirst("StorageType"));
params.getFirst("StorageType"),
params.getFirst("CACertificateIdentifier"));
}
/**
@@ -1175,7 +1217,7 @@ public class RdsQueryHandler {
parseOptionalBoolean(params, "EnableIAMDatabaseAuthentication"),
optionalInt(params.getFirst("AllocatedStorage")),
params.getFirst("ReplicaMode"),
parseTags(params), params.getFirst("StorageType"));
parseTags(params), params.getFirst("StorageType"), params.getFirst("CACertificateIdentifier"));
DbInstance replica = service.createDbInstanceReadReplica(request, region);
return Response.ok(AwsQueryResponse.envelope(
"CreateDBInstanceReadReplica", AwsNamespaces.RDS, dbInstanceXml(replica))).build();
@@ -1991,7 +2033,8 @@ public class RdsQueryHandler {
DbInstance instance = service.restoreDbInstanceFromDbSnapshot(instanceId, snapshotId,
dbInstanceClass, availabilityZone, multiAz, dbSubnetGroupName,
vpcSecurityGroupIds, tags, region, requestedPort,
parseOptionalBoolean(params, "EnableIAMDatabaseAuthentication"), params.getFirst("StorageType"));
parseOptionalBoolean(params, "EnableIAMDatabaseAuthentication"), params.getFirst("StorageType"),
params.getFirst("CACertificateIdentifier"));
String result = dbInstanceXml(instance);
return Response.ok(AwsQueryResponse.envelope("RestoreDBInstanceFromDBSnapshot", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -2770,7 +2813,7 @@ public class RdsQueryHandler {
parseIntegerParam(params, "BackupRetentionPeriod"),
params.getFirst("PreferredBackupWindow"),
parseOptionalBoolean(params, "DeletionProtection"),
parseTags(params), params.getFirst("StorageType"));
parseTags(params), params.getFirst("StorageType"), params.getFirst("CACertificateIdentifier"));
DbInstance instance = service.restoreDbInstanceToPointInTime(request, region);
return Response.ok(AwsQueryResponse.envelope(
"RestoreDBInstanceToPointInTime", AwsNamespaces.RDS, dbInstanceXml(instance))).build();
@@ -2963,6 +3006,13 @@ public class RdsQueryHandler {
.elem("Port", ep.port())
.end("Endpoint");
}
RdsService.InstanceCertificate ca = service.instanceCertificate(i);
xml.elem("CACertificateIdentifier", ca.caIdentifier())
.start("CertificateDetails").elem("CAIdentifier", ca.caIdentifier());
if (ca.validTill() != null) {
xml.elem("ValidTill", ca.validTill().toString());
}
xml.end("CertificateDetails");
xml.elem("IAMDatabaseAuthenticationEnabled", i.isIamDatabaseAuthenticationEnabled())
.elem("MultiAZ", i.isMultiAz())
.elem("AutoMinorVersionUpgrade", i.isAutoMinorVersionUpgrade())
@@ -183,6 +183,8 @@ public class RdsService implements Resettable, ResourceProvider {
private StorageBackend<String, RdsEvent> events = new InMemoryStorage<>();
private final StorageBackend<String, EventSubscription> eventSubscriptions;
private final StorageBackend<String, DbClusterEndpoint> clusterEndpoints;
/** The account's ModifyCertificates override per Region, by CA identifier. */
private final StorageBackend<String, String> certificateOverrides;
private final StorageBackend<String, DbProxyEndpoint> proxyEndpoints;
private final RdsContainerManager containerManager;
private final RdsProxyManager proxyManager;
@@ -285,6 +287,8 @@ public class RdsService implements Resettable, ResourceProvider {
new TypeReference<Map<String, String>>() {});
this.events = storageFactory.create("rds", "rds-events.json",
new TypeReference<Map<String, RdsEvent>>() {});
this.certificateOverrides = storageFactory.create("rds", "rds-certificate-overrides.json",
new TypeReference<Map<String, String>>() {});
}
RdsService(RdsContainerManager containerManager,
@@ -422,6 +426,7 @@ public class RdsService implements Resettable, ResourceProvider {
this.clusterSnapshots = new InMemoryStorage<>();
this.snapshotData = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
this.eventSubscriptions = new InMemoryStorage<>();
this.certificateOverrides = new InMemoryStorage<>();
this.clusterEndpoints = new InMemoryStorage<>();
this.proxyEndpoints = new InMemoryStorage<>();
}
@@ -743,6 +748,8 @@ public class RdsService implements Resettable, ResourceProvider {
}
DbInstanceSettings.validateMonitoringPairOnCreate(
settings.monitoringInterval(), settings.monitoringRoleArn());
resolvedSettings = resolvedSettings.withCaCertificateIdentifier(
resolveCaCertificate(settings.caCertificateIdentifier(), effectiveRegion));
boolean mock = config.services().rds().mock();
if (masterUsername == null || masterUsername.isBlank()) {
masterUsername = "root";
@@ -1247,6 +1254,17 @@ public class RdsService implements Resettable, ResourceProvider {
List<String> vpcSecurityGroupIds,
Map<String, String> tags, String region,
Integer requestedPort, Boolean iamEnabled, String storageType) {
return restoreDbInstanceFromDbSnapshot(instanceId, snapshotId, dbInstanceClass, availabilityZone,
multiAz, dbSubnetGroupName, vpcSecurityGroupIds, tags, region, requestedPort, iamEnabled,
storageType, null);
}
public DbInstance restoreDbInstanceFromDbSnapshot(String instanceId, String snapshotId, String dbInstanceClass,
String availabilityZone, boolean multiAz, String dbSubnetGroupName,
List<String> vpcSecurityGroupIds,
Map<String, String> tags, String region,
Integer requestedPort, Boolean iamEnabled, String storageType,
String caCertificateIdentifier) {
String effectiveRegion = effectiveRegion(region);
DbSnapshot snapshot = Optional.ofNullable(findSnapshotForScope(currentAccountId(), effectiveRegion, snapshotId))
.orElseThrow(() -> new AwsException("DBSnapshotNotFound", "DBSnapshot " + snapshotId + " not found.", 404));
@@ -1261,7 +1279,8 @@ public class RdsService implements Resettable, ResourceProvider {
// Use the parameters from the snapshot
DbInstanceSettings restoreSettings = new DbInstanceSettings(
snapshot.isStorageEncrypted(), snapshot.getKmsKeyId(), null, null, null, null)
.withStorageType(storageType != null ? storageType : snapshot.getStorageType());
.withStorageType(storageType != null ? storageType : snapshot.getStorageType())
.withCaCertificateIdentifier(caCertificateIdentifier);
DbInstance instance = createDbInstance(instanceId, snapshot.getEngine().name().toLowerCase(), snapshot.getEngineVersion(),
snapshot.getMasterUsername(), snapshot.getMasterPassword(),
snapshot.getDbName(), targetClass, snapshot.getAllocatedStorage(), Boolean.TRUE.equals(iamEnabled),
@@ -1363,7 +1382,8 @@ public class RdsService implements Resettable, ResourceProvider {
source.isStorageEncrypted() ? source.getKmsKeyId() : null,
request.backupRetentionPeriod(), request.preferredBackupWindow(), null,
request.copyTagsToSnapshot()).withStorageType(
request.storageType() != null ? request.storageType() : source.getStorageType());
request.storageType() != null ? request.storageType() : source.getStorageType())
.withCaCertificateIdentifier(request.caCertificateIdentifier());
DbInstance instance = createDbInstance(targetId, engineParam, source.getEngineVersion(),
source.getMasterUsername(), source.getMasterPassword(), dbName,
firstNonBlank(request.dbInstanceClass(), source.getDbInstanceClass()),
@@ -1571,7 +1591,8 @@ public class RdsService implements Resettable, ResourceProvider {
source.isStorageEncrypted() && sameRegion ? source.getKmsKeyId() : null,
0, source.getPreferredBackupWindow(), source.getPreferredMaintenanceWindow(),
copyTagsToSnapshot).withStorageType(
request.storageType() != null ? request.storageType() : source.getStorageType());
request.storageType() != null ? request.storageType() : source.getStorageType())
.withCaCertificateIdentifier(request.caCertificateIdentifier());
Map<String, String> tags = request.tags() != null ? request.tags() : Map.of();
DbInstance replica = createDbInstance(id, engineParam, source.getEngineVersion(),
@@ -3149,6 +3170,10 @@ public class RdsService implements Resettable, ResourceProvider {
effective = effective.withStorageType(null);
}
validateAutoscalingMinimum(instance, effective.maxAllocatedStorage());
if (!isBlank(settings.caCertificateIdentifier())) {
effective = effective.withCaCertificateIdentifier(
resolveCaCertificate(settings.caCertificateIdentifier(), effectiveRegion));
}
boolean changesParameterGroup = dbParameterGroupName != null && !dbParameterGroupName.isBlank();
if (changesParameterGroup) {
validateInstanceParameterGroup(dbParameterGroupName, engineName(instance),
@@ -6541,6 +6566,104 @@ public class RdsService implements Resettable, ResourceProvider {
LOG.infov("DB proxy {0} deleted", name);
}
// ── Certificates ──────────────────────────────────────────────────────────
/** A certificate authority as DescribeCertificates and ModifyCertificates report it. */
public record Certificate(String certificateIdentifier, String thumbprint, Instant validFrom,
Instant validTill, String certificateArn, boolean customerOverride,
Instant customerOverrideValidTill) {}
public record CertificatePage(List<Certificate> certificates, String defaultForNewLaunches, String marker) {}
/** The CA an instance reports and the end of its validity. */
public record InstanceCertificate(String caIdentifier, Instant validTill) {}
/**
* The Region's certificate authorities in identifier order, or the one named, with the CA a new
* instance gets. {@code Filters} is not taken: the API reference says it isn't supported.
*/
public synchronized CertificatePage describeCertificates(String region, String certificateIdentifier,
Integer maxRecords, String marker) {
String effectiveRegion = effectiveRegion(region);
requireValidMaxRecords(maxRecords);
String override = certificateOverrides.get(effectiveRegion).orElse(null);
List<Certificate> matching = new ArrayList<>();
for (RdsCaCertificates.CaCertificate ca : RdsCaCertificates.forRegion(effectiveRegion)) {
if (isBlank(certificateIdentifier) || ca.identifier().equalsIgnoreCase(certificateIdentifier)) {
matching.add(certificate(ca, effectiveRegion, ca.identifier().equals(override)));
}
}
if (!isBlank(certificateIdentifier) && matching.isEmpty()) {
throw certificateNotFound(certificateIdentifier);
}
OffsetPage<Certificate> page = offsetPage(matching, maxRecords, marker);
return new CertificatePage(page.items(), defaultCaCertificate(effectiveRegion), page.marker());
}
/**
* Sets the CA new instances in the Region get, or with {@code removeCustomerOverride} puts back
* RDS's default. The answer is the CA set, or after a removal the one that was overridden.
*/
public synchronized Certificate modifyCertificates(String region, String certificateIdentifier,
Boolean removeCustomerOverride) {
String effectiveRegion = effectiveRegion(region);
boolean remove = Boolean.TRUE.equals(removeCustomerOverride);
if (remove == !isBlank(certificateIdentifier)) {
throw new AwsException("InvalidParameterCombination",
"Specify either CertificateIdentifier or RemoveCustomerOverride, but not both.", 400);
}
if (remove) {
String previous = certificateOverrides.get(effectiveRegion)
.orElse(RdsCaCertificates.DEFAULT_FOR_NEW_LAUNCHES);
certificateOverrides.delete(effectiveRegion);
return certificate(RdsCaCertificates.find(effectiveRegion, previous)
.orElseThrow(() -> certificateNotFound(previous)), effectiveRegion, false);
}
RdsCaCertificates.CaCertificate ca = RdsCaCertificates.find(effectiveRegion, certificateIdentifier)
.orElseThrow(() -> certificateNotFound(certificateIdentifier));
certificateOverrides.put(effectiveRegion, ca.identifier());
return certificate(ca, effectiveRegion, true);
}
/**
* The CA an instance reports. One stored before CAs were recorded reports RDS's default, since an
* override applies only to instances created after it.
*/
public InstanceCertificate instanceCertificate(DbInstance instance) {
String region = regionFromArn(instance.getDbInstanceArn());
String identifier = instance.getCaCertificateIdentifier() != null
? instance.getCaCertificateIdentifier() : RdsCaCertificates.DEFAULT_FOR_NEW_LAUNCHES;
return RdsCaCertificates.find(region, identifier)
.map(ca -> new InstanceCertificate(ca.identifier(), ca.validTill()))
.orElse(new InstanceCertificate(identifier, null));
}
/** The account's override for the Region, else RDS's default. */
private String defaultCaCertificate(String region) {
return certificateOverrides.get(region).orElse(RdsCaCertificates.DEFAULT_FOR_NEW_LAUNCHES);
}
/** The requested CA in its canonical case, or the Region's default when none is requested. */
private String resolveCaCertificate(String requested, String region) {
if (isBlank(requested)) {
return defaultCaCertificate(region);
}
return RdsCaCertificates.find(region, requested)
.map(RdsCaCertificates.CaCertificate::identifier)
.orElseThrow(() -> certificateNotFound(requested));
}
private Certificate certificate(RdsCaCertificates.CaCertificate ca, String region, boolean override) {
String arn = new AwsArnUtils.Arn(regionResolver.partitionForRegion(region), "rds", region, "",
"cert:" + ca.identifier()).toString();
return new Certificate(ca.identifier(), ca.thumbprint(), ca.validFrom(), ca.validTill(), arn, override,
override ? ca.validTill() : null);
}
private static AwsException certificateNotFound(String identifier) {
return new AwsException("CertificateNotFound", "Certificate " + identifier + " not found.", 404);
}
// ── DB Proxy endpoints ────────────────────────────────────────────────────
/** AWS's limit on the endpoints a caller adds to one proxy, besides its default endpoint. */
@@ -26,6 +26,8 @@ public class DbInstance {
private String dbInstanceClass;
private int allocatedStorage;
private String storageType;
/** The RDS certificate authority for the instance; null on one stored before it was recorded. */
private String caCertificateIdentifier;
private DbInstanceStatus status;
private DbEndpoint endpoint;
private boolean iamDatabaseAuthenticationEnabled;
@@ -137,6 +139,11 @@ public class DbInstance {
public String getStorageType() { return storageType != null ? storageType : DEFAULT_STORAGE_TYPE; }
public void setStorageType(String storageType) { this.storageType = storageType; }
public String getCaCertificateIdentifier() { return caCertificateIdentifier; }
public void setCaCertificateIdentifier(String caCertificateIdentifier) {
this.caCertificateIdentifier = caCertificateIdentifier;
}
public int getAllocatedStorage() { return allocatedStorage; }
public void setAllocatedStorage(int allocatedStorage) { this.allocatedStorage = allocatedStorage; }
@@ -27,7 +27,20 @@ public record DbInstanceSettings(Boolean storageEncrypted,
List<String> enabledCloudwatchLogsExports,
LogExportChanges logExportChanges,
Integer maxAllocatedStorage,
String storageType) {
String storageType,
String caCertificateIdentifier) {
public DbInstanceSettings(Boolean storageEncrypted, String kmsKeyId, Integer backupRetentionPeriod,
String preferredBackupWindow, String preferredMaintenanceWindow,
Boolean copyTagsToSnapshot, Integer monitoringInterval, String monitoringRoleArn,
Boolean performanceInsightsEnabled, Integer performanceInsightsRetentionPeriod,
String engineLifecycleSupport, List<String> enabledCloudwatchLogsExports,
LogExportChanges logExportChanges, Integer maxAllocatedStorage, String storageType) {
this(storageEncrypted, kmsKeyId, backupRetentionPeriod, preferredBackupWindow,
preferredMaintenanceWindow, copyTagsToSnapshot, monitoringInterval, monitoringRoleArn,
performanceInsightsEnabled, performanceInsightsRetentionPeriod, engineLifecycleSupport,
enabledCloudwatchLogsExports, logExportChanges, maxAllocatedStorage, storageType, null);
}
public DbInstanceSettings(Boolean storageEncrypted, String kmsKeyId, Integer backupRetentionPeriod,
String preferredBackupWindow, String preferredMaintenanceWindow,
@@ -187,7 +200,8 @@ public record DbInstanceSettings(Boolean storageEncrypted,
backupWindow, maintenanceWindow, copyTagsToSnapshot,
monitoringInterval, monitoringRoleArn, performanceInsightsEnabled,
performanceInsightsRetentionPeriod, engineLifecycleSupport,
enabledCloudwatchLogsExports, logExportChanges, maxAllocatedStorage, storageType);
enabledCloudwatchLogsExports, logExportChanges, maxAllocatedStorage, storageType,
caCertificateIdentifier);
}
public DbInstanceSettings withKmsKeyId(String resolvedKmsKeyId) {
@@ -195,7 +209,8 @@ public record DbInstanceSettings(Boolean storageEncrypted,
preferredBackupWindow, preferredMaintenanceWindow, copyTagsToSnapshot,
monitoringInterval, monitoringRoleArn, performanceInsightsEnabled,
performanceInsightsRetentionPeriod, engineLifecycleSupport,
enabledCloudwatchLogsExports, logExportChanges, maxAllocatedStorage, storageType);
enabledCloudwatchLogsExports, logExportChanges, maxAllocatedStorage, storageType,
caCertificateIdentifier);
}
public DbInstanceSettings withStorageType(String resolvedStorageType) {
@@ -203,7 +218,18 @@ public record DbInstanceSettings(Boolean storageEncrypted,
preferredBackupWindow, preferredMaintenanceWindow, copyTagsToSnapshot,
monitoringInterval, monitoringRoleArn, performanceInsightsEnabled,
performanceInsightsRetentionPeriod, engineLifecycleSupport,
enabledCloudwatchLogsExports, logExportChanges, maxAllocatedStorage, resolvedStorageType);
enabledCloudwatchLogsExports, logExportChanges, maxAllocatedStorage, resolvedStorageType,
caCertificateIdentifier);
}
/** The same settings with the CA certificate the service resolved. */
public DbInstanceSettings withCaCertificateIdentifier(String resolvedCaCertificateIdentifier) {
return new DbInstanceSettings(storageEncrypted, kmsKeyId, backupRetentionPeriod,
preferredBackupWindow, preferredMaintenanceWindow, copyTagsToSnapshot,
monitoringInterval, monitoringRoleArn, performanceInsightsEnabled,
performanceInsightsRetentionPeriod, engineLifecycleSupport,
enabledCloudwatchLogsExports, logExportChanges, maxAllocatedStorage, storageType,
resolvedCaCertificateIdentifier);
}
public void validateStorageType() {
@@ -261,5 +287,8 @@ public record DbInstanceSettings(Boolean storageEncrypted,
if (maxAllocatedStorage != null) {
instance.setMaxAllocatedStorage(maxAllocatedStorage);
}
if (caCertificateIdentifier != null && !caCertificateIdentifier.isBlank()) {
instance.setCaCertificateIdentifier(caCertificateIdentifier);
}
}
}
@@ -36,7 +36,40 @@ public record PointInTimeRestoreRequest(String targetDbInstanceIdentifier,
String preferredBackupWindow,
Boolean deletionProtection,
Map<String, String> tags,
String storageType) {
String storageType,
String caCertificateIdentifier) {
public PointInTimeRestoreRequest(String targetDbInstanceIdentifier,
String sourceDbInstanceIdentifier,
String sourceDbiResourceId,
String sourceDbInstanceAutomatedBackupsArn,
Instant restoreTime,
Boolean useLatestRestorableTime,
String dbInstanceClass,
Integer port,
String availabilityZone,
Boolean multiAz,
Boolean autoMinorVersionUpgrade,
String dbName,
String optionGroupName,
String dbParameterGroupName,
Boolean publiclyAccessible,
String dbSubnetGroupName,
List<String> vpcSecurityGroupIds,
Boolean copyTagsToSnapshot,
Boolean iamDatabaseAuthenticationEnabled,
Integer backupRetentionPeriod,
String preferredBackupWindow,
Boolean deletionProtection,
Map<String, String> tags,
String storageType) {
this(targetDbInstanceIdentifier, sourceDbInstanceIdentifier, sourceDbiResourceId,
sourceDbInstanceAutomatedBackupsArn, restoreTime, useLatestRestorableTime, dbInstanceClass,
port, availabilityZone, multiAz, autoMinorVersionUpgrade, dbName, optionGroupName,
dbParameterGroupName, publiclyAccessible, dbSubnetGroupName, vpcSecurityGroupIds,
copyTagsToSnapshot, iamDatabaseAuthenticationEnabled, backupRetentionPeriod,
preferredBackupWindow, deletionProtection, tags, storageType, null);
}
public PointInTimeRestoreRequest(String targetDbInstanceIdentifier,
String sourceDbInstanceIdentifier,
@@ -66,6 +99,6 @@ public record PointInTimeRestoreRequest(String targetDbInstanceIdentifier,
port, availabilityZone, multiAz, autoMinorVersionUpgrade, dbName, optionGroupName,
dbParameterGroupName, publiclyAccessible, dbSubnetGroupName, vpcSecurityGroupIds,
copyTagsToSnapshot, iamDatabaseAuthenticationEnabled, backupRetentionPeriod,
preferredBackupWindow, deletionProtection, tags, null);
preferredBackupWindow, deletionProtection, tags, null, null);
}
}
@@ -27,7 +27,31 @@ public record ReadReplicaRequest(String dbInstanceIdentifier,
Integer allocatedStorage,
String replicaMode,
Map<String, String> tags,
String storageType) {
String storageType,
String caCertificateIdentifier) {
public ReadReplicaRequest(String dbInstanceIdentifier,
String sourceDbInstanceIdentifier,
String dbInstanceClass,
String availabilityZone,
Boolean multiAz,
Boolean autoMinorVersionUpgrade,
String optionGroupName,
String dbParameterGroupName,
Boolean publiclyAccessible,
String dbSubnetGroupName,
List<String> vpcSecurityGroupIds,
Boolean copyTagsToSnapshot,
Boolean iamDatabaseAuthenticationEnabled,
Integer allocatedStorage,
String replicaMode,
Map<String, String> tags,
String storageType) {
this(dbInstanceIdentifier, sourceDbInstanceIdentifier, dbInstanceClass, availabilityZone, multiAz,
autoMinorVersionUpgrade, optionGroupName, dbParameterGroupName, publiclyAccessible,
dbSubnetGroupName, vpcSecurityGroupIds, copyTagsToSnapshot, iamDatabaseAuthenticationEnabled,
allocatedStorage, replicaMode, tags, storageType, null);
}
public ReadReplicaRequest(String dbInstanceIdentifier,
String sourceDbInstanceIdentifier,
@@ -48,6 +72,6 @@ public record ReadReplicaRequest(String dbInstanceIdentifier,
this(dbInstanceIdentifier, sourceDbInstanceIdentifier, dbInstanceClass, availabilityZone, multiAz,
autoMinorVersionUpgrade, optionGroupName, dbParameterGroupName, publiclyAccessible,
dbSubnetGroupName, vpcSecurityGroupIds, copyTagsToSnapshot, iamDatabaseAuthenticationEnabled,
allocatedStorage, replicaMode, tags, null);
allocatedStorage, replicaMode, tags, null, null);
}
}
@@ -0,0 +1,616 @@
{
"_source": {
"generator": "tools/aws/regen_rds_ca_certificates.py",
"bundles": "https://truststore.pki.rds.amazonaws.com/{region}/{region}-bundle.pem"
},
"regions": {
"af-south-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "eb17498b6fee02d0f20f8f92587bf71db0cd7a47",
"validFrom": "2021-05-19T19:35:16Z",
"validTill": "2121-05-19T20:35:16Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "c8e8da8690e8f88f13c57d9703a3a688c66e482d",
"validFrom": "2021-05-19T19:24:16Z",
"validTill": "2061-05-19T20:24:16Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "046cd72b52f65afabfd6f81b63b73388133563f0",
"validFrom": "2021-05-19T19:28:43Z",
"validTill": "2121-05-19T20:28:43Z"
}
],
"ap-east-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "7fade462f2ed6b7ae39b9245ba7d6355d9c021a7",
"validFrom": "2021-05-25T21:45:11Z",
"validTill": "2121-05-25T22:45:11Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "a368611145864bff0436b8287ed1e5b32c0eadf7",
"validFrom": "2021-05-25T21:30:33Z",
"validTill": "2061-05-25T22:30:33Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "7ae043cbc8ed40fef7ccfc7d04803a6fb1952d40",
"validFrom": "2021-05-25T21:34:51Z",
"validTill": "2121-05-25T22:34:51Z"
}
],
"ap-east-2": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "0f9f26bb42ab0de393135ebe965f0fd92f9fb621",
"validFrom": "2025-02-01T00:10:31Z",
"validTill": "2125-02-01T01:10:31Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "a69cffad295b98a84d587e7ba6eac08ec8992a9c",
"validFrom": "2025-02-01T00:10:21Z",
"validTill": "2065-02-01T01:10:21Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "a5a8551f61e5bcda4337711c94382f7a21665724",
"validFrom": "2025-02-01T00:10:26Z",
"validTill": "2125-02-01T01:10:26Z"
}
],
"ap-northeast-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "aef371e2014ce6064513cac92c0c550ab7ccf288",
"validFrom": "2021-05-25T22:03:16Z",
"validTill": "2121-05-25T23:03:16Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "d790bbb661bafa4101829f103d639befa300f9a4",
"validFrom": "2021-05-25T21:54:58Z",
"validTill": "2061-05-25T22:54:58Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "47104f39034f4722a41ec96c1e9f9ad2342d63db",
"validFrom": "2021-05-25T21:59:10Z",
"validTill": "2121-05-25T22:59:10Z"
}
],
"ap-northeast-2": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "1942e0edf16cf7e83001b2bbd642f19563b0eb74",
"validFrom": "2021-05-20T16:38:26Z",
"validTill": "2121-05-20T17:38:26Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "58fe7e8c3b1f561be7e51f69dcfc8acfbb546e02",
"validFrom": "2021-05-20T16:28:41Z",
"validTill": "2061-05-20T17:28:41Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "58f4fd12f736da59fbd0d2bf63e54b24c7f4e0d8",
"validFrom": "2021-05-20T16:33:23Z",
"validTill": "2121-05-20T17:33:23Z"
}
],
"ap-northeast-3": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "1af13f3fb0b14e7a6fc6c7b18b1bb6699b7a914d",
"validFrom": "2021-05-24T20:32:17Z",
"validTill": "2121-05-24T21:32:17Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "85a2f639e393c815e3a3a50f061003d20186afed",
"validFrom": "2021-05-24T20:23:16Z",
"validTill": "2061-05-24T21:23:16Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "9fee20b96a49a5d71eb09b298f45a9f12dff2339",
"validFrom": "2021-05-24T20:28:03Z",
"validTill": "2121-05-24T21:28:03Z"
}
],
"ap-south-1": [
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "cd4bec28c1b9b43688a7e9d5d24cc99ae506957f",
"validFrom": "2021-05-19T17:40:34Z",
"validTill": "2061-05-19T18:40:34Z"
}
],
"ap-south-2": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "901a29a5512afe9b2198db383208ab0533fdc0da",
"validFrom": "2022-06-06T21:54:42Z",
"validTill": "2122-06-06T22:54:42Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "247098fa168936a3ae65df5310cfa56711c1c5ac",
"validFrom": "2022-06-06T21:42:22Z",
"validTill": "2062-06-06T22:42:22Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "7050c86e7ee972e94085e7ab8b48688ce15bf9b9",
"validFrom": "2022-06-06T21:48:18Z",
"validTill": "2122-06-06T22:48:18Z"
}
],
"ap-southeast-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "5fa447d7be948b1325b6ba736987d658362e0e21",
"validFrom": "2021-05-21T21:50:01Z",
"validTill": "2121-05-21T22:50:01Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "aa6b73726c21176cc714815278d6ebc932f293b3",
"validFrom": "2021-05-21T21:39:39Z",
"validTill": "2061-05-21T22:39:39Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "f4f6e4163a0de677e5976c0cc1f7d361f95bd487",
"validFrom": "2021-05-21T21:45:05Z",
"validTill": "2121-05-21T22:45:05Z"
}
],
"ap-southeast-2": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "e9583afdfda93978f50e9dff5e622ecca0d03b04",
"validFrom": "2021-05-24T20:50:15Z",
"validTill": "2121-05-24T21:50:15Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "6946d79e4c5b015ebc5fbd4c2b9e24d0e07ec528",
"validFrom": "2021-05-24T20:42:33Z",
"validTill": "2061-05-24T21:42:33Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "19dcede6eda2209044b28335b12dd2442e12ac2a",
"validFrom": "2021-05-24T20:46:18Z",
"validTill": "2121-05-24T21:46:18Z"
}
],
"ap-southeast-3": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "a7e235c9eee3b4fe64e9e761c25f19b5a9d2ba1e",
"validFrom": "2021-06-11T00:12:43Z",
"validTill": "2121-06-11T01:12:43Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "86c110e10967a0589346178806a9ffa605031dfa",
"validFrom": "2021-06-10T18:19:07Z",
"validTill": "2061-06-10T19:19:07Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "3cd1a556c570b4b2b8714da8fb5868dfb1edd565",
"validFrom": "2021-06-11T00:08:36Z",
"validTill": "2121-06-11T01:08:36Z"
}
],
"ap-southeast-4": [
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "1e79d7542516385da20dad542bbc52863c3d7b3c",
"validFrom": "2022-05-25T16:49:16Z",
"validTill": "2062-05-25T17:49:16Z"
}
],
"ap-southeast-5": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "09cc63ba354cdd0053ab634a7cf351c97d093d2c",
"validFrom": "2024-05-15T21:50:46Z",
"validTill": "2124-05-15T22:50:46Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "140d859becfb353bbcaa65ac629eed64b505d6d6",
"validFrom": "2024-05-15T21:50:37Z",
"validTill": "2064-05-15T22:50:37Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "d4f4a00efe08a1004ee2d647e37f7fdaa3b98e92",
"validFrom": "2024-05-15T21:50:41Z",
"validTill": "2124-05-15T22:50:41Z"
}
],
"ap-southeast-6": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "21b984c9086855eaef6f8958ecf132ea218a09d1",
"validFrom": "2025-05-20T01:44:07Z",
"validTill": "2125-05-20T02:44:07Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "9c9ceac35a80741fe9c8c4dcaf3af6c26c9ccccb",
"validFrom": "2025-05-20T01:43:57Z",
"validTill": "2065-05-20T02:43:57Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "38b385fb5d6a03820a36c51169b7c255ea27a912",
"validFrom": "2025-05-20T01:44:02Z",
"validTill": "2125-05-20T02:44:02Z"
}
],
"ap-southeast-7": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "c76fd91493bc103f623249f946cf35fc2b7a6146",
"validFrom": "2024-09-12T15:54:40Z",
"validTill": "2124-09-12T16:54:40Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "de207c6602ead605616041129f4b6e03d0c3b6f7",
"validFrom": "2024-09-12T15:54:31Z",
"validTill": "2064-09-12T16:54:31Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "dbf90da3be8a5b3cf4162e5de3bf19ad9efa91fa",
"validFrom": "2024-09-12T15:54:36Z",
"validTill": "2124-09-12T16:54:36Z"
}
],
"ca-central-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "acf799b55df74dc0831b3f452072bcfed0b3abb5",
"validFrom": "2021-05-21T22:13:09Z",
"validTill": "2121-05-21T23:13:09Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "b2b2dc2cd60938ffbd260ac587483437dc69ee8c",
"validFrom": "2021-05-21T22:02:35Z",
"validTill": "2061-05-21T23:02:35Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "d0192ad2dd437dad5e3e3a5a4822d125c6f0a96c",
"validFrom": "2021-05-21T22:08:53Z",
"validTill": "2121-05-21T23:08:53Z"
}
],
"ca-west-1": [
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "c3890f3c7a024e0195ff7477ead5318a7ce546a3",
"validFrom": "2023-09-13T20:21:34Z",
"validTill": "2063-09-13T21:21:33Z"
}
],
"eu-central-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "d2eb0ba87c0b459c89baa462c15cbf58e26798dc",
"validFrom": "2021-05-21T22:33:24Z",
"validTill": "2121-05-21T23:33:24Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "94e6f1a27cf230f869ec32b4611ca10a8280ad05",
"validFrom": "2021-05-21T22:23:47Z",
"validTill": "2061-05-21T23:23:47Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "d6878cce33c963c3d25bfd75bedee0461587a8df",
"validFrom": "2021-05-21T22:28:26Z",
"validTill": "2121-05-21T23:28:26Z"
}
],
"eu-central-2": [
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "bb78d17650755aa3777fc89ab59aa0249fc6ffb3",
"validFrom": "2022-06-06T21:17:05Z",
"validTill": "2062-06-06T22:17:05Z"
}
],
"eu-north-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "9b1dc638d42cf64e574a0d5d688855325932931f",
"validFrom": "2021-05-24T21:06:38Z",
"validTill": "2121-05-24T22:06:38Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "f6b6ce88387b94cbae7bffc5c1ab2bf5700126f6",
"validFrom": "2021-05-24T20:59:21Z",
"validTill": "2061-05-24T21:59:21Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "a32adde2b66d15b43058b0d761aa21f6c83925cd",
"validFrom": "2021-05-24T21:03:20Z",
"validTill": "2121-05-24T22:03:20Z"
}
],
"eu-south-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "85206e1e431071800e90a825255ba4f92dc4f4b6",
"validFrom": "2021-05-19T18:38:11Z",
"validTill": "2121-05-19T19:38:11Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "8f00fb08bf5f0c9cc9178e837a8a1490362c2006",
"validFrom": "2021-05-19T18:27:18Z",
"validTill": "2061-05-19T19:27:18Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "06722cd56a7ed942f8bed1d50425f0f12f856431",
"validFrom": "2021-05-19T18:33:21Z",
"validTill": "2121-05-19T19:33:21Z"
}
],
"eu-south-2": [
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "2c288b6a49cc18046ac82a58a8494ccaee48b49d",
"validFrom": "2022-05-23T18:16:32Z",
"validTill": "2062-05-23T19:16:32Z"
}
],
"eu-west-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "5ea6fe9d6773c8f072f30b6e16c11fa5d25f7fdd",
"validFrom": "2021-05-20T16:58:07Z",
"validTill": "2121-05-20T17:58:07Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "6063e7c0472f519526110dbf86a273b5c51953f3",
"validFrom": "2021-05-20T16:49:12Z",
"validTill": "2061-05-20T17:49:12Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "bd8624f023a2cd6f9c5965ab32a630a03560f1a1",
"validFrom": "2021-05-20T16:53:54Z",
"validTill": "2121-05-20T17:53:54Z"
}
],
"eu-west-2": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "ca0e522940d23c70de18678d7a83213f9acd5a70",
"validFrom": "2021-05-21T22:55:21Z",
"validTill": "2121-05-21T23:55:21Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "30d2b9d972a11f331cc76b2c4013eb0129eedcf0",
"validFrom": "2021-05-21T22:46:24Z",
"validTill": "2061-05-21T23:46:24Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "eb1680bd740240dcea1303c212dcfda397d809c5",
"validFrom": "2021-05-21T22:51:22Z",
"validTill": "2121-05-21T23:51:22Z"
}
],
"eu-west-3": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "c77dd20770981e8f135fe071a44fe9dd19d11a5c",
"validFrom": "2021-05-25T22:26:12Z",
"validTill": "2121-05-25T23:26:12Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "dabef00db9022b46c2ab1747a6421252872b058e",
"validFrom": "2021-05-25T22:18:33Z",
"validTill": "2061-05-25T23:18:33Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "20ad9a591cb5174b57960da9714844e595ef3250",
"validFrom": "2021-05-25T22:22:33Z",
"validTill": "2121-05-25T23:22:33Z"
}
],
"il-central-1": [
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "b9e33b6381a161cb875f36761cbe499296b6edca",
"validFrom": "2022-12-02T20:14:08Z",
"validTill": "2062-12-02T21:14:08Z"
}
],
"me-central-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "6cb23d56510932d28946d0858ce48c90c9824b26",
"validFrom": "2022-05-07T00:44:37Z",
"validTill": "2122-05-07T01:44:37Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "2f0c13891565299af97b930bc722da849504c028",
"validFrom": "2022-05-06T23:20:09Z",
"validTill": "2062-05-07T00:20:09Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "2bff95bb0a23e110856800c37de14abc208fec39",
"validFrom": "2022-05-07T00:40:23Z",
"validTill": "2122-05-07T01:40:23Z"
}
],
"me-south-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "674d3be6cc4fb231e7e06ef6fad27773ebe177cc",
"validFrom": "2021-05-20T17:19:55Z",
"validTill": "2121-05-20T18:19:55Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "71d170c07914224f64b2aeefd19fe01c6b5f9cea",
"validFrom": "2021-05-20T17:09:16Z",
"validTill": "2061-05-20T18:09:16Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "71df58555e079f4ca139303e2c9ab3462421bca4",
"validFrom": "2021-05-20T17:15:33Z",
"validTill": "2121-05-20T18:15:33Z"
}
],
"mx-central-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "e4b02140083fadd2315f4453c1fbb5af134b45a9",
"validFrom": "2024-09-30T16:14:00Z",
"validTill": "2124-09-30T17:13:59Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "f61302c5788a1ae5a6315423f22ad7901f64ac43",
"validFrom": "2024-09-30T16:13:50Z",
"validTill": "2064-09-30T17:13:50Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "b033d401ef5745b6991baa149084882a9aa02481",
"validFrom": "2024-09-30T16:13:55Z",
"validTill": "2124-09-30T17:13:55Z"
}
],
"sa-east-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "d2a9d3215a5bbd195d73448a3ae0c54fe48037bf",
"validFrom": "2021-05-19T18:16:01Z",
"validTill": "2121-05-19T19:16:01Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "cb025abf1b2ac719b680da4ab12fb2d14d797a0f",
"validFrom": "2021-05-19T18:06:26Z",
"validTill": "2061-05-19T19:06:26Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "7d2fdd76898b78b97e4bc436777a36283ac1b412",
"validFrom": "2021-05-19T18:11:20Z",
"validTill": "2121-05-19T19:11:20Z"
}
],
"us-east-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "24a97b91cbe86911190576c35c36aab4fa7b25de",
"validFrom": "2021-05-25T22:41:55Z",
"validTill": "2121-05-25T23:41:55Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "2fa77ef894d983ba9d37ad699c84ab0f657be1c8",
"validFrom": "2021-05-25T22:34:57Z",
"validTill": "2061-05-25T23:34:57Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "9da6fa7fd2ec09c569a400d876b01b0c12759a96",
"validFrom": "2021-05-25T22:38:35Z",
"validTill": "2121-05-25T23:38:35Z"
}
],
"us-east-2": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "46dd6725f28f5b8af1d9344c6ecd8e292abd95dd",
"validFrom": "2021-05-21T23:15:56Z",
"validTill": "2121-05-22T00:15:56Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "8cf85e3e2bdbcbe2c4a34c1e85828fb29833e87f",
"validFrom": "2021-05-21T23:04:44Z",
"validTill": "2061-05-22T00:04:44Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "dd8e39e6bdd7ea8e747dce66c76b98b1d42a49a7",
"validFrom": "2021-05-21T23:11:06Z",
"validTill": "2121-05-22T00:11:06Z"
}
],
"us-west-1": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "f71225019679757429e4be85f31ee1b6fbc82b81",
"validFrom": "2021-05-19T19:13:24Z",
"validTill": "2121-05-19T20:13:24Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "0f7fb44cf65fc3b2b9133305fd11bc80973a36d5",
"validFrom": "2021-05-19T19:04:06Z",
"validTill": "2061-05-19T20:04:06Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "c748cb45e7509e9c2d29b17efe4656989ef94a26",
"validFrom": "2021-05-19T19:08:58Z",
"validTill": "2121-05-19T20:08:58Z"
}
],
"us-west-2": [
{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "2ee3dcc06e50192559b13929e73484354f23387d",
"validFrom": "2021-05-24T22:06:59Z",
"validTill": "2121-05-24T23:06:59Z"
},
{
"certificateIdentifier": "rds-ca-rsa2048-g1",
"thumbprint": "7c40cb42714b6fdb2b296f9bbd0e8bb364436a76",
"validFrom": "2021-05-24T21:59:00Z",
"validTill": "2061-05-24T22:59:00Z"
},
{
"certificateIdentifier": "rds-ca-rsa4096-g1",
"thumbprint": "19da4f2af579a8ae1f6a0fa77aa5befd874b4cab",
"validFrom": "2021-05-24T22:03:20Z",
"validTill": "2121-05-24T23:03:20Z"
}
]
}
}
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbEndpoint;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings;
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbProxy;
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
@@ -30,6 +31,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@@ -75,6 +77,8 @@ class RdsCfnProvisionerTest {
@BeforeEach
void setUp() {
rdsService = mock(RdsService.class);
when(rdsService.instanceCertificate(any())).thenReturn(
new RdsService.InstanceCertificate("rds-ca-rsa2048-g1", Instant.parse("2061-05-25T23:34:57Z")));
secretsManagerService = mock(SecretsManagerService.class);
ssmService = mock(SsmService.class);
importResolver = name -> null;
@@ -127,6 +131,14 @@ class RdsCfnProvisionerTest {
"us-east-1", "000000000000", "my-stack", existingPhysicalId, Map.of());
}
/** Any {@code createDbInstance} call returns {@code instance}. */
private void stubCreateDbInstance(DbInstance instance) {
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), anyList(), nullable(String.class), nullable(String.class),
anyBoolean(), any(DbInstanceSettings.class))).thenReturn(instance);
}
@Test
void provisionsDbInstanceWithMappedArgsAndEndpointAttributes() {
DbInstance instance = mock(DbInstance.class);
@@ -134,9 +146,7 @@ class RdsCfnProvisionerTest {
when(instance.getEndpoint()).thenReturn(new DbEndpoint("mydb.local", 5432));
when(instance.getDbInstanceArn()).thenReturn("arn:aws:rds:us-east-1:000000000000:db:mydb");
when(instance.getDbiResourceId()).thenReturn("db-ABCDEFGHIJKLMNOP");
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), nullable(String.class))).thenReturn(instance);
stubCreateDbInstance(instance);
StackResource r = provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","EngineVersion":"16",
@@ -155,16 +165,37 @@ class RdsCfnProvisionerTest {
// CFN properties mapped to the create-method arguments; absent optionals are null.
verify(rdsService).createDbInstance("mydb", "postgres", "16", "admin", "secret",
"appdb", "db.t3.small", 50, false, null, null, null,
null, false, false, null, Map.of(), "us-east-1");
null, false, false, null, Map.of(), List.of(), null, "us-east-1", true,
DbInstanceSettings.defaults());
}
@Test
void aDbInstanceTakesItsCaCertificateAndExposesItsDetails() {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
stubCreateDbInstance(instance);
when(rdsService.instanceCertificate(instance)).thenReturn(
new RdsService.InstanceCertificate("rds-ca-ecc384-g1", Instant.parse("2121-05-25T23:41:55Z")));
StackResource r = provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
"MasterUserPassword":"secret","CACertificateIdentifier":"rds-ca-ecc384-g1"}
""");
assertEquals("CREATE_COMPLETE", r.getStatus());
assertEquals("rds-ca-ecc384-g1", r.getAttributes().get("CertificateDetails.CAIdentifier"));
assertEquals("2121-05-25T23:41:55Z", r.getAttributes().get("CertificateDetails.ValidTill"));
verify(rdsService).createDbInstance("mydb", "postgres", null, "admin", "secret",
null, "db.t3.micro", 20, false, null, null, null,
null, false, false, null, Map.of(), List.of(), null, "us-east-1", true,
DbInstanceSettings.defaults().withCaCertificateIdentifier("rds-ca-ecc384-g1"));
}
@Test
void deletesANewDbInstanceWhoseAssociatedRolesAreRefused() {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), nullable(String.class))).thenReturn(instance);
stubCreateDbInstance(instance);
when(rdsService.addRoleToDbInstance("us-east-1", "mydb", "arn:aws:iam::000000000000:role/a", "s3Import"))
.thenReturn(instance);
when(rdsService.addRoleToDbInstance("us-east-1", "mydb", "arn:aws:iam::000000000000:role/b", "s3Import"))
@@ -186,9 +217,7 @@ class RdsCfnProvisionerTest {
void provisionsDbInstanceInStackRegion() {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), nullable(String.class))).thenReturn(instance);
stubCreateDbInstance(instance);
provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
@@ -197,7 +226,8 @@ class RdsCfnProvisionerTest {
verify(rdsService).createDbInstance("mydb", "postgres", null, "admin", "secret",
null, "db.t3.micro", 20, false, null, null, null,
null, false, false, null, Map.of(), "us-west-2");
null, false, false, null, Map.of(), List.of(), null, "us-west-2", true,
DbInstanceSettings.defaults());
}
@Test
@@ -407,9 +437,7 @@ class RdsCfnProvisionerTest {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), nullable(String.class))).thenReturn(instance);
stubCreateDbInstance(instance);
provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres",
@@ -420,7 +448,8 @@ class RdsCfnProvisionerTest {
verify(rdsService).createDbInstance(
eq("mydb"), eq("postgres"), any(), eq("resolved-user"), eq("resolved-secret"),
any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(),
anyBoolean(), anyBoolean(), any(), anyMap(), eq("us-west-2"));
anyBoolean(), anyBoolean(), any(), anyMap(), anyList(), nullable(String.class), eq("us-west-2"),
anyBoolean(), any(DbInstanceSettings.class));
verify(secretsManagerService, times(2))
.getSecretValue("my-secret", null, null, "us-west-2");
}
@@ -693,9 +722,7 @@ class RdsCfnProvisionerTest {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), nullable(String.class))).thenReturn(instance);
stubCreateDbInstance(instance);
StackResource resource = provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres",
@@ -707,7 +734,8 @@ class RdsCfnProvisionerTest {
verify(rdsService).createDbInstance(
eq("mydb"), eq("postgres"), any(), eq("admin"), eq("resolved-secure"),
any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(),
anyBoolean(), anyBoolean(), any(), anyMap(), eq("us-east-1"));
anyBoolean(), anyBoolean(), any(), anyMap(), anyList(), nullable(String.class), eq("us-east-1"),
anyBoolean(), any(DbInstanceSettings.class));
}
@ParameterizedTest
@@ -1382,7 +1410,8 @@ class RdsCfnProvisionerTest {
when(rdsService.getDbInstance("mydb")).thenReturn(existing);
DbInstance reconciled = mock(DbInstance.class);
when(reconciled.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.modifyDbInstance(eq("mydb"), any(), anyBoolean(), any())).thenReturn(reconciled);
when(rdsService.modifyDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), any(),
any(DbInstanceSettings.class))).thenReturn(reconciled);
StackResource r = provisionUpdate("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
@@ -1392,8 +1421,27 @@ class RdsCfnProvisionerTest {
assertEquals("mydb", r.getPhysicalId());
verify(rdsService, never()).createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), nullable(String.class));
verify(rdsService).modifyDbInstance("mydb", "secret", false, null);
any(), anyMap(), anyList(), nullable(String.class), nullable(String.class),
anyBoolean(), any(DbInstanceSettings.class));
verify(rdsService).modifyDbInstance("mydb", "secret", false, null, null, null, null, null,
DbInstanceSettings.unchanged());
}
@Test
void updateStackChangesAnExistingDbInstancesCaCertificate() {
when(rdsService.getDbInstance("mydb")).thenReturn(mock(DbInstance.class));
DbInstance reconciled = mock(DbInstance.class);
when(reconciled.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.modifyDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), any(),
any(DbInstanceSettings.class))).thenReturn(reconciled);
provisionUpdate("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
"MasterUserPassword":"secret","CACertificateIdentifier":"rds-ca-rsa4096-g1"}
""", "mydb");
verify(rdsService).modifyDbInstance("mydb", "secret", false, null, null, null, null, null,
DbInstanceSettings.unchanged().withCaCertificateIdentifier("rds-ca-rsa4096-g1"));
}
@Test
@@ -1573,7 +1621,8 @@ class RdsCfnProvisionerTest {
when(withLambda.getDbInstanceIdentifier()).thenReturn("mydb");
when(withLambda.getAssociatedRoles()).thenReturn(List.of(new DbRoleAssociation(lambda, "Lambda")));
when(rdsService.getDbInstance("mydb")).thenReturn(before);
when(rdsService.modifyDbInstance(eq("mydb"), any(), any(), any())).thenReturn(before);
when(rdsService.modifyDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), any(),
any(DbInstanceSettings.class))).thenReturn(before);
when(rdsService.removeRoleFromDbInstance("us-east-1", "mydb", old, "s3Import")).thenReturn(withoutOld);
when(rdsService.addRoleToDbInstance("us-east-1", "mydb", lambda, "Lambda")).thenReturn(withLambda);
when(rdsService.addRoleToDbInstance("us-east-1", "mydb", refused, "s3Export"))
@@ -1600,9 +1649,7 @@ class RdsCfnProvisionerTest {
// costs only the new instance.
DbInstance renamed = mock(DbInstance.class);
when(renamed.getDbInstanceIdentifier()).thenReturn("newdb");
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), nullable(String.class))).thenReturn(renamed);
stubCreateDbInstance(renamed);
when(rdsService.addRoleToDbInstance(any(), eq("newdb"), any(), any()))
.thenThrow(new AwsException("InvalidParameterValue", "feature not supported", 400));
@@ -0,0 +1,128 @@
package io.github.hectorvent.floci.services.rds;
import io.github.hectorvent.floci.testing.RdsMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
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.restassured.RestAssured.given;
import static io.restassured.http.ContentType.URLENC;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
/**
* {@code DescribeCertificates}, {@code ModifyCertificates} and an instance's
* {@code CACertificateIdentifier} over the Query protocol. The requests sign for eu-north-1, so the
* account override set here is not the one other tests' instances in us-east-1 see.
*/
@QuarkusTest
@TestProfile(RdsMockProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class RdsCertificatesIntegrationTest {
private static final String REGION = "eu-north-1";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261020/" + REGION + "/rds/aws4_request, "
+ "SignedHeaders=content-type;host, Signature=test";
private static RequestSpecification query(String action) {
return given().header("Authorization", AUTH)
.contentType(URLENC)
.formParam("Action", action)
.formParam("Version", "2014-10-31");
}
private static RequestSpecification createInstance(String id) {
return query("CreateDBInstance")
.formParam("DBInstanceIdentifier", id)
.formParam("Engine", "postgres")
.formParam("DBInstanceClass", "db.t3.micro")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "password123")
.formParam("AllocatedStorage", "20");
}
/** The instances hold ports the other tests in this Quarkus app expect to find free. */
@AfterEach
void cleanUp() {
for (String id : new String[] {"ca-default-db", "ca-named-db"}) {
query("DeleteDBInstance").formParam("DBInstanceIdentifier", id)
.formParam("SkipFinalSnapshot", "true").when().post("/");
}
query("ModifyCertificates").formParam("RemoveCustomerOverride", "true").when().post("/");
}
@Test
@Order(1)
void theRegionsCertificatesAreListedWithTheDefault() {
query("DescribeCertificates")
.when().post("/").then().statusCode(200)
.body(containsString("<DescribeCertificatesResult><DefaultCertificateForNewLaunches>"
+ "rds-ca-rsa2048-g1</DefaultCertificateForNewLaunches><Certificates><Certificate>"
+ "<CertificateIdentifier>rds-ca-ecc384-g1</CertificateIdentifier>"
+ "<CertificateType>CA</CertificateType>"))
.body(containsString("<CertificateArn>arn:aws:rds:" + REGION + "::cert:rds-ca-rsa2048-g1"
+ "</CertificateArn><CustomerOverride>false</CustomerOverride>"))
.body(not(containsString("<Marker>")));
query("DescribeCertificates").formParam("CertificateIdentifier", "rds-ca-2019")
.when().post("/").then().statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
query("DescribeCertificates").formParam("MaxRecords", "20").formParam("Marker", "2")
.when().post("/").then().statusCode(200)
.body(containsString("<Certificates><Certificate><CertificateIdentifier>rds-ca-rsa4096-g1"
+ "</CertificateIdentifier>"));
}
@Test
@Order(2)
void anOverrideIsWhatANewInstanceGets() {
query("ModifyCertificates").formParam("CertificateIdentifier", "rds-ca-ecc384-g1")
.when().post("/").then().statusCode(200)
.body(containsString("<ModifyCertificatesResult><Certificate>"
+ "<CertificateIdentifier>rds-ca-ecc384-g1</CertificateIdentifier>"))
.body(containsString("<CustomerOverride>true</CustomerOverride><CustomerOverrideValidTill>"));
query("DescribeCertificates")
.when().post("/").then().statusCode(200)
.body(containsString("<DefaultCertificateForNewLaunches>rds-ca-ecc384-g1"
+ "</DefaultCertificateForNewLaunches>"));
createInstance("ca-default-db")
.when().post("/").then().statusCode(200)
.body(containsString("<CACertificateIdentifier>rds-ca-ecc384-g1</CACertificateIdentifier>"
+ "<CertificateDetails><CAIdentifier>rds-ca-ecc384-g1</CAIdentifier><ValidTill>"));
query("ModifyCertificates").formParam("RemoveCustomerOverride", "true")
.when().post("/").then().statusCode(200)
.body(containsString("<CustomerOverride>false</CustomerOverride>"));
query("ModifyCertificates")
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterCombination"));
}
@Test
@Order(3)
void anInstanceNamesItsCaAndChangesIt() {
createInstance("ca-named-db").formParam("CACertificateIdentifier", "rds-ca-rsa4096-g1")
.when().post("/").then().statusCode(200)
.body(containsString("<CACertificateIdentifier>rds-ca-rsa4096-g1</CACertificateIdentifier>"));
createInstance("ca-refused-db").formParam("CACertificateIdentifier", "rds-ca-2019")
.when().post("/").then().statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
query("ModifyDBInstance").formParam("DBInstanceIdentifier", "ca-named-db")
.formParam("CACertificateIdentifier", "rds-ca-rsa2048-g1")
.formParam("CertificateRotationRestart", "false")
.when().post("/").then().statusCode(200)
.body(containsString("<CACertificateIdentifier>rds-ca-rsa2048-g1</CACertificateIdentifier>"));
query("DescribeDBInstances").formParam("DBInstanceIdentifier", "ca-named-db")
.when().post("/").then().statusCode(200)
.body(containsString("<CertificateDetails><CAIdentifier>rds-ca-rsa2048-g1</CAIdentifier>"));
}
}
@@ -24,6 +24,8 @@ import io.github.hectorvent.floci.services.rds.model.EventSubscription;
import io.github.hectorvent.floci.services.rds.model.ExportTask;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
import io.github.hectorvent.floci.services.rds.model.PointInTimeRestoreRequest;
import io.github.hectorvent.floci.services.rds.model.ReadReplicaRequest;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
@@ -57,6 +59,8 @@ class RdsQueryHandlerTest {
@BeforeEach
void setUp() {
service = mock(RdsService.class);
when(service.instanceCertificate(any())).thenReturn(
new RdsService.InstanceCertificate("rds-ca-rsa2048-g1", Instant.parse("2061-05-25T23:34:57Z")));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.RdsServiceConfig rdsConfig = mock(EmulatorConfig.RdsServiceConfig.class);
@@ -269,6 +273,46 @@ class RdsQueryHandlerTest {
assertEquals(enabled, settings.getValue().performanceInsightsEnabled());
}
/** Each action that takes CACertificateIdentifier hands it to the service as sent. */
@Test
void caCertificateIdentifierReachesTheServiceFromEveryActionThatTakesIt() {
ArgumentCaptor<DbInstanceSettings> created = ArgumentCaptor.forClass(DbInstanceSettings.class);
when(service.createDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(),
any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), any(), any(), any(),
anyBoolean(), created.capture(), any(), any(), any())).thenReturn(makeInstance("mydb"));
ArgumentCaptor<DbInstanceSettings> modified = ArgumentCaptor.forClass(DbInstanceSettings.class);
when(service.modifyDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), any(),
modified.capture(), any(), any(DbInstanceScalingChanges.class), any(), any()))
.thenReturn(makeInstance("mydb"));
when(service.restoreDbInstanceFromDbSnapshot(any(), any(), any(), any(), anyBoolean(), any(), any(), any(),
any(), any(), any(), any(), eq("rds-ca-ecc384-g1"))).thenReturn(makeInstance("restored"));
ArgumentCaptor<ReadReplicaRequest> replica = ArgumentCaptor.forClass(ReadReplicaRequest.class);
when(service.createDbInstanceReadReplica(replica.capture(), any())).thenReturn(makeInstance("replica"));
ArgumentCaptor<PointInTimeRestoreRequest> pitr = ArgumentCaptor.forClass(PointInTimeRestoreRequest.class);
when(service.restoreDbInstanceToPointInTime(pitr.capture(), any())).thenReturn(makeInstance("pitr"));
MultivaluedMap<String, String> p = params();
p.putSingle("DBInstanceIdentifier", "mydb");
p.putSingle("Engine", "postgres");
p.putSingle("CACertificateIdentifier", "rds-ca-rsa4096-g1");
assertEquals(200, handler.handle("CreateDBInstance", p).getStatus());
assertEquals("rds-ca-rsa4096-g1", created.getValue().caCertificateIdentifier());
p.putSingle("CACertificateIdentifier", "rds-ca-rsa2048-g1");
assertEquals(200, handler.handle("ModifyDBInstance", p).getStatus());
assertEquals("rds-ca-rsa2048-g1", modified.getValue().caCertificateIdentifier());
p.putSingle("DBSnapshotIdentifier", "snap");
p.putSingle("CACertificateIdentifier", "rds-ca-ecc384-g1");
assertEquals(200, handler.handle("RestoreDBInstanceFromDBSnapshot", p).getStatus());
p.putSingle("SourceDBInstanceIdentifier", "source");
assertEquals(200, handler.handle("CreateDBInstanceReadReplica", p).getStatus());
assertEquals("rds-ca-ecc384-g1", replica.getValue().caCertificateIdentifier());
p.putSingle("TargetDBInstanceIdentifier", "pitr");
p.putSingle("UseLatestRestorableTime", "true");
assertEquals(200, handler.handle("RestoreDBInstanceToPointInTime", p).getStatus());
assertEquals("rds-ca-ecc384-g1", pitr.getValue().caCertificateIdentifier());
}
@Test
void invalidAutoMinorVersionUpgradeIsRejectedBeforeCreateOrModify() {
for (String action : List.of("CreateDBInstance", "ModifyDBInstance")) {
@@ -2590,7 +2634,7 @@ class RdsQueryHandlerTest {
})
void restoreBooleanFlagsRejectMalformedValuesBeforeServiceCalls(String action, String parameter) {
when(service.restoreDbInstanceFromDbSnapshot(any(), any(), any(), any(), anyBoolean(),
any(), any(), any(), any(), any(), any(), isNull())).thenReturn(makeInstance("restored"));
any(), any(), any(), any(), any(), any(), isNull(), isNull())).thenReturn(makeInstance("restored"));
when(service.restoreDbClusterFromSnapshot(any(), any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any(), any())).thenReturn(makeCluster("restored"));
when(service.restoreDbClusterToPointInTime(any(), any(), any(), any(), any(), any(),
@@ -2621,10 +2665,10 @@ class RdsQueryHandlerTest {
void restoreInstanceSnapshotPreservesMultiAzValuesAndDefault(String value) {
boolean enabled = Boolean.parseBoolean(value);
when(service.restoreDbInstanceFromDbSnapshot(eq("restored"), eq("source"), isNull(), isNull(),
eq(enabled), isNull(), eq(List.of()), eq(Map.of()), isNull(), isNull(), isNull(), isNull()))
eq(enabled), isNull(), eq(List.of()), eq(Map.of()), isNull(), isNull(), isNull(), isNull(), isNull()))
.thenReturn(makeInstance("restored"));
when(service.restoreDbInstanceFromDbSnapshot(eq("restored"), eq("source"), isNull(), isNull(),
eq(enabled), isNull(), eq(List.of()), eq(Map.of()), isNull(), eq(5433), isNull(), isNull()))
eq(enabled), isNull(), eq(List.of()), eq(Map.of()), isNull(), eq(5433), isNull(), isNull(), isNull()))
.thenReturn(makeInstance("restored"));
MultivaluedMap<String, String> p = params();
p.putSingle("DBInstanceIdentifier", "restored");
@@ -2635,11 +2679,11 @@ class RdsQueryHandlerTest {
assertEquals(200, handler.handle("RestoreDBInstanceFromDBSnapshot", p).getStatus());
verify(service).restoreDbInstanceFromDbSnapshot("restored", "source", null, null,
enabled, null, List.of(), Map.of(), null, null, null, null);
enabled, null, List.of(), Map.of(), null, null, null, null, null);
p.putSingle("Port", "5433");
assertEquals(200, handler.handle("RestoreDBInstanceFromDBSnapshot", p).getStatus());
verify(service).restoreDbInstanceFromDbSnapshot("restored", "source", null, null,
enabled, null, List.of(), Map.of(), null, 5433, null, null);
enabled, null, List.of(), Map.of(), null, 5433, null, null, null);
}
@ParameterizedTest
@@ -2648,7 +2692,7 @@ class RdsQueryHandlerTest {
void restoreInstanceSnapshotForwardsIamFlagWithAndWithoutPort(String value) {
Boolean enabled = value == null ? null : Boolean.parseBoolean(value);
when(service.restoreDbInstanceFromDbSnapshot(any(), any(), any(), any(), anyBoolean(),
any(), any(), any(), any(), any(), eq(enabled), isNull())).thenReturn(makeInstance("restored"));
any(), any(), any(), any(), any(), eq(enabled), isNull(), isNull())).thenReturn(makeInstance("restored"));
MultivaluedMap<String, String> p = params();
p.putSingle("DBInstanceIdentifier", "restored");
p.putSingle("DBSnapshotIdentifier", "source");
@@ -2657,11 +2701,11 @@ class RdsQueryHandlerTest {
}
assertEquals(200, handler.handle("RestoreDBInstanceFromDBSnapshot", p).getStatus());
verify(service).restoreDbInstanceFromDbSnapshot("restored", "source", null, null,
false, null, List.of(), Map.of(), null, null, enabled, null);
false, null, List.of(), Map.of(), null, null, enabled, null, null);
p.putSingle("Port", "5433");
assertEquals(200, handler.handle("RestoreDBInstanceFromDBSnapshot", p).getStatus());
verify(service).restoreDbInstanceFromDbSnapshot("restored", "source", null, null,
false, null, List.of(), Map.of(), null, 5433, enabled, null);
false, null, List.of(), Map.of(), null, 5433, enabled, null, null);
}
@ParameterizedTest
@@ -2696,7 +2740,7 @@ class RdsQueryHandlerTest {
@Test
void restoreDbInstanceFromDbSnapshot_success() {
DbInstance instance = makeInstance("mydb");
when(service.restoreDbInstanceFromDbSnapshot(eq("mydb"), eq("mysnap"), eq("db.t3.large"), eq("us-east-1a"), eq(true), eq("my-subnets"), eq(List.of("sg-123")), eq(Map.of("Env", "Prod")), isNull(), isNull(), isNull(), isNull()))
when(service.restoreDbInstanceFromDbSnapshot(eq("mydb"), eq("mysnap"), eq("db.t3.large"), eq("us-east-1a"), eq(true), eq("my-subnets"), eq(List.of("sg-123")), eq(Map.of("Env", "Prod")), isNull(), isNull(), isNull(), isNull(), isNull()))
.thenReturn(instance);
MultivaluedMap<String, String> p = params();
@@ -10615,6 +10615,178 @@ class RdsServiceTest {
assertEquals("reader", rdsService.getDbCluster("aurora").resolveWriterIdentifier());
}
// ── Certificates ──────────────────────────────────────────────────────────
private DbInstance createInstanceWithCa(String id, String caCertificateIdentifier) {
return rdsService.createDbInstance(id, "postgres", "16.3", "admin", "password", "appdb", "db.t3.micro",
20, false, null, null, null, null, false, false, null, Map.of(), List.of(), null, "us-east-1",
true, DbInstanceSettings.defaults().withCaCertificateIdentifier(caCertificateIdentifier));
}
private static List<String> certificateIds(RdsService.CertificatePage page) {
return page.certificates().stream().map(RdsService.Certificate::certificateIdentifier).toList();
}
/** The values the AWS CLI reference's describe-certificates example gives for us-west-2. */
@Test
void certificatesAreTheRegionsCasAsAwsReportsThem() {
RdsService.CertificatePage page = rdsService.describeCertificates("us-west-2", null, null, null);
assertEquals(List.of("rds-ca-ecc384-g1", "rds-ca-rsa2048-g1", "rds-ca-rsa4096-g1"), certificateIds(page));
assertEquals("rds-ca-rsa2048-g1", page.defaultForNewLaunches());
assertNull(page.marker());
RdsService.Certificate rsa2048 = page.certificates().get(1);
assertEquals("7c40cb42714b6fdb2b296f9bbd0e8bb364436a76", rsa2048.thumbprint());
assertEquals(Instant.parse("2021-05-24T21:59:00Z"), rsa2048.validFrom());
assertEquals(Instant.parse("2061-05-24T22:59:00Z"), rsa2048.validTill());
assertEquals("arn:aws:rds:us-west-2::cert:rds-ca-rsa2048-g1", rsa2048.certificateArn());
assertFalse(rsa2048.customerOverride());
assertNull(rsa2048.customerOverrideValidTill());
assertEquals("2ee3dcc06e50192559b13929e73484354f23387d", page.certificates().get(0).thumbprint());
assertEquals("19da4f2af579a8ae1f6a0fa77aa5befd874b4cab", page.certificates().get(2).thumbprint());
// Each Region has its own CAs.
assertNotEquals(rsa2048.thumbprint(), rdsService.describeCertificates("us-east-1", null, null, null)
.certificates().get(1).thumbprint());
}
@Test
void certificatesFilterByIdentifierWithoutRegardToCaseAndPage() {
assertEquals(List.of("rds-ca-ecc384-g1"), certificateIds(
rdsService.describeCertificates("us-east-1", "RDS-CA-ECC384-G1", null, null)));
AwsException unknown = assertThrows(AwsException.class,
() -> rdsService.describeCertificates("us-east-1", "rds-ca-2019", null, null));
assertEquals("CertificateNotFound", unknown.getErrorCode());
assertEquals(404, unknown.getHttpStatus());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> rdsService.describeCertificates("us-east-1", null, 19, null)).getErrorCode());
assertEquals(List.of("rds-ca-rsa4096-g1"), certificateIds(
rdsService.describeCertificates("us-east-1", null, 20, "2")));
}
@Test
void aRegionWithoutVendoredCertificatesUsesUsEast1sUnderItsOwnArn() {
RdsService.Certificate custom = rdsService.describeCertificates("xx-custom-1", "rds-ca-rsa2048-g1", null,
null).certificates().get(0);
RdsService.Certificate usEast1 = rdsService.describeCertificates("us-east-1", "rds-ca-rsa2048-g1", null,
null).certificates().get(0);
assertEquals(usEast1.thumbprint(), custom.thumbprint());
assertEquals("arn:aws:rds:xx-custom-1::cert:rds-ca-rsa2048-g1", custom.certificateArn());
}
/** The user guide lists six Regions without rds-ca-rsa4096-g1 and rds-ca-ecc384-g1; Mumbai is one. */
@Test
void aRegionWithoutTheNewerCasOffersOnlyRsa2048() {
assertEquals(List.of("rds-ca-rsa2048-g1"),
certificateIds(rdsService.describeCertificates("ap-south-1", null, null, null)));
assertEquals("CertificateNotFound", assertThrows(AwsException.class,
() -> rdsService.describeCertificates("ap-south-1", "rds-ca-ecc384-g1", null, null)).getErrorCode());
assertEquals("CertificateNotFound", assertThrows(AwsException.class,
() -> rdsService.modifyCertificates("ap-south-1", "rds-ca-rsa4096-g1", null)).getErrorCode());
}
@Test
void modifyCertificatesSetsAndRemovesTheDefaultForNewInstances() {
RdsService.Certificate set = rdsService.modifyCertificates("us-east-1", "RDS-CA-ECC384-G1", null);
assertEquals("rds-ca-ecc384-g1", set.certificateIdentifier());
assertTrue(set.customerOverride());
assertEquals(set.validTill(), set.customerOverrideValidTill());
RdsService.CertificatePage page = rdsService.describeCertificates("us-east-1", null, null, null);
assertEquals("rds-ca-ecc384-g1", page.defaultForNewLaunches());
assertEquals(List.of(true, false, false),
page.certificates().stream().map(RdsService.Certificate::customerOverride).toList());
// The override is the account's in this Region only.
assertEquals("rds-ca-rsa2048-g1",
rdsService.describeCertificates("us-west-2", null, null, null).defaultForNewLaunches());
RdsService.Certificate removed = rdsService.modifyCertificates("us-east-1", null, true);
assertEquals("rds-ca-ecc384-g1", removed.certificateIdentifier());
assertFalse(removed.customerOverride());
assertEquals("rds-ca-rsa2048-g1",
rdsService.describeCertificates("us-east-1", null, null, null).defaultForNewLaunches());
for (Executable both : List.<Executable>of(
() -> rdsService.modifyCertificates("us-east-1", "rds-ca-rsa4096-g1", true),
() -> rdsService.modifyCertificates("us-east-1", null, null),
() -> rdsService.modifyCertificates("us-east-1", "", false))) {
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class, both).getErrorCode());
}
assertEquals("CertificateNotFound", assertThrows(AwsException.class,
() -> rdsService.modifyCertificates("us-east-1", "rds-ca-2015", null)).getErrorCode());
assertEquals("rds-ca-rsa2048-g1",
rdsService.describeCertificates("us-east-1", null, null, null).defaultForNewLaunches());
}
@Test
void anInstanceTakesItsCaOrTheAccountsDefaultAndCanChangeIt() {
assertEquals("rds-ca-rsa2048-g1", createInstanceWithCa("plain", null).getCaCertificateIdentifier());
rdsService.modifyCertificates("us-east-1", "rds-ca-ecc384-g1", null);
assertEquals("rds-ca-ecc384-g1", createInstanceWithCa("after-override", null).getCaCertificateIdentifier());
DbInstance explicit = createInstanceWithCa("explicit", "RDS-CA-RSA4096-G1");
assertEquals("rds-ca-rsa4096-g1", explicit.getCaCertificateIdentifier());
// The instance keeps the CA it was given when the default moves again.
rdsService.modifyCertificates("us-east-1", null, true);
assertEquals("rds-ca-ecc384-g1", rdsService.getDbInstance("after-override").getCaCertificateIdentifier());
RdsService.InstanceCertificate details = rdsService.instanceCertificate(explicit);
assertEquals("rds-ca-rsa4096-g1", details.caIdentifier());
assertEquals(rdsService.describeCertificates("us-east-1", "rds-ca-rsa4096-g1", null, null)
.certificates().get(0).validTill(), details.validTill());
AwsException unknown = assertThrows(AwsException.class, () -> createInstanceWithCa("refused", "rds-ca-2019"));
assertEquals("CertificateNotFound", unknown.getErrorCode());
assertEquals("DBInstanceNotFound", assertThrows(AwsException.class,
() -> rdsService.getDbInstance("refused")).getErrorCode());
DbInstanceSettings change = DbInstanceSettings.unchanged().withCaCertificateIdentifier("rds-ca-ecc384-g1");
assertEquals("rds-ca-ecc384-g1", rdsService.modifyDbInstance("plain", null, null, null, null, null,
"us-east-1", null, change).getCaCertificateIdentifier());
DbInstanceSettings bad = DbInstanceSettings.unchanged().withCaCertificateIdentifier("rds-ca-2019");
assertEquals("CertificateNotFound", assertThrows(AwsException.class, () -> rdsService.modifyDbInstance(
"plain", null, null, null, null, null, "us-east-1", null, bad)).getErrorCode());
assertEquals("rds-ca-ecc384-g1", rdsService.getDbInstance("plain").getCaCertificateIdentifier());
// A modify that leaves the CA out, or sends it blank, keeps it.
assertEquals("rds-ca-ecc384-g1", rdsService.modifyDbInstance("plain", null, true, null)
.getCaCertificateIdentifier());
DbInstanceSettings blank = DbInstanceSettings.unchanged().withCaCertificateIdentifier("");
assertEquals("rds-ca-ecc384-g1", rdsService.modifyDbInstance("plain", null, null, null, null, null,
"us-east-1", null, blank).getCaCertificateIdentifier());
}
@Test
void anInstanceStoredWithoutACaReportsRdsDefaultNotTheOverride() {
DbInstance legacy = createInstanceWithCa("legacy", null);
legacy.setCaCertificateIdentifier(null);
// An override applies only to instances created after it.
rdsService.modifyCertificates("us-east-1", "rds-ca-rsa4096-g1", null);
assertEquals("rds-ca-rsa2048-g1", rdsService.instanceCertificate(legacy).caIdentifier());
}
@Test
void restoresAndReplicasTakeACa() {
createPostgresSource("ca-source");
when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
rdsService.createDbSnapshot("ca-snapshot", "ca-source");
assertEquals("rds-ca-ecc384-g1", rdsService.restoreDbInstanceFromDbSnapshot("ca-restored", "ca-snapshot",
null, null, false, null, List.of(), Map.of(), "us-east-1", null, null, null, "rds-ca-ecc384-g1")
.getCaCertificateIdentifier());
assertEquals("rds-ca-rsa2048-g1", rdsService.restoreDbInstanceFromDbSnapshot("ca-default", "ca-snapshot",
null, null, false, null, List.of(), Map.of(), "us-east-1").getCaCertificateIdentifier());
assertEquals("CertificateNotFound", assertThrows(AwsException.class, () ->
rdsService.restoreDbInstanceFromDbSnapshot("ca-refused", "ca-snapshot", null, null, false, null,
List.of(), Map.of(), "us-east-1", null, null, null, "rds-ca-2019")).getErrorCode());
assertEquals("rds-ca-rsa4096-g1", rdsService.createDbInstanceReadReplica(new ReadReplicaRequest(
"ca-replica", "ca-source", null, null, null, null, null, null, null, null, null, null, null, null,
null, Map.of(), null, "rds-ca-rsa4096-g1"), null).getCaCertificateIdentifier());
assertEquals("rds-ca-ecc384-g1", rdsService.restoreDbInstanceToPointInTime(new PointInTimeRestoreRequest(
"ca-pitr", "ca-source", null, null, null, true, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, Map.of(), null, "rds-ca-ecc384-g1"), "us-east-1")
.getCaCertificateIdentifier());
}
// ── DB proxy endpoints ────────────────────────────────────────────────────
private DbProxy proxyForEndpoints(String name, String engineFamily) {
@@ -31,7 +31,7 @@ AWS::RDS::DBCluster ReadEndpoint ReadEndpoint.Address is set instead, the form A
AWS::RDS::DBCluster StorageEncryptionType cluster storage encryption is not emulated
AWS::RDS::DBCluster StorageThroughput provisioned storage throughput is not emulated
AWS::RDS::DBInstance AutomaticRestartTime instance restart scheduling is not emulated
AWS::RDS::DBInstance CertificateDetails per-instance CA certificate metadata is not emulated
AWS::RDS::DBInstance CertificateDetails the dotted CertificateDetails.CAIdentifier and CertificateDetails.ValidTill are set instead, the form AWS's GetAtt exposes for the nested object
AWS::RDS::DBInstance DBInstanceStatus the model carries no lifecycle status; instances reach available synchronously
AWS::RDS::DBInstance InstanceCreateTime creation timestamps are not recorded on the instance
AWS::RDS::DBInstance IsStorageConfigUpgradeAvailable storage configuration upgrades are not emulated
Can't render this file because it contains an unexpected character in line 6 and column 144.
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""Regenerate src/main/resources/aws/rds-ca-certificates.json from the RDS certificate bundles AWS publishes.
`DescribeCertificates` reports, for each RDS certificate authority in a Region, a SHA-1
`Thumbprint` and its `ValidFrom` and `ValidTill`. Those are the SHA-1 fingerprint and validity of
the Region's root CA certificate in the bundle AWS publishes for that Region: the us-west-2 example
in the AWS CLI reference for `describe-certificates` matches the root certificates of
`us-west-2-bundle.pem` exactly, for all three CAs. The CA's identifier follows from the root's
common name, `Amazon RDS <region> Root CA <RSA2048|RSA4096|ECC384> G1`, as
`rds-ca-<rsa2048|rsa4096|ecc384>-g1`.
The bundles are read from `local/aws/rds-truststore/<region>-bundle.pem`, one per Region of the
`aws` partition in `partitions.json`. AWS serves them at
https://truststore.pki.rds.amazonaws.com/<region>/<region>-bundle.pem
and `--download` saves them there; a Region AWS serves no bundle for is left out. Other partitions
are left out: the one GovCloud thumbprint AWS shows (re:Post, us-gov-east-1) is not its root's.
The user guide ("Certificate bundles by AWS Region", UsingWithRDS.SSL.html) says rds-ca-rsa4096-g1
and rds-ca-ecc384-g1 are not available in six Regions, though their bundles carry those roots. For
those Regions only rds-ca-rsa2048-g1 is kept.
Run from anywhere in the repo:
python3 tools/aws/regen_rds_ca_certificates.py --download # fetch the bundles into local/aws
python3 tools/aws/regen_rds_ca_certificates.py # rewrite the vendored file in place
python3 tools/aws/regen_rds_ca_certificates.py --check # exit 1 when the vendored file is stale
Without the bundles, `--check` verifies the vendored file's shape only.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import re
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from request_shapes import REPO_ROOT
OUTPUT = REPO_ROOT / "src/main/resources/aws/rds-ca-certificates.json"
PARTITIONS = REPO_ROOT / "src/main/resources/aws/partitions.json"
LOCAL_BUNDLES = REPO_ROOT / "local/aws/rds-truststore"
BUNDLE_URL = "https://truststore.pki.rds.amazonaws.com/{region}/{region}-bundle.pem"
ROOT_CN = re.compile(r"Amazon RDS (?P<region>[a-z0-9-]+) Root CA (?P<kind>RSA2048|RSA4096|ECC384) G1")
PEM = re.compile(r"-----BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE-----", re.S)
COMMON_NAME_OID = bytes([0x55, 0x04, 0x03])
IDENTIFIER = re.compile(r"rds-ca-(rsa2048|rsa4096|ecc384)-g1")
INSTANT = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z")
DEFAULT_CA = "rds-ca-rsa2048-g1"
# Mumbai, Melbourne, Calgary, Zurich, Spain and Tel Aviv, as the user guide lists them.
RSA2048_ONLY = frozenset({"ap-south-1", "ap-southeast-4", "ca-west-1", "eu-central-2", "eu-south-2",
"il-central-1"})
# What the truststore answers for a Region it serves no bundle for.
NO_BUNDLE = frozenset({403, 404})
def _tlv(data: bytes, offset: int) -> tuple[int, int, int]:
"""The tag, the content's start and the content's end of the DER element at `offset`."""
tag = data[offset]
length = data[offset + 1]
start = offset + 2
if length & 0x80:
count = length & 0x7F
length = int.from_bytes(data[start:start + count], "big")
start += count
return tag, start, start + length
def _children(data: bytes, start: int, end: int) -> list[tuple[int, int, int]]:
out = []
while start < end:
tag, content, stop = _tlv(data, start)
out.append((tag, content, stop))
start = stop
return out
def _time(data: bytes, tag: int, start: int, end: int) -> str:
text = data[start:end].decode("ascii")
parsed = datetime.strptime(text, "%y%m%d%H%M%SZ" if tag == 0x17 else "%Y%m%d%H%M%SZ")
return parsed.replace(tzinfo=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _common_name(data: bytes, start: int, end: int) -> str | None:
for _, rdn_start, rdn_end in _children(data, start, end):
for _, atv_start, atv_end in _children(data, rdn_start, rdn_end):
(_, oid_start, oid_end), (_, value_start, value_end) = _children(data, atv_start, atv_end)[:2]
if data[oid_start:oid_end] == COMMON_NAME_OID:
return data[value_start:value_end].decode("utf-8")
return None
def read_certificate(der: bytes) -> dict:
"""The subject common name, validity and SHA-1 fingerprint of one DER certificate."""
_, cert_start, cert_end = _tlv(der, 0)
_, tbs_start, tbs_end = _children(der, cert_start, cert_end)[0]
fields = _children(der, tbs_start, tbs_end)
if fields[0][0] == 0xA0: # the explicit version
fields = fields[1:]
# serialNumber, signature, issuer, validity, subject
_, validity_start, validity_end = fields[3]
(nb_tag, nb_start, nb_end), (na_tag, na_start, na_end) = _children(der, validity_start, validity_end)
_, subject_start, subject_end = fields[4]
return {
"commonName": _common_name(der, subject_start, subject_end),
"validFrom": _time(der, nb_tag, nb_start, nb_end),
"validTill": _time(der, na_tag, na_start, na_end),
"thumbprint": hashlib.sha1(der).hexdigest(),
}
def certificates_in(pem_text: str, region: str) -> list[dict]:
"""The bundle's root CAs for `region`, by identifier."""
found = []
for block in PEM.findall(pem_text):
cert = read_certificate(base64.b64decode("".join(block.split())))
match = ROOT_CN.fullmatch(cert["commonName"] or "")
if match and match.group("region") == region:
found.append({
"certificateIdentifier": f"rds-ca-{match.group('kind').lower()}-g1",
"thumbprint": cert["thumbprint"],
"validFrom": cert["validFrom"],
"validTill": cert["validTill"],
})
return sorted(found, key=lambda c: c["certificateIdentifier"])
def offered_in(region: str, certificates: list[dict]) -> list[dict]:
"""The CAs RDS offers in `region`, which is fewer than its bundle carries in RSA2048_ONLY."""
if region in RSA2048_ONLY:
return [c for c in certificates if c["certificateIdentifier"] == DEFAULT_CA]
return certificates
def commercial_regions(partitions: Path) -> list[str]:
doc = json.loads(partitions.read_text(encoding="utf-8"))
aws = next(p for p in doc["partitions"] if p["id"] == "aws")
return sorted(r["id"] for r in aws["regions"])
def build(bundles: Path, partitions: Path) -> dict:
regions = {}
for region in commercial_regions(partitions):
path = bundles / f"{region}-bundle.pem"
if path.exists():
certificates = offered_in(region, certificates_in(path.read_text(encoding="utf-8"), region))
if certificates:
regions[region] = certificates
return {
"_source": {
"generator": "tools/aws/regen_rds_ca_certificates.py",
"bundles": BUNDLE_URL,
},
"regions": regions,
}
def download(bundles: Path, partitions: Path) -> list[str]:
"""Saves each Region's bundle and returns the Regions that failed for a reason other than having none."""
bundles.mkdir(parents=True, exist_ok=True)
failed = []
for region in commercial_regions(partitions):
try:
with urllib.request.urlopen(BUNDLE_URL.format(region=region), timeout=30) as response:
(bundles / f"{region}-bundle.pem").write_bytes(response.read())
print(f"saved {region}")
except urllib.error.HTTPError as e:
if e.code in NO_BUNDLE:
print(f"skipped {region}: HTTP {e.code}, no bundle published")
else:
print(f"failed {region}: HTTP {e.code}", file=sys.stderr)
failed.append(region)
except OSError as e: # URLError, a timeout or a refused connection
print(f"failed {region}: {e}", file=sys.stderr)
failed.append(region)
return failed
def self_check(output: Path) -> list[str]:
"""What a stale-proof check can say without the bundles: the file parses and keeps its shape."""
try:
doc = json.loads(output.read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
return [f"cannot read {output}: {e}"]
problems = []
regions = doc.get("regions")
if not isinstance(regions, dict) or "us-east-1" not in regions:
return ["regions must be an object that includes us-east-1"]
for region, certificates in regions.items():
identifiers = [c.get("certificateIdentifier") for c in certificates]
if DEFAULT_CA not in identifiers:
problems.append(f"{region}: no {DEFAULT_CA}")
if region in RSA2048_ONLY and identifiers != [DEFAULT_CA]:
problems.append(f"{region}: offers only {DEFAULT_CA}")
for c in certificates:
if not IDENTIFIER.fullmatch(str(c.get("certificateIdentifier"))):
problems.append(f"{region}: bad identifier {c.get('certificateIdentifier')!r}")
if not re.fullmatch(r"[0-9a-f]{40}", str(c.get("thumbprint"))):
problems.append(f"{region}: bad thumbprint for {c.get('certificateIdentifier')}")
if not (INSTANT.fullmatch(str(c.get("validFrom"))) and INSTANT.fullmatch(str(c.get("validTill")))):
problems.append(f"{region}: bad validity for {c.get('certificateIdentifier')}")
return problems
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
parser.add_argument("--download", action="store_true", help="fetch the Region bundles into --bundles and exit")
parser.add_argument("--bundles", type=Path, default=LOCAL_BUNDLES, help="directory of <region>-bundle.pem files")
parser.add_argument("--partitions", type=Path, default=PARTITIONS, help="vendored partitions.json")
parser.add_argument("--output", type=Path, default=OUTPUT, help="vendored file to write or check")
args = parser.parse_args(argv)
if args.download:
failed = download(args.bundles, args.partitions)
if failed:
print(f"error: no bundle saved for {', '.join(failed)}; run --download again", file=sys.stderr)
return 1
return 0
rel = args.output.relative_to(REPO_ROOT) if args.output.is_relative_to(REPO_ROOT) else args.output
if not (args.bundles / "us-east-1-bundle.pem").exists():
if args.check:
problems = self_check(args.output)
for problem in problems:
print(f"{rel}: {problem}", file=sys.stderr)
if not problems:
print(f"{rel}: bundles not downloaded, shape verified only")
return 1 if problems else 0
raise SystemExit("error: regenerating needs the bundles under local/aws/rds-truststore; run with --download")
fresh = json.dumps(build(args.bundles, args.partitions), indent=2) + "\n"
if args.check:
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
if current != fresh:
print(f"{rel} is out of date", file=sys.stderr)
return 1
print(f"{rel} is up to date")
return 0
args.output.write_text(fresh, encoding="utf-8")
print(f"wrote {rel} for {len(json.loads(fresh)['regions'])} Regions")
return 0
if __name__ == "__main__":
sys.exit(main())
+147
View File
@@ -0,0 +1,147 @@
"""Tests for regen_rds_ca_certificates.
Run with: pytest tools/aws -q (or: make aws-data-test)
"""
from __future__ import annotations
import json
from pathlib import Path
import regen_rds_ca_certificates as r
# The us-west-2 ECC384 root from AWS's us-west-2-bundle.pem. The AWS CLI reference's
# describe-certificates example gives this CA thumbprint 2ee3dcc06e50192559b13929e73484354f23387d,
# ValidFrom 2021-05-24T22:06:59 and ValidTill 2121-05-24T23:06:59.
US_WEST_2_ECC384 = """
-----BEGIN CERTIFICATE-----
MIICrjCCAjSgAwIBAgIRAOxu0I1QuMAhIeszB3fJIlkwCgYIKoZIzj0EAwMwgZYx
CzAJBgNVBAYTAlVTMSIwIAYDVQQKDBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMu
MRMwEQYDVQQLDApBbWF6b24gUkRTMQswCQYDVQQIDAJXQTEvMC0GA1UEAwwmQW1h
em9uIFJEUyB1cy13ZXN0LTIgUm9vdCBDQSBFQ0MzODQgRzExEDAOBgNVBAcMB1Nl
YXR0bGUwIBcNMjEwNTI0MjIwNjU5WhgPMjEyMTA1MjQyMzA2NTlaMIGWMQswCQYD
VQQGEwJVUzEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNlcywgSW5jLjETMBEG
A1UECwwKQW1hem9uIFJEUzELMAkGA1UECAwCV0ExLzAtBgNVBAMMJkFtYXpvbiBS
RFMgdXMtd2VzdC0yIFJvb3QgQ0EgRUNDMzg0IEcxMRAwDgYDVQQHDAdTZWF0dGxl
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEz4bylRcGqqDWdP7gQIIoTHdBK6FNtKH1
4SkEIXRXkYDmRvL9Bci1MuGrwuvrka5TDj4b7e+csY0llEzHpKfq6nJPFljoYYP9
uqHFkv77nOpJJ633KOr8IxmeHW5RXgrZo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0G
A1UdDgQWBBQQikVz8wmjd9eDFRXzBIU8OseiGzAOBgNVHQ8BAf8EBAMCAYYwCgYI
KoZIzj0EAwMDaAAwZQIwf06Mcrpw1O0EBLBBrp84m37NYtOkE/0Z0O+C7D41wnXi
EQdn6PXUVgdD23Gj82SrAjEAklhKs+liO1PtN15yeZR1Io98nFve+lLptaLakZcH
+hfFuUtCqMbaI8CdvJlKnPqT
-----END CERTIFICATE-----
"""
def partitions(tmp_path: Path, regions: list[str]) -> Path:
path = tmp_path / "partitions.json"
path.write_text(json.dumps({"partitions": [
{"id": "aws", "regions": [{"id": region} for region in regions]},
{"id": "aws-us-gov", "regions": [{"id": "us-gov-west-1"}]},
]}), encoding="utf-8")
return path
def test_a_root_reads_as_the_cli_reference_reports_it():
assert r.certificates_in(US_WEST_2_ECC384, "us-west-2") == [{
"certificateIdentifier": "rds-ca-ecc384-g1",
"thumbprint": "2ee3dcc06e50192559b13929e73484354f23387d",
"validFrom": "2021-05-24T22:06:59Z",
"validTill": "2121-05-24T23:06:59Z",
}]
def test_a_root_named_for_another_region_is_left_out():
assert r.certificates_in(US_WEST_2_ECC384, "us-east-1") == []
def test_build_takes_the_aws_partition_regions_that_have_a_bundle(tmp_path):
bundles = tmp_path / "bundles"
bundles.mkdir()
(bundles / "us-west-2-bundle.pem").write_text(US_WEST_2_ECC384, encoding="utf-8")
(bundles / "us-gov-west-1-bundle.pem").write_text(US_WEST_2_ECC384, encoding="utf-8")
doc = r.build(bundles, partitions(tmp_path, ["us-east-1", "us-west-2"]))
assert list(doc["regions"]) == ["us-west-2"]
assert doc["_source"]["generator"] == "tools/aws/regen_rds_ca_certificates.py"
def test_check_reports_a_stale_file(tmp_path, capsys):
bundles = tmp_path / "bundles"
bundles.mkdir()
(bundles / "us-east-1-bundle.pem").write_text(US_WEST_2_ECC384, encoding="utf-8")
(bundles / "us-west-2-bundle.pem").write_text(US_WEST_2_ECC384, encoding="utf-8")
output = tmp_path / "out.json"
args = ["--bundles", str(bundles), "--partitions", str(partitions(tmp_path, ["us-east-1", "us-west-2"])),
"--output", str(output)]
assert r.main(args) == 0
assert r.main(args + ["--check"]) == 0
output.write_text("{}", encoding="utf-8")
assert r.main(args + ["--check"]) == 1
assert "out of date" in capsys.readouterr().err
def test_without_bundles_the_check_verifies_the_shape(tmp_path):
output = tmp_path / "out.json"
entry = {"certificateIdentifier": "rds-ca-rsa2048-g1", "thumbprint": "a" * 40,
"validFrom": "2021-05-25T22:34:57Z", "validTill": "2061-05-25T23:34:57Z"}
output.write_text(json.dumps({"regions": {"us-east-1": [entry]}}), encoding="utf-8")
args = ["--bundles", str(tmp_path / "none"), "--output", str(output), "--check"]
assert r.main(args) == 0
assert r.self_check(output) == []
for broken in ({"regions": {"eu-west-1": [entry]}},
{"regions": {"us-east-1": [dict(entry, certificateIdentifier="rds-ca-2019")]}},
{"regions": {"us-east-1": [entry, dict(entry, certificateIdentifier="rds-ca-ecc384-g1",
thumbprint="XYZ")]}},
{"regions": {"us-east-1": [dict(entry, validTill="2061-05-25")]}}):
output.write_text(json.dumps(broken), encoding="utf-8")
assert r.self_check(output), broken
assert r.main(args) == 1
def test_the_vendored_file_keeps_its_shape():
assert r.self_check(r.OUTPUT) == []
def test_the_six_regions_the_user_guide_names_offer_only_rsa2048():
def ca(identifier):
return {"certificateIdentifier": identifier, "thumbprint": "a" * 40,
"validFrom": "2021-05-25T22:34:57Z", "validTill": "2061-05-25T23:34:57Z"}
bundle = [ca("rds-ca-ecc384-g1"), ca("rds-ca-rsa2048-g1"), ca("rds-ca-rsa4096-g1")]
assert r.RSA2048_ONLY == {"ap-south-1", "ap-southeast-4", "ca-west-1", "eu-central-2", "eu-south-2",
"il-central-1"}
for region in r.RSA2048_ONLY:
assert r.offered_in(region, bundle) == [ca("rds-ca-rsa2048-g1")]
assert r.offered_in("us-west-2", bundle) == bundle
def test_the_shape_check_refuses_another_ca_in_the_six_regions(tmp_path):
output = tmp_path / "out.json"
entry = {"certificateIdentifier": "rds-ca-rsa2048-g1", "thumbprint": "a" * 40,
"validFrom": "2021-05-25T22:34:57Z", "validTill": "2061-05-25T23:34:57Z"}
output.write_text(json.dumps({"regions": {"us-east-1": [entry], "ap-south-1": [
entry, dict(entry, certificateIdentifier="rds-ca-ecc384-g1")]}}), encoding="utf-8")
assert r.self_check(output) == ["ap-south-1: offers only rds-ca-rsa2048-g1"]
def test_download_skips_a_region_with_no_bundle_and_fails_on_anything_else(tmp_path, monkeypatch, capsys):
import io
import urllib.error
def urlopen(url, timeout):
if "/us-east-1/" in url:
return io.BytesIO(US_WEST_2_ECC384.encode())
if "/us-west-1/" in url:
raise urllib.error.HTTPError(url, 404, "Not Found", {}, None)
if "/us-west-2/" in url:
raise urllib.error.HTTPError(url, 503, "Service Unavailable", {}, None)
raise urllib.error.URLError("name resolution failed")
monkeypatch.setattr(r.urllib.request, "urlopen", urlopen)
bundles = tmp_path / "bundles"
regions = partitions(tmp_path, ["us-east-1", "us-west-1", "us-west-2", "eu-west-1"])
assert r.download(bundles, regions) == ["eu-west-1", "us-west-2"]
assert sorted(p.name for p in bundles.iterdir()) == ["us-east-1-bundle.pem"]
assert r.main(["--download", "--bundles", str(bundles), "--partitions", str(regions)]) == 1
assert "no bundle saved for eu-west-1, us-west-2" in capsys.readouterr().err