feat(docdb): support cluster snapshots and restores (#7585)

Adds CreateDBClusterSnapshot, DeleteDBClusterSnapshot, RestoreDBClusterFromSnapshot and RestoreDBClusterToPointInTime, and makes DescribeDBClusterSnapshots list stored snapshots. A snapshot is a mongodump archive of the cluster's MongoDB container; rds-signed requests naming a DocumentDB cluster or snapshot are routed to DocumentDB.

fix(docdb): round out cluster snapshots and restores after review

List DocumentDB snapshots in the RDS-family list form on either endpoint, accept snapshot ARNs, keep the source's encryption and key on restore, check restore and snapshot identifiers against RDS too, read a point-in-time restore's data as a snapshot does, refuse RestoreToTime, apply every describe filter, and remove a cluster whose restore failed even under deletion protection. Drop the unrelated endpoint host, container-name host and audit log group changes. Cover the archive reaching the restored cluster outside mock mode.

Read a snapshot's record and archive together under the snapshot lock delete takes, and refuse a restore whose archive is missing or empty before any cluster exists; a snapshot taken in mock mode is marked metadata-only and restores only in mock mode. A KmsKeyId on RestoreDBClusterFromSnapshot now encrypts the restored cluster under that key even when the snapshot is unencrypted, as the restore guide allows; the point-in-time restore still refuses one for an unencrypted source. Share the docdb-scoped request in the integration test.
This commit is contained in:
jibin-jusdb authored and GitHub committed 2026-11-07 09:58:08 -04:00
1 parent 5fe30ee5eb
commit 46a8cbe51d
13 files changed
+1260 -19

No files matched your search

+6 -2
View File
@@ -21,7 +21,11 @@ The management API shares the RDS Query endpoint (`POST /` with an `Action=` par
| --- | --- |
| `CreateDBCluster` | Create a DocumentDB cluster and start a MongoDB container |
| `DescribeDBClusters` | List clusters and their connection details |
| `DescribeDBClusterSnapshots` | Return an empty cluster-snapshot list (snapshots are not modeled) |
| `DescribeDBClusterSnapshots` | List manual cluster snapshots matching every one of `DBClusterSnapshotIdentifier` (an identifier or an ARN), `DBClusterIdentifier` (or the `db-cluster-id` filter) and `SnapshotType`. The list form, without an identifier, answers for the whole RDS family on the RDS and DocumentDB endpoints alike |
| `CreateDBClusterSnapshot` | Take a manual snapshot: a `mongodump` archive of the cluster's MongoDB container, `available` as soon as the call returns. The identifier is refused when an RDS or DocumentDB cluster snapshot already holds it |
| `DeleteDBClusterSnapshot` | Delete a manual snapshot, named by identifier or ARN, and its archive |
| `RestoreDBClusterFromSnapshot` | Create a new cluster holding the snapshot's data and master user, from a snapshot named by identifier or ARN. As on AWS it has no instances; add them with `CreateDBInstance`. It is encrypted when the snapshot is, with the snapshot's key, or under `KmsKeyId` when the request names one, which encrypts an unencrypted snapshot's restore as the restore guide allows. A snapshot whose archive is missing is refused with `InvalidDBClusterSnapshotStateFault` |
| `RestoreDBClusterToPointInTime` | Create a new cluster holding the source cluster's data as it is now, its latest restorable time, read as `CreateDBClusterSnapshot` reads it. Needs `UseLatestRestorableTime=true`; a `RestoreToTime` is refused. Encryption follows the source; a `KmsKeyId` for an unencrypted source is refused |
| `DescribeGlobalClusters` | List global clusters — always empty, as none are modeled |
| `DeleteDBCluster` | Stop and remove a cluster (must have no instances) |
| `ModifyDBCluster` | Update engine version or IAM auth setting |
@@ -156,6 +160,6 @@ print(cluster["DBCluster"]["Endpoint"])
- IAM database authentication for MongoDB connections (the flag is stored and echoed back, but connections are not SigV4-proxied).
- TLS / `--tls` enforced connections.
- Snapshot and restore operations.
- Automated snapshots, `CopyDBClusterSnapshot`, and restoring to a time other than the latest restorable time.
- Global clusters, replicas, and read-scaling beyond a single MongoDB container per cluster.
- Parameter groups, subnet groups, and maintenance windows.
+1 -1
View File
@@ -77,7 +77,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 135 |
| [Lake Formation](lakeformation.md) | `POST /<Action>` | REST JSON | 16 |
| [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 |
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 13 |
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 |
| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 |
| [QuickSight](quicksight.md) | `/accounts/{AwsAccountId}/...` | REST JSON, metadata only | 16 |
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 55 |
@@ -211,6 +211,11 @@ public class AwsQueryController {
if ("docdb".equalsIgnoreCase(engine)
|| docDbService.hasCluster(clusterId, region)
|| docDbService.hasInstance(instanceId, region)
|| docDbService.hasCluster(formParams.getFirst("SourceDBClusterIdentifier"), region)
// A create names the snapshot it makes, not one that exists: it follows its cluster.
|| (!"CreateDBClusterSnapshot".equals(action)
&& docDbService.hasClusterSnapshot(formParams.getFirst("DBClusterSnapshotIdentifier"), region))
|| docDbService.hasClusterSnapshot(formParams.getFirst("SnapshotIdentifier"), region)
|| namesDocDbResource(formParams.getFirst("ResourceName"), region)) {
yield docDbQueryHandler.handle(action, formParams);
}
@@ -300,7 +305,9 @@ public class AwsQueryController {
* check has to run on every route that reaches DocumentDB, not only the {@code rds} scope.
*
* <p>Only the identifier being created is checked: {@code CreateDBInstance} names its parent
* cluster too, and that cluster existing in RDS is the normal case rather than a clash.
* cluster too, and that cluster existing in RDS is the normal case rather than a clash. The
* restores create a cluster and {@code CreateDBClusterSnapshot} a snapshot, so those identifiers
* are checked against both stores, which share one cluster and cluster-snapshot ARN space.
*/
private Response rdsAlreadyHoldsIdentifier(String action,
MultivaluedMap<String, String> formParams,
@@ -313,6 +320,19 @@ public class AwsQueryController {
null, formParams.getFirst("DBInstanceIdentifier"), region)) {
return xmlErrorResponse("DBInstanceAlreadyExists", "DB Instance already exists", 400);
}
if ("RestoreDBClusterFromSnapshot".equals(action) || "RestoreDBClusterToPointInTime".equals(action)) {
String clusterId = formParams.getFirst("DBClusterIdentifier");
if (rdsService.hasClusterOrInstance(clusterId, null, region) || docDbService.hasCluster(clusterId, region)) {
return xmlErrorResponse("DBClusterAlreadyExistsFault", "DB Cluster already exists", 400);
}
}
if ("CreateDBClusterSnapshot".equals(action)) {
String snapshotId = formParams.getFirst("DBClusterSnapshotIdentifier");
if (rdsService.hasClusterSnapshot(snapshotId, region) || docDbService.hasClusterSnapshot(snapshotId, region)) {
return xmlErrorResponse("DBClusterSnapshotAlreadyExistsFault",
"DB cluster snapshot " + snapshotId + " already exists.", 400);
}
}
return null;
}
@@ -336,6 +356,8 @@ public class AwsQueryController {
return switch (action) {
case "DescribeDBClusters" -> isBlank(formParams.getFirst("DBClusterIdentifier"));
case "DescribeDBInstances" -> isBlank(formParams.getFirst("DBInstanceIdentifier"));
case "DescribeDBClusterSnapshots" -> isBlank(formParams.getFirst("DBClusterSnapshotIdentifier"))
&& isBlank(formParams.getFirst("DBClusterIdentifier"));
default -> false;
};
}
@@ -9,6 +9,7 @@ import io.floci.aws.core.common.RdsFamilyQuerySupport;
import io.floci.aws.core.common.XmlBuilder;
import io.floci.aws.services.docdb.model.DocDbCluster;
import io.floci.aws.services.docdb.model.DocDbClusterSettings;
import io.floci.aws.services.docdb.model.DocDbClusterSnapshot;
import io.floci.aws.services.docdb.model.DocDbInstance;
import io.floci.aws.services.docdb.model.DocDbInstanceSettings;
import jakarta.enterprise.context.ApplicationScoped;
@@ -44,6 +45,10 @@ public class DocDbQueryHandler {
case "CreateDBCluster" -> handleCreateDbCluster(params);
case "DescribeDBClusters" -> handleDescribeDbClusters(params);
case "DescribeDBClusterSnapshots" -> handleDescribeDbClusterSnapshots(params);
case "CreateDBClusterSnapshot" -> handleCreateDbClusterSnapshot(params);
case "DeleteDBClusterSnapshot" -> handleDeleteDbClusterSnapshot(params);
case "RestoreDBClusterFromSnapshot" -> handleRestoreDbClusterFromSnapshot(params);
case "RestoreDBClusterToPointInTime" -> handleRestoreDbClusterToPointInTime(params);
case "DescribeGlobalClusters" -> handleDescribeGlobalClusters(params);
case "DeleteDBCluster" -> handleDeleteDbCluster(params);
case "ModifyDBCluster" -> handleModifyDbCluster(params);
@@ -120,6 +125,16 @@ public class DocDbQueryHandler {
return service.listDbClusters(filterId).stream().map(this::clusterInnerXml).toList();
}
/**
* The rows the list form of DescribeDBClusterSnapshots would return, for the RDS-family listing
* {@code RdsQueryHandler} assembles: a live account lists DocumentDB cluster snapshots from the
* RDS endpoint too.
*/
public List<String> clusterSnapshotRowsXml(String clusterId, String snapshotType) {
return service.describeDbClusterSnapshots(null, clusterId, snapshotType).stream()
.map(this::snapshotInnerXml).toList();
}
public List<String> instanceRowsXml(String filterId) {
return service.listDbInstances(filterId).stream().map(this::instanceInnerXml).toList();
}
@@ -129,13 +144,104 @@ public class DocDbQueryHandler {
}
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params) {
// Snapshots are not modeled by the emulator; return the wire-accurate empty result
// the DocDB/RDS Query API uses (empty <DBClusterSnapshots/>, no <Marker>) so SDK
// clients complete the read instead of failing on an unsupported action.
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshots").end("DBClusterSnapshots");
String clusterId = params.getFirst("DBClusterIdentifier");
if (clusterId == null || clusterId.isBlank()) {
clusterId = extractFilterValue(params, "db-cluster-id");
}
List<DocDbClusterSnapshot> found = service.describeDbClusterSnapshots(
params.getFirst("DBClusterSnapshotIdentifier"), clusterId, params.getFirst("SnapshotType"));
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshots");
for (DocDbClusterSnapshot snapshot : found) {
xml.start("DBClusterSnapshot").raw(snapshotInnerXml(snapshot)).end("DBClusterSnapshot");
}
xml.end("DBClusterSnapshots");
return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterSnapshots", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleCreateDbClusterSnapshot(MultivaluedMap<String, String> params) {
DocDbClusterSnapshot snapshot = service.createDbClusterSnapshot(
params.getFirst("DBClusterSnapshotIdentifier"), params.getFirst("DBClusterIdentifier"),
parseTags(params));
return Response.ok(AwsQueryResponse.envelope("CreateDBClusterSnapshot", AwsNamespaces.RDS,
snapshotXml(snapshot))).build();
}
private Response handleDeleteDbClusterSnapshot(MultivaluedMap<String, String> params) {
DocDbClusterSnapshot snapshot = service.deleteDbClusterSnapshot(params.getFirst("DBClusterSnapshotIdentifier"));
return Response.ok(AwsQueryResponse.envelope("DeleteDBClusterSnapshot", AwsNamespaces.RDS,
snapshotXml(snapshot))).build();
}
private Response handleRestoreDbClusterFromSnapshot(MultivaluedMap<String, String> params) {
String id = params.getFirst("DBClusterIdentifier");
String snapshotId = params.getFirst("SnapshotIdentifier");
if (id == null || id.isBlank() || snapshotId == null || snapshotId.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue",
"DBClusterIdentifier and SnapshotIdentifier are required.", AwsNamespaces.RDS, 400);
}
DocDbCluster cluster = service.restoreDbClusterFromSnapshot(id, snapshotId,
params.getFirst("EngineVersion"), clusterSettings(params, true), parseTags(params));
return Response.ok(AwsQueryResponse.envelope("RestoreDBClusterFromSnapshot", AwsNamespaces.RDS,
clusterXml(cluster))).build();
}
private Response handleRestoreDbClusterToPointInTime(MultivaluedMap<String, String> params) {
String id = params.getFirst("DBClusterIdentifier");
String sourceId = params.getFirst("SourceDBClusterIdentifier");
if (id == null || id.isBlank() || sourceId == null || sourceId.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue",
"DBClusterIdentifier and SourceDBClusterIdentifier are required.", AwsNamespaces.RDS, 400);
}
// The same checks as RDS's restore; only the latest restorable time is modeled, so a
// requested time is refused rather than silently answered with the source's current data.
boolean restoreTimeGiven = params.getFirst("RestoreToTime") != null && !params.getFirst("RestoreToTime").isBlank();
boolean latestRequested = Boolean.TRUE.equals(optionalBoolean(params.getFirst("UseLatestRestorableTime")));
if (restoreTimeGiven && latestRequested) {
return AwsQueryResponse.error("InvalidParameterCombination",
"RestoreToTime cannot be specified when UseLatestRestorableTime is true.", AwsNamespaces.RDS, 400);
}
if (!restoreTimeGiven && !latestRequested) {
return AwsQueryResponse.error("InvalidParameterCombination",
"Specify either RestoreToTime or UseLatestRestorableTime.", AwsNamespaces.RDS, 400);
}
if (restoreTimeGiven) {
return AwsQueryResponse.error("InvalidParameterValue",
"Floci restores DocumentDB clusters to the latest restorable time only; use UseLatestRestorableTime.",
AwsNamespaces.RDS, 400);
}
DocDbCluster cluster = service.restoreDbClusterToPointInTime(id, sourceId,
clusterSettings(params, true), parseTags(params));
return Response.ok(AwsQueryResponse.envelope("RestoreDBClusterToPointInTime", AwsNamespaces.RDS,
clusterXml(cluster))).build();
}
private String snapshotXml(DocDbClusterSnapshot snapshot) {
return new XmlBuilder().start("DBClusterSnapshot").raw(snapshotInnerXml(snapshot))
.end("DBClusterSnapshot").build();
}
private String snapshotInnerXml(DocDbClusterSnapshot s) {
XmlBuilder xml = new XmlBuilder()
.elem("DBClusterSnapshotIdentifier", s.getDbClusterSnapshotIdentifier())
.elem("DBClusterIdentifier", s.getDbClusterIdentifier())
.elem("SnapshotCreateTime", s.getSnapshotCreateTime() != null ? s.getSnapshotCreateTime().toString() : "")
.elem("Engine", "docdb")
.elem("Status", s.getStatus())
.elem("Port", s.getPort())
.elem("ClusterCreateTime", s.getClusterCreateTime() != null ? s.getClusterCreateTime().toString() : "")
.elem("MasterUsername", s.getMasterUsername())
.elem("EngineVersion", s.getEngineVersion())
.elem("SnapshotType", s.getSnapshotType())
.elem("PercentProgress", 100)
.elem("StorageEncrypted", s.isStorageEncrypted())
.elem("DBClusterSnapshotArn", s.getDbClusterSnapshotArn());
if (s.getKmsKeyId() != null && !s.getKmsKeyId().isBlank()) {
xml.elem("KmsKeyId", s.getKmsKeyId());
}
return xml.start("AvailabilityZones").elem("AvailabilityZone", config.defaultAvailabilityZone())
.end("AvailabilityZones").build();
}
private Response handleDeleteDbCluster(MultivaluedMap<String, String> params) {
String id = params.getFirst("DBClusterIdentifier");
if (id == null || id.isBlank()) {
@@ -12,6 +12,7 @@ import io.floci.aws.services.docdb.container.DocDbContainerHandle;
import io.floci.aws.services.docdb.container.DocDbContainerManager;
import io.floci.aws.services.docdb.model.DocDbCluster;
import io.floci.aws.services.docdb.model.DocDbClusterSettings;
import io.floci.aws.services.docdb.model.DocDbClusterSnapshot;
import io.floci.aws.services.docdb.model.DocDbInstance;
import io.floci.aws.services.docdb.model.DocDbInstanceSettings;
import io.floci.aws.services.ec2.Ec2Service;
@@ -54,6 +55,9 @@ public class DocDbService {
private final StorageBackend<String, DocDbCluster> clusters;
private final StorageBackend<String, DocDbInstance> instances;
private final StorageBackend<String, DocDbClusterSnapshot> snapshots;
/** Snapshot archives, keyed like the snapshot records they belong to. */
private final StorageBackend<String, String> snapshotData;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final DocDbContainerManager containerManager;
@@ -188,6 +192,10 @@ public class DocDbService {
new TypeReference<Map<String, DocDbCluster>>() {});
this.instances = storageFactory.create("docdb", "docdb-instances.json",
new TypeReference<Map<String, DocDbInstance>>() {});
this.snapshots = storageFactory.create("docdb", "docdb-cluster-snapshots.json",
new TypeReference<Map<String, DocDbClusterSnapshot>>() {});
this.snapshotData = storageFactory.create("docdb", "docdb-cluster-snapshot-data.json",
new TypeReference<Map<String, String>>() {});
}
// ── Clusters ──────────────────────────────────────────────────────────────
@@ -640,18 +648,282 @@ public class DocDbService {
"Cannot delete DocDB cluster " + id + " — it still has DB instances.", 400);
}
cluster.setStatus("deleting");
clusters.put(key(region, id), cluster);
removeCluster(region, cluster);
}
}
if (cluster.getContainerId() != null) {
containerManager.stop(new DocDbContainerHandle(
cluster.getContainerId(), id,
cluster.getContainerHost(), cluster.getContainerPort()));
/** Stops a cluster's container and removes its record; the caller holds the cluster's lock. */
private void removeCluster(String region, DocDbCluster cluster) {
String id = cluster.getDbClusterIdentifier();
cluster.setStatus("deleting");
clusters.put(key(region, id), cluster);
if (cluster.getContainerId() != null) {
containerManager.stop(new DocDbContainerHandle(
cluster.getContainerId(), id,
cluster.getContainerHost(), cluster.getContainerPort()));
}
clusters.delete(key(region, id));
writeLocks.remove("cluster:" + key(region, id));
LOG.infov("DocDB cluster {0} deleted", id);
}
// ── Cluster snapshots ─────────────────────────────────────────────────────
/** What a snapshot or a point-in-time restore takes from a cluster: its data and master password. */
private record ClusterArchive(String data, String masterPassword) {}
/**
* Takes a manual snapshot: a {@code mongodump} archive of the cluster's MongoDB container,
* complete when this returns, so the snapshot is {@code available} straight away.
*/
public DocDbClusterSnapshot createDbClusterSnapshot(String snapshotId, String clusterId,
Map<String, String> tags) {
String region = regionResolver.getRegion();
requireIdentifier(snapshotId, "DBClusterSnapshotIdentifier");
DocDbCluster cluster = getDbCluster(clusterId, region);
synchronized (lockFor("snapshot:" + key(region, snapshotId))) {
if (snapshots.get(key(region, snapshotId)).isPresent()) {
throw new AwsException("DBClusterSnapshotAlreadyExistsFault",
"Cannot create the cluster snapshot because one with the identifier "
+ snapshotId + " already exists.", 400);
}
ClusterArchive archive = archiveOf(cluster);
DocDbClusterSnapshot snapshot = new DocDbClusterSnapshot();
snapshot.setDbClusterSnapshotIdentifier(snapshotId);
snapshot.setDbClusterIdentifier(clusterId);
snapshot.setDbClusterSnapshotArn(regionResolver.buildArn("rds", region, "cluster-snapshot:" + snapshotId));
snapshot.setStatus("available");
snapshot.setSnapshotType("manual");
snapshot.setEngineVersion(cluster.getEngineVersion());
snapshot.setMasterUsername(cluster.getMasterUsername());
snapshot.setMasterPassword(archive.masterPassword());
snapshot.setPort(cluster.getPort());
snapshot.setStorageEncrypted(cluster.isStorageEncrypted());
snapshot.setKmsKeyId(cluster.getKmsKeyId());
snapshot.setSnapshotCreateTime(Instant.now());
snapshot.setClusterCreateTime(cluster.getCreatedAt());
snapshot.setSizeBytes(archive.data().length() * 3L / 4L);
snapshot.setMetadataOnly(config.services().docdb().mock());
if (tags != null && !tags.isEmpty()) {
snapshot.setTags(new LinkedHashMap<>(tags));
}
snapshotData.put(key(region, snapshotId), archive.data());
snapshots.put(key(region, snapshotId), snapshot);
LOG.infov("DocDB cluster snapshot {0} of {1} created ({2} bytes)",
snapshotId, clusterId, String.valueOf(snapshot.getSizeBytes()));
return snapshot;
}
}
clusters.delete(key(region, id));
writeLocks.remove("cluster:" + key(region, id));
LOG.infov("DocDB cluster {0} deleted", id);
/**
* The cluster's data and master password, read from its MongoDB container. A snapshot and a
* point-in-time restore both take them this way, with the same checks: the cluster has to be
* available and, outside mock mode, running a backend whose data can be read.
*/
private ClusterArchive archiveOf(DocDbCluster cluster) {
String clusterId = cluster.getDbClusterIdentifier();
if (!"available".equals(cluster.getStatus())) {
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster " + clusterId + " is not available.", 400);
}
if (config.services().docdb().mock()) {
return new ClusterArchive("", null);
}
if (cluster.getContainerId() == null) {
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster " + clusterId + " has no running MongoDB backend to read.", 400);
}
try {
return new ClusterArchive(containerManager.dumpCluster(cluster.getContainerId()),
containerManager.masterPassword(cluster.getContainerId()));
} catch (RuntimeException e) {
LOG.warnv(e, "Failed to read the data of DocDB cluster {0}", clusterId);
throw new AwsException("InvalidDBClusterStateFault",
"Failed to read the data of DB cluster " + clusterId + ": " + e.getMessage(), 400);
}
}
/**
* Whether a request's snapshot parameter, an identifier or an ARN, names a DocumentDB snapshot
* in this region. An ARN matches only the record stored under that exact ARN.
*/
public boolean hasClusterSnapshot(String snapshotIdOrArn, String region) {
if (snapshotIdOrArn == null || snapshotIdOrArn.isBlank()) {
return false;
}
if (!AwsArnUtils.isArn(snapshotIdOrArn)) {
return snapshots.get(key(region, snapshotIdOrArn)).isPresent();
}
String id = snapshotIdInArn(snapshotIdOrArn);
return id != null && snapshots.get(key(region, id))
.map(snapshot -> snapshotIdOrArn.equals(snapshot.getDbClusterSnapshotArn()))
.orElse(false);
}
/** The snapshot identifier an RDS cluster-snapshot ARN names, or null when it names none. */
private static String snapshotIdInArn(String arn) {
try {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String prefix = "cluster-snapshot:";
return "rds".equals(parsed.service()) && parsed.resource().startsWith(prefix)
? parsed.resource().substring(prefix.length()) : null;
} catch (IllegalArgumentException malformed) {
return null;
}
}
/** The snapshot a request names, by identifier or by ARN, in the caller's region. */
public DocDbClusterSnapshot getDbClusterSnapshot(String snapshotIdOrArn) {
String region = regionResolver.getRegion();
String id = snapshotIdOrArn;
if (AwsArnUtils.isArn(snapshotIdOrArn)) {
id = snapshotIdInArn(snapshotIdOrArn);
if (id == null) {
throw new AwsException("InvalidParameterValue",
"Invalid DB cluster snapshot identifier: " + snapshotIdOrArn, 400);
}
}
String name = id;
DocDbClusterSnapshot snapshot = snapshots.get(key(region, id)).orElseThrow(() ->
new AwsException("DBClusterSnapshotNotFoundFault",
"DBClusterSnapshot " + name + " not found.", 404));
// Storage is keyed by identifier alone, so an ARN of another region or account would
// otherwise resolve this caller's snapshot.
if (AwsArnUtils.isArn(snapshotIdOrArn) && !snapshotIdOrArn.equals(snapshot.getDbClusterSnapshotArn())) {
throw new AwsException("DBClusterSnapshotNotFoundFault",
"DBClusterSnapshot " + snapshotIdOrArn + " not found.", 404);
}
return snapshot;
}
/** Snapshots in this region matching every one of the request's identifier, cluster and type. */
public List<DocDbClusterSnapshot> describeDbClusterSnapshots(String snapshotIdOrArn, String clusterId,
String snapshotType) {
List<DocDbClusterSnapshot> candidates = snapshotIdOrArn != null && !snapshotIdOrArn.isBlank()
? List.of(getDbClusterSnapshot(snapshotIdOrArn))
: inRegion(snapshots, regionResolver.getRegion(), DocDbClusterSnapshot::getDbClusterSnapshotIdentifier);
return candidates.stream()
.filter(sn -> clusterId == null || clusterId.isBlank() || clusterId.equals(sn.getDbClusterIdentifier()))
.filter(sn -> snapshotType == null || snapshotType.isBlank() || snapshotType.equals(sn.getSnapshotType()))
.toList();
}
public DocDbClusterSnapshot deleteDbClusterSnapshot(String snapshotIdOrArn) {
String region = regionResolver.getRegion();
String snapshotId = getDbClusterSnapshot(snapshotIdOrArn).getDbClusterSnapshotIdentifier();
synchronized (lockFor("snapshot:" + key(region, snapshotId))) {
DocDbClusterSnapshot snapshot = getDbClusterSnapshot(snapshotIdOrArn);
snapshots.delete(key(region, snapshotId));
snapshotData.delete(key(region, snapshotId));
writeLocks.remove("snapshot:" + key(region, snapshotId));
snapshot.setStatus("deleted");
return snapshot;
}
}
/**
* A new cluster holding the snapshot's data. It has no instances, as on AWS: the caller adds
* them with CreateDBInstance. The snapshot's master user comes back with the data.
*/
public DocDbCluster restoreDbClusterFromSnapshot(String clusterId, String snapshotIdOrArn, String engineVersion,
DocDbClusterSettings settings, Map<String, String> tags) {
String region = regionResolver.getRegion();
String snapshotId = getDbClusterSnapshot(snapshotIdOrArn).getDbClusterSnapshotIdentifier();
DocDbClusterSnapshot snapshot;
String data;
// The record and its archive are read together under the lock delete takes, so a restore
// sees both or neither, and a snapshot whose archive is gone is refused before any cluster
// exists rather than restored as an empty one.
synchronized (lockFor("snapshot:" + key(region, snapshotId))) {
snapshot = getDbClusterSnapshot(snapshotIdOrArn);
data = snapshotData.get(key(region, snapshotId)).orElse(null);
boolean restorable = snapshot.isMetadataOnly()
? config.services().docdb().mock()
: data != null && !data.isEmpty();
if (!restorable) {
throw new AwsException("InvalidDBClusterSnapshotStateFault",
"DB cluster snapshot " + snapshotId + " has no data to restore.", 400);
}
}
String password = snapshot.getMasterPassword() != null ? snapshot.getMasterPassword()
: UUID.randomUUID().toString();
String version = engineVersion != null && !engineVersion.isBlank()
? engineVersion : snapshot.getEngineVersion();
DocDbCluster cluster = createDbCluster(clusterId, version, snapshot.getMasterUsername(), password, false,
restoredFrom(settings, snapshot.isStorageEncrypted(), snapshot.getKmsKeyId(), true), tags);
loadInto(cluster, snapshot.isMetadataOnly() ? "" : data);
return cluster;
}
/**
* A new cluster holding the source's data as it is now, the latest restorable time. The data is
* read as a snapshot reads it, with the same checks and faults.
*/
public DocDbCluster restoreDbClusterToPointInTime(String clusterId, String sourceClusterId,
DocDbClusterSettings settings, Map<String, String> tags) {
DocDbCluster source = getDbCluster(sourceClusterId);
ClusterArchive archive = archiveOf(source);
String password = archive.masterPassword() != null ? archive.masterPassword()
: UUID.randomUUID().toString();
DocDbCluster cluster = createDbCluster(clusterId, source.getEngineVersion(), source.getMasterUsername(),
password, false, restoredFrom(settings, source.isStorageEncrypted(), source.getKmsKeyId(), false), tags);
loadInto(cluster, archive.data());
return cluster;
}
/**
* The settings a restore creates its cluster with. A restore request carries no
* {@code StorageEncrypted} of its own: the cluster takes its source's encryption and key unless
* the request names a key. A snapshot restore may encrypt an unencrypted snapshot that way, as
* the restore guide allows; a point-in-time restore may not, and a key named for an unencrypted
* source is refused by {@code validate}, as its reference has it.
*/
private static DocDbClusterSettings restoredFrom(DocDbClusterSettings requested, boolean sourceEncrypted,
String sourceKmsKeyId, boolean keyMayEncrypt) {
boolean keyNamed = requested.kmsKeyId() != null && !requested.kmsKeyId().isBlank();
String kmsKeyId = keyNamed ? requested.kmsKeyId() : (sourceEncrypted ? sourceKmsKeyId : null);
boolean encrypted = sourceEncrypted || (keyNamed && keyMayEncrypt);
return new DocDbClusterSettings(requested.dbSubnetGroupName(), requested.dbClusterParameterGroupName(),
requested.vpcSecurityGroupIds(), encrypted, kmsKeyId, requested.backupRetentionPeriod(),
requested.preferredBackupWindow(), requested.preferredMaintenanceWindow(),
requested.deletionProtection());
}
private void loadInto(DocDbCluster cluster, String data) {
if (config.services().docdb().mock() || data.isEmpty() || cluster.getContainerId() == null) {
return;
}
try {
containerManager.restoreCluster(cluster.getContainerId(), data);
} catch (RuntimeException e) {
try {
discardRestoredCluster(cluster.getDbClusterIdentifier());
} catch (RuntimeException cleanup) {
LOG.warnv(cleanup, "Could not remove DocDB cluster {0} after its failed restore",
cluster.getDbClusterIdentifier());
e.addSuppressed(cleanup);
}
throw new AwsException("InvalidRestoreFault",
"Failed to restore cluster " + cluster.getDbClusterIdentifier() + ": " + e.getMessage(), 400);
}
}
/**
* Removes a cluster this restore just created and could not load. It bypasses deletion
* protection, which the request may have asked for: the caller never received the cluster.
*/
private void discardRestoredCluster(String id) {
String region = regionResolver.getRegion();
synchronized (lockFor("cluster:" + key(region, id))) {
findCluster(region, id).ifPresent(cluster -> removeCluster(region, cluster));
}
}
private static void requireIdentifier(String value, String name) {
if (value == null || value.isBlank()) {
throw new AwsException("InvalidParameterValue", name + " is required.", 400);
}
}
@@ -5,12 +5,14 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.RetryingTarCopier;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -20,6 +22,7 @@ import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -171,6 +174,79 @@ public class DocDbContainerManager {
}
}
/**
* The master password the container was started with. A restore replays the source's users,
* so the restored cluster's container must start with the same password for later dumps of
* it to authenticate.
*/
public String masterPassword(String containerId) {
String[] env = lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec().getConfig().getEnv();
if (env != null) {
for (String entry : env) {
if (entry.startsWith("MONGO_INITDB_ROOT_PASSWORD=")) {
return entry.substring("MONGO_INITDB_ROOT_PASSWORD=".length());
}
}
}
return null;
}
/**
* A snapshot of the cluster's data: a gzipped {@code mongodump} archive of every database,
* users and roles included, base64 encoded so it travels through the exec's text output.
* The container's own MONGO_INITDB credentials authenticate the dump.
*/
public String dumpCluster(String containerId) {
String[] cmd = {"bash", "-o", "pipefail", "-c",
"mongodump --quiet --host 127.0.0.1 --port " + MONGO_PORT
+ " \"--username=$MONGO_INITDB_ROOT_USERNAME\" \"--password=$MONGO_INITDB_ROOT_PASSWORD\""
+ " --authenticationDatabase admin --archive --gzip | base64 -w0"};
ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 600);
if (result.exitCode() != 0) {
throw new RuntimeException("mongodump failed with exit code " + result.exitCode() + ": " + result.stderr());
}
return result.stdout().trim();
}
/**
* Loads a {@link #dumpCluster} archive into a cluster's container, replacing what it holds. The
* archive carries the source's users, so the restored cluster keeps the snapshot's master
* credentials, as a restore does on AWS. Waits for the server to accept writes first: a new
* container may still be initializing or electing its replica-set primary.
*/
public void restoreCluster(String containerId, String archiveBase64) {
byte[] archive = Base64.getDecoder().decode(archiveBase64);
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/tmp",
"floci-docdb-restore.archive.gz", archive, 0644, RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, 500);
String auth = " \"--username=$MONGO_INITDB_ROOT_USERNAME\" \"--password=$MONGO_INITDB_ROOT_PASSWORD\" --authenticationDatabase admin";
String[] ready = {"bash", "-c", "mongosh --quiet --host 127.0.0.1 --port " + MONGO_PORT + auth
+ " --eval 'quit(db.hello().isWritablePrimary ? 0 : 3)'"};
ContainerExec.Result probe = null;
for (int i = 0; i < 120; i++) {
probe = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, ready, 30);
if (probe.exitCode() == 0) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted waiting for MongoDB to accept writes", ie);
}
}
if (probe == null || probe.exitCode() != 0) {
throw new RuntimeException("MongoDB did not accept writes before the restore: "
+ (probe != null ? probe.stderr() : ""));
}
String[] cmd = {"bash", "-c", "mongorestore --quiet --host 127.0.0.1 --port " + MONGO_PORT + auth
+ " --drop --nsExclude='config.*' --archive=/tmp/floci-docdb-restore.archive.gz --gzip"
+ " && rm -f /tmp/floci-docdb-restore.archive.gz"};
ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 600);
if (result.exitCode() != 0) {
throw new RuntimeException("mongorestore failed with exit code " + result.exitCode() + ": " + result.stderr());
}
}
private static void waitForBackendReady(String clusterId, String host, int port) {
long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS;
int attempt = 0;
@@ -0,0 +1,87 @@
package io.floci.aws.services.docdb.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A DocumentDB cluster snapshot. The data itself, a {@code mongodump} archive of the cluster's
* MongoDB container, is kept beside the record under the same key rather than on it, so listing
* snapshots never reads every archive.
*/
@RegisterForReflection
public class DocDbClusterSnapshot {
private String dbClusterSnapshotIdentifier;
private String dbClusterIdentifier;
private String dbClusterSnapshotArn;
private String status;
private String snapshotType;
private String engineVersion;
private String masterUsername;
/** Kept so a restore starts its container with the credentials the data carries; never returned by the API. */
private String masterPassword;
private int port;
private String vpcId;
private boolean storageEncrypted;
private String kmsKeyId;
private Instant snapshotCreateTime;
private Instant clusterCreateTime;
private long sizeBytes;
/** Taken in mock mode, with no backend to read: the record alone, with no archive to restore. */
private boolean metadataOnly;
private Map<String, String> tags = new LinkedHashMap<>();
public String getDbClusterSnapshotIdentifier() { return dbClusterSnapshotIdentifier; }
public void setDbClusterSnapshotIdentifier(String v) { this.dbClusterSnapshotIdentifier = v; }
public String getDbClusterIdentifier() { return dbClusterIdentifier; }
public void setDbClusterIdentifier(String v) { this.dbClusterIdentifier = v; }
public String getDbClusterSnapshotArn() { return dbClusterSnapshotArn; }
public void setDbClusterSnapshotArn(String v) { this.dbClusterSnapshotArn = v; }
public String getStatus() { return status; }
public void setStatus(String v) { this.status = v; }
public String getSnapshotType() { return snapshotType; }
public void setSnapshotType(String v) { this.snapshotType = v; }
public String getEngineVersion() { return engineVersion; }
public void setEngineVersion(String v) { this.engineVersion = v; }
public String getMasterUsername() { return masterUsername; }
public void setMasterUsername(String v) { this.masterUsername = v; }
public String getMasterPassword() { return masterPassword; }
public void setMasterPassword(String v) { this.masterPassword = v; }
public int getPort() { return port; }
public void setPort(int v) { this.port = v; }
public String getVpcId() { return vpcId; }
public void setVpcId(String v) { this.vpcId = v; }
public boolean isMetadataOnly() { return metadataOnly; }
public void setMetadataOnly(boolean v) { this.metadataOnly = v; }
public boolean isStorageEncrypted() { return storageEncrypted; }
public void setStorageEncrypted(boolean v) { this.storageEncrypted = v; }
public String getKmsKeyId() { return kmsKeyId; }
public void setKmsKeyId(String v) { this.kmsKeyId = v; }
public Instant getSnapshotCreateTime() { return snapshotCreateTime; }
public void setSnapshotCreateTime(Instant v) { this.snapshotCreateTime = v; }
public Instant getClusterCreateTime() { return clusterCreateTime; }
public void setClusterCreateTime(Instant v) { this.clusterCreateTime = v; }
public long getSizeBytes() { return sizeBytes; }
public void setSizeBytes(long v) { this.sizeBytes = v; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> v) { this.tags = v != null ? v : new LinkedHashMap<>(); }
}
@@ -2822,12 +2822,25 @@ public class RdsQueryHandler {
}
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params, String region) {
String snapshotId = params.getFirst("DBClusterSnapshotIdentifier");
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshots");
for (DbClusterSnapshot s : service.describeDbClusterSnapshots(
params.getFirst("DBClusterSnapshotIdentifier"), params.getFirst("DBClusterIdentifier"),
snapshotId, params.getFirst("DBClusterIdentifier"),
params.getFirst("SnapshotType"), region)) {
xml.raw(dbClusterSnapshotXml(s));
}
// The list form covers the whole RDS family, as DescribeDBClusters does: a live account
// lists DocumentDB cluster snapshots here too. The identifier form is routed to the store
// that owns the identifier.
if (snapshotId == null || snapshotId.isBlank()) {
String clusterId = params.getFirst("DBClusterIdentifier");
if (clusterId == null || clusterId.isBlank()) {
clusterId = extractRdsFilterValue(params, "db-cluster-id");
}
for (String row : docDbQueryHandler.clusterSnapshotRowsXml(clusterId, params.getFirst("SnapshotType"))) {
xml.start("DBClusterSnapshot").raw(row).end("DBClusterSnapshot");
}
}
xml.end("DBClusterSnapshots");
return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterSnapshots", AwsNamespaces.RDS, xml.build())).build();
}
@@ -5730,6 +5730,12 @@ public class RdsService implements Resettable, ResourceProvider {
return cluster || instance;
}
/** Whether RDS holds a cluster snapshot of this identifier in the request's region. */
public boolean hasClusterSnapshot(String snapshotId, String region) {
return snapshotId != null && !snapshotId.isBlank()
&& findClusterSnapshotForScope(currentAccountId(), effectiveRegion(region), snapshotId) != null;
}
public DbCluster getDbCluster(String id) {
return getDbCluster(id, regionResolver.getDefaultRegion());
}
@@ -0,0 +1,307 @@
package io.floci.aws.services.docdb;
import io.floci.aws.testing.DocDbMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
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 org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/**
* Cluster snapshots and the two restores. Requests are signed for {@code rds}, as the AWS CLI and
* SDKs sign DocumentDB calls, so they reach DocumentDB only through the routing that recognizes a
* DocumentDB cluster or snapshot named in the request.
*/
@QuarkusTest
@TestProfile(DocDbMockProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DocDbClusterSnapshotIntegrationTest {
private static final String FORM = "application/x-www-form-urlencoded";
private static final String CLUSTER_ID = "snap-source-cluster";
private static final String SNAPSHOT_ID = "snap-source-cluster-manual";
private static final String RESTORED_ID = "snap-restored-cluster";
private static final String POINT_IN_TIME_ID = "snap-point-in-time-cluster";
private static final String LISTED_SNAPSHOT_ID = "snap-source-cluster-listed";
private static final String ARN_RESTORED_ID = "snap-arn-restored-cluster";
private static final String MASTER_USERNAME = "docdbadmin";
private static final String MASTER_PASSWORD = "secret99password";
private static final String AUTH_RDS_SCOPE =
"AWS4-HMAC-SHA256 Credential=test/20260615/us-east-1/rds/aws4_request, "
+ "SignedHeaders=content-type;host, Signature=test";
private static String listedSnapshotArn;
@Test
@Order(1)
void createSourceCluster() {
request("CreateDBCluster")
.formParam("DBClusterIdentifier", CLUSTER_ID)
.formParam("Engine", "docdb")
.formParam("MasterUsername", MASTER_USERNAME)
.formParam("MasterUserPassword", MASTER_PASSWORD)
.when().post("/")
.then()
.statusCode(200)
.body(containsString(CLUSTER_ID));
}
@Test
@Order(2)
void createSnapshotIsAvailableAtOnce() {
request("CreateDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", SNAPSHOT_ID)
.formParam("DBClusterIdentifier", CLUSTER_ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<CreateDBClusterSnapshotResponse"))
.body(containsString("<DBClusterSnapshotIdentifier>" + SNAPSHOT_ID + "</DBClusterSnapshotIdentifier>"))
.body(containsString("<DBClusterIdentifier>" + CLUSTER_ID + "</DBClusterIdentifier>"))
.body(containsString("<Engine>docdb</Engine>"))
.body(containsString("<Status>available</Status>"))
.body(containsString("<SnapshotType>manual</SnapshotType>"))
.body(containsString(":cluster-snapshot:" + SNAPSHOT_ID))
.body(not(containsString(MASTER_PASSWORD)));
}
@Test
@Order(3)
void createSnapshotWithATakenIdentifierFails() {
request("CreateDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", SNAPSHOT_ID)
.formParam("DBClusterIdentifier", CLUSTER_ID)
.when().post("/")
.then()
.statusCode(400)
.body(containsString("DBClusterSnapshotAlreadyExistsFault"));
}
@Test
@Order(4)
void describeSnapshotsOfTheCluster() {
request("DescribeDBClusterSnapshots")
.formParam("DBClusterIdentifier", CLUSTER_ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<DBClusterSnapshotIdentifier>" + SNAPSHOT_ID + "</DBClusterSnapshotIdentifier>"));
}
@Test
@Order(5)
void restoreFromSnapshotCreatesAClusterWithTheSnapshotsMasterUser() {
request("RestoreDBClusterFromSnapshot")
.formParam("DBClusterIdentifier", RESTORED_ID)
.formParam("SnapshotIdentifier", SNAPSHOT_ID)
.formParam("Engine", "docdb")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<RestoreDBClusterFromSnapshotResponse"))
.body(containsString("<DBClusterIdentifier>" + RESTORED_ID + "</DBClusterIdentifier>"))
.body(containsString("<MasterUsername>" + MASTER_USERNAME + "</MasterUsername>"));
}
@Test
@Order(6)
void restoreToPointInTimeCreatesAClusterFromTheSource() {
request("RestoreDBClusterToPointInTime")
.formParam("DBClusterIdentifier", POINT_IN_TIME_ID)
.formParam("SourceDBClusterIdentifier", CLUSTER_ID)
.formParam("UseLatestRestorableTime", "true")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<RestoreDBClusterToPointInTimeResponse"))
.body(containsString("<DBClusterIdentifier>" + POINT_IN_TIME_ID + "</DBClusterIdentifier>"))
.body(containsString("<MasterUsername>" + MASTER_USERNAME + "</MasterUsername>"));
}
@Test
@Order(7)
void restoredClustersAreDocDbClusters() {
request("DescribeDBClusters")
.formParam("DBClusterIdentifier", RESTORED_ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<Engine>docdb</Engine>"));
}
@Test
@Order(8)
void deleteSnapshot() {
request("DeleteDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", SNAPSHOT_ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<DeleteDBClusterSnapshotResponse"))
.body(containsString("<DBClusterSnapshotIdentifier>" + SNAPSHOT_ID + "</DBClusterSnapshotIdentifier>"));
}
@Test
@Order(9)
void aDeletedSnapshotIsGoneFromTheCluster() {
request("DescribeDBClusterSnapshots")
.formParam("DBClusterIdentifier", CLUSTER_ID)
.when().post("/")
.then()
.statusCode(200)
.body(not(containsString(SNAPSHOT_ID)));
}
@Test
@Order(10)
void snapshotOfAnUnknownClusterIsNotFound() {
docDbRequest("CreateDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", "orphan-snapshot")
.formParam("DBClusterIdentifier", "no-such-cluster")
.when().post("/")
.then()
.statusCode(404)
.body(containsString("DBClusterNotFoundFault"));
}
@Test
@Order(11)
void takeASnapshotForTheListingAndArnChecks() {
String body = request("CreateDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", LISTED_SNAPSHOT_ID)
.formParam("DBClusterIdentifier", CLUSTER_ID)
.when().post("/")
.then()
.statusCode(200)
.extract().asString();
listedSnapshotArn = body.substring(body.indexOf("<DBClusterSnapshotArn>") + "<DBClusterSnapshotArn>".length(),
body.indexOf("</DBClusterSnapshotArn>"));
}
@Test
@Order(12)
void theRdsListFormIncludesDocDbSnapshots() {
request("DescribeDBClusterSnapshots")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<DBClusterSnapshotIdentifier>" + LISTED_SNAPSHOT_ID + "</DBClusterSnapshotIdentifier>"));
}
@Test
@Order(13)
void theDocDbListFormIncludesDocDbSnapshots() {
docDbRequest("DescribeDBClusterSnapshots")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<DBClusterSnapshotIdentifier>" + LISTED_SNAPSHOT_ID + "</DBClusterSnapshotIdentifier>"));
}
@Test
@Order(14)
void theDbClusterIdFilterNarrowsTheRdsListForm() {
request("DescribeDBClusterSnapshots")
.formParam("Filters.Filter.1.Name", "db-cluster-id")
.formParam("Filters.Filter.1.Values.Value.1", CLUSTER_ID)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<DBClusterSnapshotIdentifier>" + LISTED_SNAPSHOT_ID + "</DBClusterSnapshotIdentifier>"));
request("DescribeDBClusterSnapshots")
.formParam("Filters.Filter.1.Name", "db-cluster-id")
.formParam("Filters.Filter.1.Values.Value.1", "another-cluster")
.when().post("/")
.then()
.statusCode(200)
.body(not(containsString(LISTED_SNAPSHOT_ID)));
}
@Test
@Order(15)
void anIdentifierStillHonorsTheOtherFilters() {
request("DescribeDBClusterSnapshots")
.formParam("DBClusterSnapshotIdentifier", LISTED_SNAPSHOT_ID)
.formParam("SnapshotType", "automated")
.when().post("/")
.then()
.statusCode(200)
.body(not(containsString("<DBClusterSnapshotIdentifier>")));
}
@Test
@Order(16)
void restoreFromSnapshotAcceptsTheSnapshotArn() {
request("RestoreDBClusterFromSnapshot")
.formParam("DBClusterIdentifier", ARN_RESTORED_ID)
.formParam("SnapshotIdentifier", listedSnapshotArn)
.formParam("Engine", "docdb")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<DBClusterIdentifier>" + ARN_RESTORED_ID + "</DBClusterIdentifier>"));
}
@Test
@Order(17)
void aSnapshotArnOfAnotherRegionIsNotFound() {
docDbRequest("RestoreDBClusterFromSnapshot")
.formParam("DBClusterIdentifier", "arn-other-region-restore")
.formParam("SnapshotIdentifier", listedSnapshotArn.replace(":us-east-1:", ":eu-west-1:"))
.when().post("/")
.then()
.statusCode(404)
.body(containsString("DBClusterSnapshotNotFoundFault"));
}
@Test
@Order(18)
void aPointInTimeRestoreNeedsTheLatestRestorableTime() {
request("RestoreDBClusterToPointInTime")
.formParam("DBClusterIdentifier", "pitr-requested-time")
.formParam("SourceDBClusterIdentifier", CLUSTER_ID)
.formParam("RestoreToTime", "2026-11-01T00:00:00Z")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("InvalidParameterValue"));
request("RestoreDBClusterToPointInTime")
.formParam("DBClusterIdentifier", "pitr-no-time")
.formParam("SourceDBClusterIdentifier", CLUSTER_ID)
.when().post("/")
.then()
.statusCode(400)
.body(containsString("InvalidParameterCombination"));
request("RestoreDBClusterToPointInTime")
.formParam("DBClusterIdentifier", "pitr-both-times")
.formParam("SourceDBClusterIdentifier", CLUSTER_ID)
.formParam("RestoreToTime", "2026-11-01T00:00:00Z")
.formParam("UseLatestRestorableTime", "true")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("InvalidParameterCombination"));
}
private static RequestSpecification request(String action) {
return given()
.header("Authorization", AUTH_RDS_SCOPE)
.contentType(FORM)
.formParam("Action", action);
}
/** As {@link #request}, signed for the docdb endpoint, which dispatches to DocumentDB directly. */
private static RequestSpecification docDbRequest(String action) {
return given()
.header("Authorization", AUTH_RDS_SCOPE.replace("/rds/", "/docdb/"))
.contentType(FORM)
.formParam("Action", action);
}
}
@@ -0,0 +1,250 @@
package io.floci.aws.services.docdb;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.docdb.container.DocDbContainerHandle;
import io.floci.aws.services.docdb.container.DocDbContainerManager;
import io.floci.aws.services.docdb.model.DocDbCluster;
import io.floci.aws.services.docdb.model.DocDbClusterSettings;
import io.floci.aws.services.docdb.model.DocDbClusterSnapshot;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.kms.model.KmsKey;
import io.floci.aws.services.rds.RdsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Snapshots and restores with a container behind each cluster, the container layer mocked: what a
* snapshot reads from its cluster is what a restore loads into the new one, and the failure paths
* leave nothing behind.
*/
class DocDbClusterSnapshotServiceTest {
private static final String KEY_ARN = "arn:aws:kms:us-east-1:000000000000:key/k1";
private static final String ARCHIVE = "H4sIAAAAAAAA/2NgYGBgBGIQAAAA//8DAP2uCU4MAAAA";
private DocDbService docDbService;
private DocDbContainerManager containerManager;
private EmulatorConfig.DocDbServiceConfig docdbConfig;
private StorageBackend<String, String> archives;
@BeforeEach
void setUp() {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> {
StorageBackend<String, Object> store = AccountAwareStorageBackend.inMemory("000000000000");
if ("docdb-cluster-snapshot-data.json".equals(inv.getArgument(1))) {
archives = cast(store);
}
return store;
});
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
docdbConfig = mock(EmulatorConfig.DocDbServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.docdb()).thenReturn(docdbConfig);
when(docdbConfig.mock()).thenReturn(false);
when(docdbConfig.defaultImage()).thenReturn("mongo:7.0");
containerManager = mock(DocDbContainerManager.class);
// Every cluster gets a container named after it.
when(containerManager.tryStart(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenAnswer(inv -> new DocDbContainerHandle("container-" + inv.getArgument(0),
inv.getArgument(0), "localhost", 27017));
when(containerManager.dumpCluster("container-source")).thenReturn(ARCHIVE);
when(containerManager.masterPassword("container-source")).thenReturn("source-password");
KmsService kmsService = mock(KmsService.class);
KmsKey key = new KmsKey();
key.setKeyId("k1");
key.setArn(KEY_ARN);
key.setEnabled(true);
key.setKeyState("Enabled");
doReturn(key).when(kmsService).describeKey(KEY_ARN, "us-east-1");
docDbService = new DocDbService(config, new RegionResolver("us-east-1", "000000000000"), containerManager,
storageFactory, mock(RdsService.class), mock(Ec2Service.class), kmsService);
}
@Test
void theSnapshotsArchiveReachesTheRestoredClusterWithTheSourcesPassword() {
source(DocDbClusterSettings.defaults());
docDbService.createDbClusterSnapshot("snap", "source", Map.of());
docDbService.restoreDbClusterFromSnapshot("restored", "snap", null, DocDbClusterSettings.defaults(), Map.of());
verify(containerManager).tryStart(eq("restored"), anyString(), eq("admin"), eq("source-password"), anyString());
verify(containerManager).restoreCluster("container-restored", ARCHIVE);
}
@Test
void aPointInTimeRestoreLoadsTheSourcesCurrentData() {
source(DocDbClusterSettings.defaults());
docDbService.restoreDbClusterToPointInTime("copy", "source", DocDbClusterSettings.defaults(), Map.of());
verify(containerManager).dumpCluster("container-source");
verify(containerManager).tryStart(eq("copy"), anyString(), eq("admin"), eq("source-password"), anyString());
verify(containerManager).restoreCluster("container-copy", ARCHIVE);
}
@Test
void aPointInTimeRestoreOfAnUnreadableSourceFailsLikeASnapshotAndCreatesNothing() {
source(DocDbClusterSettings.defaults());
when(containerManager.dumpCluster("container-source")).thenThrow(new IllegalStateException("mongodump exited 1"));
AwsException e = assertThrows(AwsException.class, () -> docDbService.restoreDbClusterToPointInTime(
"copy", "source", DocDbClusterSettings.defaults(), Map.of()));
assertEquals("InvalidDBClusterStateFault", e.getErrorCode());
assertEquals(400, e.getHttpStatus());
assertThrows(AwsException.class, () -> docDbService.getDbCluster("copy"));
verify(containerManager, never()).tryStart(eq("copy"), anyString(), anyString(), anyString(), anyString());
}
@Test
void aFailedLoadRemovesTheRestoredClusterEvenUnderDeletionProtection() {
source(DocDbClusterSettings.defaults());
docDbService.createDbClusterSnapshot("snap", "source", Map.of());
doThrow(new IllegalStateException("mongorestore exited 1"))
.when(containerManager).restoreCluster("container-restored", ARCHIVE);
DocDbClusterSettings protectedCluster = new DocDbClusterSettings(null, null, null, null, null, null,
null, null, true);
AwsException e = assertThrows(AwsException.class, () -> docDbService.restoreDbClusterFromSnapshot(
"restored", "snap", null, protectedCluster, Map.of()));
assertEquals("InvalidRestoreFault", e.getErrorCode());
AwsException gone = assertThrows(AwsException.class, () -> docDbService.getDbCluster("restored"));
assertEquals("DBClusterNotFoundFault", gone.getErrorCode());
verify(containerManager).stop(argThat(handle -> "container-restored".equals(handle.getContainerId())));
}
@Test
void bothRestoresKeepTheSourcesEncryptionAndKey() {
source(new DocDbClusterSettings(null, null, null, true, KEY_ARN, null, null, null, null));
docDbService.createDbClusterSnapshot("snap", "source", Map.of());
DocDbCluster fromSnapshot = docDbService.restoreDbClusterFromSnapshot("restored", "snap", null,
DocDbClusterSettings.defaults(), Map.of());
DocDbCluster pointInTime = docDbService.restoreDbClusterToPointInTime("copy", "source",
DocDbClusterSettings.defaults(), Map.of());
for (DocDbCluster cluster : List.of(fromSnapshot, pointInTime)) {
assertTrue(cluster.isStorageEncrypted(), cluster.getDbClusterIdentifier());
assertEquals(KEY_ARN, cluster.getKmsKeyId(), cluster.getDbClusterIdentifier());
}
}
@Test
void anUnencryptedSnapshotRestoresUnencryptedOrEncryptedUnderANamedKey() {
source(DocDbClusterSettings.defaults());
docDbService.createDbClusterSnapshot("snap", "source", Map.of());
DocDbCluster plain = docDbService.restoreDbClusterFromSnapshot("restored", "snap", null,
DocDbClusterSettings.defaults(), Map.of());
assertFalse(plain.isStorageEncrypted());
assertNull(plain.getKmsKeyId());
DocDbCluster keyed = docDbService.restoreDbClusterFromSnapshot("keyed", "snap", null,
new DocDbClusterSettings(null, null, null, null, KEY_ARN, null, null, null, null), Map.of());
assertTrue(keyed.isStorageEncrypted());
assertEquals(KEY_ARN, keyed.getKmsKeyId());
}
@Test
void aPointInTimeRestoreRefusesAKeyForAnUnencryptedSource() {
source(DocDbClusterSettings.defaults());
AwsException e = assertThrows(AwsException.class, () -> docDbService.restoreDbClusterToPointInTime(
"keyed", "source",
new DocDbClusterSettings(null, null, null, null, KEY_ARN, null, null, null, null), Map.of()));
assertEquals("InvalidParameterCombination", e.getErrorCode());
}
@Test
void aSnapshotWhoseArchiveIsLostIsRefusedBeforeAnyClusterExists() {
source(DocDbClusterSettings.defaults());
docDbService.createDbClusterSnapshot("snap", "source", Map.of());
archives.clear();
AwsException e = assertThrows(AwsException.class, () -> docDbService.restoreDbClusterFromSnapshot(
"restored", "snap", null, DocDbClusterSettings.defaults(), Map.of()));
assertEquals("InvalidDBClusterSnapshotStateFault", e.getErrorCode());
assertThrows(AwsException.class, () -> docDbService.getDbCluster("restored"));
verify(containerManager, never()).tryStart(eq("restored"), anyString(), anyString(), anyString(), anyString());
}
@Test
void aMockModeSnapshotIsMetadataOnlyAndRestoresOnlyInMockMode() {
when(docdbConfig.mock()).thenReturn(true);
source(DocDbClusterSettings.defaults());
DocDbClusterSnapshot snapshot = docDbService.createDbClusterSnapshot("snap", "source", Map.of());
assertTrue(snapshot.isMetadataOnly());
docDbService.restoreDbClusterFromSnapshot("in-mock", "snap", null, DocDbClusterSettings.defaults(), Map.of());
when(docdbConfig.mock()).thenReturn(false);
AwsException e = assertThrows(AwsException.class, () -> docDbService.restoreDbClusterFromSnapshot(
"outside-mock", "snap", null, DocDbClusterSettings.defaults(), Map.of()));
assertEquals("InvalidDBClusterSnapshotStateFault", e.getErrorCode());
verify(containerManager, never()).restoreCluster(anyString(), anyString());
}
@Test
void aSnapshotIsNamedByIdentifierOrByItsOwnArnOnly() {
source(DocDbClusterSettings.defaults());
DocDbClusterSnapshot snapshot = docDbService.createDbClusterSnapshot("snap", "source", Map.of());
String arn = snapshot.getDbClusterSnapshotArn();
assertEquals("snap", docDbService.getDbClusterSnapshot(arn).getDbClusterSnapshotIdentifier());
assertTrue(docDbService.hasClusterSnapshot(arn, "us-east-1"));
String otherRegion = arn.replace(":us-east-1:", ":eu-west-1:");
assertFalse(docDbService.hasClusterSnapshot(otherRegion, "us-east-1"));
assertEquals("DBClusterSnapshotNotFoundFault",
assertThrows(AwsException.class, () -> docDbService.getDbClusterSnapshot(otherRegion)).getErrorCode());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> docDbService.getDbClusterSnapshot("arn:aws:rds:us-east-1:000000000000:cluster:source"))
.getErrorCode());
}
@Test
void anIdentifierIsNarrowedByTheClusterAndTypeFilters() {
source(DocDbClusterSettings.defaults());
docDbService.createDbClusterSnapshot("snap", "source", Map.of());
assertEquals(1, docDbService.describeDbClusterSnapshots("snap", "source", "manual").size());
assertTrue(docDbService.describeDbClusterSnapshots("snap", "another-cluster", null).isEmpty());
assertTrue(docDbService.describeDbClusterSnapshots("snap", null, "automated").isEmpty());
}
@SuppressWarnings("unchecked")
private static StorageBackend<String, String> cast(StorageBackend<String, Object> store) {
return (StorageBackend<String, String>) (StorageBackend<?, ?>) store;
}
private void source(DocDbClusterSettings settings) {
docDbService.createDbCluster("source", "5.0.0", "admin", "source-password", false, settings, Map.of());
}
}
@@ -278,7 +278,7 @@ class DocDbIntegrationTest {
given()
.header("Authorization", AUTH)
.contentType(FORM)
.formParam("Action", "RestoreDBClusterFromSnapshot")
.formParam("Action", "CopyDBClusterSnapshot")
.when().post("/")
.then()
.statusCode(400)
@@ -56,6 +56,104 @@ class SharedClusterIdentifierIntegrationTest {
.formParam("Version", "2014-10-31");
}
@Test
void aRestoreCannotTakeAClusterIdentifierRdsAlreadyHolds() {
String held = "restore-target-held-by-rds";
createRdsCluster(held);
createDocDbCluster("restore-source");
query("CreateDBClusterSnapshot")
.formParam("DBClusterIdentifier", "restore-source")
.formParam("DBClusterSnapshotIdentifier", "restore-source-snapshot")
.when().post("/").then().statusCode(200);
query("RestoreDBClusterFromSnapshot")
.formParam("DBClusterIdentifier", held)
.formParam("SnapshotIdentifier", "restore-source-snapshot")
.formParam("Engine", "docdb")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("DBClusterAlreadyExistsFault"));
query("RestoreDBClusterToPointInTime")
.formParam("DBClusterIdentifier", held)
.formParam("SourceDBClusterIdentifier", "restore-source")
.formParam("UseLatestRestorableTime", "true")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("DBClusterAlreadyExistsFault"));
query("DeleteDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", "restore-source-snapshot")
.when().post("/").then().statusCode(200);
deleteCluster("restore-source");
deleteCluster(held);
}
@Test
void aClusterSnapshotIdentifierIsOneSpaceAcrossRdsAndDocumentDb() {
createDocDbCluster("snapshot-space-docdb");
createRdsCluster("snapshot-space-rds");
query("CreateDBClusterSnapshot")
.formParam("DBClusterIdentifier", "snapshot-space-docdb")
.formParam("DBClusterSnapshotIdentifier", "snapshot-space-docdb-first")
.when().post("/").then().statusCode(200);
query("CreateDBClusterSnapshot")
.formParam("DBClusterIdentifier", "snapshot-space-rds")
.formParam("DBClusterSnapshotIdentifier", "snapshot-space-rds-first")
.when().post("/").then().statusCode(200);
// An RDS cluster's snapshot named like a DocumentDB one: refused, not routed to DocumentDB.
query("CreateDBClusterSnapshot")
.formParam("DBClusterIdentifier", "snapshot-space-rds")
.formParam("DBClusterSnapshotIdentifier", "snapshot-space-docdb-first")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("DBClusterSnapshotAlreadyExistsFault"));
// And the reverse.
query("CreateDBClusterSnapshot")
.formParam("DBClusterIdentifier", "snapshot-space-docdb")
.formParam("DBClusterSnapshotIdentifier", "snapshot-space-rds-first")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("DBClusterSnapshotAlreadyExistsFault"));
for (String snapshot : new String[]{"snapshot-space-docdb-first", "snapshot-space-rds-first"}) {
query("DeleteDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", snapshot)
.when().post("/").then().statusCode(200);
}
deleteCluster("snapshot-space-docdb");
deleteCluster("snapshot-space-rds");
}
private static void createRdsCluster(String id) {
query("CreateDBCluster")
.formParam("DBClusterIdentifier", id)
.formParam("Engine", "aurora-postgresql")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "secret99password")
.when().post("/").then().statusCode(200);
}
private static void createDocDbCluster(String id) {
query("CreateDBCluster")
.formParam("DBClusterIdentifier", id)
.formParam("Engine", "docdb")
.formParam("MasterUsername", "docdbadmin")
.formParam("MasterUserPassword", "secret99password")
.when().post("/").then().statusCode(200);
}
private static void deleteCluster(String id) {
query("DeleteDBCluster")
.formParam("DBClusterIdentifier", id)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
}
@Test
void docDbCannotTakeAnIdentifierRdsAlreadyHolds() {
query("CreateDBCluster")