Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

rds: wire ManageMasterUserPassword to Secrets Manager (#1324)

kiran01bmdd36bf91bddc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b557bdd8..20a52691 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **RDS — `ManageMasterUserPassword` wires Aurora clusters to Secrets Manager** — `CreateDBCluster(ManageMasterUserPassword=true)` previously ignored the flag: no secret was created, no `MasterUserSecret` was returned, and code paths that resolve database credentials from Secrets Manager (the common production pattern) could not be rehearsed locally. The flag now generates a random master password, stores it in MiniStack's own Secrets Manager as `{"username", "password"}` under the AWS naming convention (`rds!cluster-<uuid>`), and returns `MasterUserSecret` (`SecretArn`, `SecretStatus`, `KmsKeyId`) from create/describe/modify. `ModifyDBCluster(RotateMasterUserPassword=true, ApplyImmediately=true)` rotates the real database login through the same path as an explicit password change — including the pending-rotation behavior for stopped compute — and promotes the new credentials to `AWSCURRENT` (previous ones stay readable as `AWSPREVIOUS`); a rotation whose managed secret was deleted out from under RDS fails with `InvalidDBClusterStateFault` and flips `SecretStatus` to `impaired`, as on AWS. `DeleteDBCluster` deletes the managed secret with the cluster (and only when the delete actually succeeds). AWS-exact rejections: `ManageMasterUserPassword` + explicit `MasterUserPassword` at create, explicit password against a managed cluster, `RotateMasterUserPassword` without a managed secret or without `ApplyImmediately`, and explicit password + rotate flag in one request — validated before anything mutates. The RDS↔Secrets Manager seam is in-process and one-directional (rds → secretsmanager), reusing the emulator's existing stage-promotion and replica-sync internals. Contributed by @kiran01bm.
- **EventBridge — API destination targets are now invoked over HTTP on `PutEvents`** — API destinations and connections were control-plane stubs: a matching rule with an api-destination target logged "unsupported event target ARN" and dropped the event, so webhook-style pipelines (EventBridge → HTTPS endpoint) could not be tested locally. Matching events now POST (or the destination's configured method) to the `InvocationEndpoint` with the input-selected payload (`Input` / `InputPath` / `InputTransformer` apply as for other targets). Connection authorization is honored: `BASIC` populates `Authorization: Basic …`, `API_KEY` sends the configured header, and `OAUTH_CLIENT_CREDENTIALS` exchanges the client ID/secret at the authorization endpoint (`OAuthHttpParameters` merged in, `grant_type=client_credentials` defaulted), caches the token per connection and invalidates it when the connection is deleted, re-authorized, or deauthorized (a connection recreated under a reused name never inherits its predecessor's token), refreshes proactively when it expires within 60 seconds, and refreshes + retries once on a `401`/`407` response — matching documented AWS behavior. Connection `InvocationHttpParameters` and target `HttpParameters` are merged with connection values taking precedence (per the `HttpParameters` API reference), `PathParameterValues` populate `*` path wildcards, and body parameters fold into JSON-object bodies. Requests carry the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations` and `Range` non-overridable, `Content-Type` defaulting to `application/json; charset=utf-8`), strip the headers real EventBridge removes, and time out after 5 seconds (the documented maximum client execution timeout). Delivery runs on a background thread mirroring the SNS HTTP(S) path. Not modeled, mirroring the cross-region FailedInvocations policy: the 24h/185-attempt retry pipeline, `Retry-After`, DLQs, and `InvocationRateLimitPerSecond` — retryable statuses (`401`, `407`, `409`, `429`, `5xx`) are logged and dropped.
### Fixed
- **CloudWatch Logs — ARN-based tag operations resolve vended-delivery resources** — `TagResource`, `UntagResource`, and `ListTagsForResource` only resolved log-group ARNs, so the AWS provider's read-after-create on `aws_cloudwatch_log_delivery_source` / `aws_cloudwatch_log_delivery_destination` / `aws_cloudwatch_log_delivery` failed with `ResourceNotFoundException` and broke `terraform apply` of any stack using EventBridge bus logging (the community EventBridge module ≥ v4.1 provisions the trio). All three operations now resolve the delivery records' tags.
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 2a314685..10c1d85d 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -39,6 +39,7 @@ import hashlib
import json
import logging
import os
+import secrets as stdlib_secrets
import socket
import threading
import time
@@ -55,6 +56,7 @@ from ministack.core.responses import (
get_region,
new_uuid,
)
+from ministack.services import secretsmanager
logger = logging.getLogger("rds")
@@ -3455,11 +3457,26 @@ def _create_db_cluster(p):
explicit_master_user = _p(p, "MasterUsername") or None
explicit_master_pass = _p(p, "MasterUserPassword") or None
explicit_database_name = _p(p, "DatabaseName") or None
+ manage_master_pass = _p(p, "ManageMasterUserPassword") == "true"
+ if manage_master_pass and explicit_master_pass:
+ return _error(
+ "InvalidParameterCombination",
+ "You can't specify MasterUserPassword when ManageMasterUserPassword "
+ "is enabled.",
+ 400,
+ )
global_writer = (
_global_cluster_writer_cluster(global_cluster)
if global_cluster
else None
)
+ if manage_master_pass and global_writer:
+ return _error(
+ "InvalidParameterCombination",
+ "You can't manage the master user password on an Aurora global "
+ "database secondary cluster.",
+ 400,
+ )
if global_writer:
inherited_fields = (
("MasterUsername", explicit_master_user, global_writer.get("MasterUsername")),
@@ -3513,6 +3530,20 @@ def _create_db_cluster(p):
if global_writer
else explicit_master_pass or "password"
)
+ master_user_secret = None
+ if manage_master_pass:
+ master_pass = _generate_master_user_password()
+ secret_arn = secretsmanager.create_secret_in_process(
+ f"rds!cluster-{new_uuid()}",
+ json.dumps({"username": master_user, "password": master_pass}),
+ description=f"Secret managed by RDS for DB cluster {cluster_id}",
+ )
+ master_user_secret = {
+ "SecretArn": secret_arn,
+ "SecretStatus": "active",
+ "KmsKeyId": _p(p, "MasterUserSecretKmsKeyId")
+ or f"arn:aws:kms:{get_region()}:{get_account_id()}:key/aws-secretsmanager-default",
+ }
database_name = (
global_writer.get("DatabaseName")
if global_writer
@@ -3528,6 +3559,7 @@ def _create_db_cluster(p):
"Status": "available",
"MasterUsername": master_user,
"_MasterUserPassword": master_pass,
+ "MasterUserSecret": master_user_secret,
"DatabaseName": database_name,
"NetworkType": _p(p, "NetworkType") or "IPV4",
"EngineLifecycleSupport": _p(p, "EngineLifecycleSupport") or "open-source-rds-extended-support",
@@ -3648,6 +3680,10 @@ def _delete_db_cluster(p):
)
_tags.pop(cluster["DBClusterArn"], None)
del _clusters[cluster["DBClusterIdentifier"]]
+ master_user_secret = cluster.get("MasterUserSecret")
+ if master_user_secret and master_user_secret.get("SecretArn"):
+ # RDS deletes its managed master user secret with the cluster.
+ secretsmanager.delete_secret_in_process(master_user_secret["SecretArn"])
return _xml(200, "DeleteDBClusterResponse",
f"<DeleteDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></DeleteDBClusterResult>")
@@ -3673,6 +3709,15 @@ def _describe_db_clusters(p):
f"<DescribeDBClustersResult><DBClusters>{members}</DBClusters></DescribeDBClustersResult>")
+def _generate_master_user_password():
+ """Generate a random master user password for a managed secret.
+
+ Stays within RDS's password rules (printable ASCII excluding '/', '@',
+ '"', and spaces) — token_urlsafe only emits letters, digits, '-' and '_'.
+ """
+ return stdlib_secrets.token_urlsafe(24)
+
+
def _rotate_real_password(cluster, old_pass, new_pass):
"""Rotate the real cluster master login before publishing new metadata."""
cluster_id = cluster.get("DBClusterIdentifier", "")
@@ -3770,6 +3815,51 @@ def _rotate_real_password(cluster, old_pass, new_pass):
pass
+def _apply_cluster_master_password_change(cluster, new_pass):
+ """Publish *new_pass* as the cluster's master password and rotate the real
+ database login.
+
+ Shared by the explicit ``MasterUserPassword`` and the managed
+ ``RotateMasterUserPassword`` paths so the compute-availability and
+ pending-rotation semantics cannot drift between them. When compute is
+ down but storage survives, the rotation is parked as pending: the first
+ replacement member authenticates with the old password, applies the
+ pending rotation, then publishes readiness using the new one.
+ """
+ with _shared_container_lock:
+ old_pass = cluster.get("_MasterUserPassword", "password")
+ cluster["_MasterUserPassword"] = new_pass
+ pending_rotation = cluster.get(
+ "_pending_master_password_rotation",
+ )
+ rotation_old_pass = (
+ pending_rotation["old_password"]
+ if pending_rotation
+ else old_pass
+ )
+ has_available_compute = bool(
+ cluster.get("DBClusterMembers"),
+ ) and bool(
+ cluster.get("_shared_container_id"),
+ ) and cluster.get("_shared_container_ready", True)
+ if has_available_compute and _rotate_real_password(
+ cluster, rotation_old_pass, new_pass,
+ ):
+ cluster.pop("_pending_master_password_rotation", None)
+ _sync_global_mysql_credentials(cluster)
+ elif (
+ cluster.get("_shared_container_id")
+ or cluster.get("_shared_storage_initialized")
+ ):
+ # The stopped preserved container still has rotation_old_pass.
+ # The first replacement member authenticates with it, applies
+ # the pending rotation, then publishes readiness using new_pass.
+ cluster["_pending_master_password_rotation"] = {
+ "old_password": rotation_old_pass,
+ "new_password": new_pass,
+ }
+
+
def _modify_db_cluster(p):
cluster_id = _p(p, "DBClusterIdentifier")
cluster = _resolve_cluster_in_request_region(cluster_id)
@@ -3779,48 +3869,67 @@ def _modify_db_cluster(p):
return wrong_region
return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)
+ # Validate the password parameters together before mutating anything, so
+ # a rejected combination cannot leave a half-applied password change.
+ if _p(p, "MasterUserPassword") and _p(p, "RotateMasterUserPassword") == "true":
+ return _error(
+ "InvalidParameterCombination",
+ "You can't specify MasterUserPassword and RotateMasterUserPassword "
+ "in the same request.",
+ 400,
+ )
if _p(p, "EngineVersion"):
cluster["EngineVersion"] = _p(p, "EngineVersion")
if _p(p, "MasterUserPassword"):
+ if cluster.get("MasterUserSecret"):
+ return _error(
+ "InvalidParameterCombination",
+ "You can't specify MasterUserPassword for a cluster with "
+ "ManageMasterUserPassword enabled.",
+ 400,
+ )
if _mysql_replication_secondary(cluster):
return _error(
"InvalidDBClusterStateFault",
"MasterUserPassword must be changed on the global writer.",
400,
)
- new_pass = _p(p, "MasterUserPassword")
- with _shared_container_lock:
- old_pass = cluster.get("_MasterUserPassword", "password")
- cluster["_MasterUserPassword"] = new_pass
- pending_rotation = cluster.get(
- "_pending_master_password_rotation",
+ _apply_cluster_master_password_change(cluster, _p(p, "MasterUserPassword"))
+ if _p(p, "RotateMasterUserPassword") == "true":
+ master_user_secret = cluster.get("MasterUserSecret")
+ if not master_user_secret:
+ return _error(
+ "InvalidParameterCombination",
+ "You can only rotate the master user password when it's "
+ "managed by RDS in AWS Secrets Manager.",
+ 400,
)
- rotation_old_pass = (
- pending_rotation["old_password"]
- if pending_rotation
- else old_pass
+ if _p(p, "ApplyImmediately") != "true":
+ return _error(
+ "InvalidParameterCombination",
+ "You must specify apply immediately when rotating the master "
+ "user password.",
+ 400,
)
- has_available_compute = bool(
- cluster.get("DBClusterMembers"),
- ) and bool(
- cluster.get("_shared_container_id"),
- ) and cluster.get("_shared_container_ready", True)
- if has_available_compute and _rotate_real_password(
- cluster, rotation_old_pass, new_pass,
- ):
- cluster.pop("_pending_master_password_rotation", None)
- _sync_global_mysql_credentials(cluster)
- elif (
- cluster.get("_shared_container_id")
- or cluster.get("_shared_storage_initialized")
- ):
- # The stopped preserved container still has rotation_old_pass.
- # The first replacement member authenticates with it, applies
- # the pending rotation, then publishes readiness using new_pass.
- cluster["_pending_master_password_rotation"] = {
- "old_password": rotation_old_pass,
- "new_password": new_pass,
- }
+ new_pass = _generate_master_user_password()
+ secret_updated = secretsmanager.put_secret_value_in_process(
+ master_user_secret["SecretArn"],
+ json.dumps({
+ "username": cluster.get("MasterUsername", "admin"),
+ "password": new_pass,
+ }),
+ )
+ if not secret_updated:
+ # The secret was deleted out from under RDS. AWS reports such a
+ # secret as impaired: usable state is gone and it can't be rotated.
+ master_user_secret["SecretStatus"] = "impaired"
+ return _error(
+ "InvalidDBClusterStateFault",
+ f"The master user secret for DB cluster {cluster_id} "
+ "can't be rotated.",
+ 400,
+ )
+ _apply_cluster_master_password_change(cluster, new_pass)
if _p(p, "Port"):
cluster["Port"] = int(_p(p, "Port"))
if _p(p, "BackupRetentionPeriod"):
@@ -5561,6 +5670,21 @@ def _cluster_xml(c):
if global_write_forwarding else ""
)
+ # AWS emits <MasterUserSecret> only for clusters with an RDS-managed
+ # master user password; KmsKeyId appears only when a key was specified.
+ master_user_secret = c.get("MasterUserSecret")
+ master_user_secret_xml = ""
+ if master_user_secret:
+ kms_key_id = master_user_secret.get("KmsKeyId")
+ kms_key_xml = f"<KmsKeyId>{kms_key_id}</KmsKeyId>" if kms_key_id else ""
+ master_user_secret_xml = (
+ "<MasterUserSecret>"
+ f"<SecretArn>{master_user_secret.get('SecretArn', '')}</SecretArn>"
+ f"<SecretStatus>{master_user_secret.get('SecretStatus', 'active')}</SecretStatus>"
+ f"{kms_key_xml}"
+ "</MasterUserSecret>"
+ )
+
return f"""<DBClusterIdentifier>{c['DBClusterIdentifier']}</DBClusterIdentifier>
<DBClusterArn>{c['DBClusterArn']}</DBClusterArn>
<Engine>{c['Engine']}</Engine>
@@ -5600,6 +5724,7 @@ def _cluster_xml(c):
<NetworkType>{c.get('NetworkType','IPV4')}</NetworkType>
{global_cluster_xml}
{global_write_forwarding_xml}
+ {master_user_secret_xml}
<EngineLifecycleSupport>{c.get('EngineLifecycleSupport','open-source-rds-extended-support')}</EngineLifecycleSupport>"""
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index 47813772..0805723b 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -176,6 +176,45 @@ def resolve_secret_string(secret_id, version_stage="AWSCURRENT"):
return ver.get("SecretString")
+def create_secret_in_process(name, secret_string, description=""):
+ """Create a secret on behalf of another service (e.g. RDS managed master
+ user passwords) without going through the HTTP API.
+
+ The seam is one-directional: other services call into Secrets Manager,
+ never the reverse. Returns the new secret's ARN, or None when a secret
+ named *name* already exists.
+ """
+ if name in _secrets:
+ return None
+ arn, _ = _store_new_secret(name, secret_string=secret_string, description=description)
+ return arn
+
+
+def put_secret_value_in_process(secret_id, secret_string):
+ """Store a new AWSCURRENT version for *secret_id* on behalf of another
+ service, promoting stages the same way UpdateSecret does (old AWSCURRENT
+ becomes AWSPREVIOUS). Returns True on success, False when the secret does
+ not exist or is scheduled for deletion.
+ """
+ _, secret = _resolve(secret_id, use_arn_scope=True)
+ if not secret or secret.get("DeletedDate"):
+ return False
+ _publish_new_version(secret, secret_string=secret_string)
+ return True
+
+
+def delete_secret_in_process(secret_id):
+ """Force-delete *secret_id* on behalf of another service (no recovery
+ window — mirrors RDS deleting its managed master user secret when the
+ owning resource is deleted). Returns True when a secret was deleted.
+ """
+ key, secret = _resolve(secret_id, use_arn_scope=True)
+ if not secret:
+ return False
+ _purge_secret(key, secret)
+ return True
+
+
def _emit_secret_label_updated(secret, label, version_id):
"""Native Secrets Manager → EventBridge ``Secret Label Updated`` event, fired
when a staging label moves to a new version — for every label except
@@ -243,6 +282,34 @@ def _apply_current_promotion(secret, new_vid):
_emit_secret_label_updated(secret, "AWSCURRENT", new_vid)
+def _publish_new_version(secret, secret_string=None, secret_binary=None):
+ """Add a new version to *secret* and promote it to AWSCURRENT.
+
+ Shared by ``UpdateSecret`` and the in-process seam so stage promotion and
+ replica sync cannot drift between the two paths. Returns the version id.
+ """
+ vid = new_uuid()
+ now = int(time.time())
+ secret["Versions"][vid] = {
+ "SecretString": secret_string,
+ "SecretBinary": secret_binary,
+ "CreatedDate": now,
+ "Stages": [],
+ }
+ _apply_current_promotion(secret, vid)
+ secret["LastChangedDate"] = now
+ _sync_replicas(secret)
+ return vid
+
+
+def _purge_secret(key, secret):
+ """Remove *secret* (stored under *key*) and everything hanging off it:
+ replicas and any orphaned resource policy."""
+ _delete_replicas(secret)
+ del _secrets[key]
+ _resource_policies.pop(secret["ARN"], None)
+
+
def _vid_to_stages(secret):
return {vid: list(ver["Stages"]) for vid, ver in secret["Versions"].items() if ver["Stages"]}
@@ -424,16 +491,13 @@ async def handle_request(method, path, headers, body, query_params):
# Actions
# ---------------------------------------------------------------------------
-def _create_secret(data):
- name = data.get("Name")
- if not name:
- return error_response_json("InvalidParameterException", "Name is required.", 400)
- if name in _secrets:
- return error_response_json(
- "ResourceExistsException",
- f"The operation failed because the secret {name} already exists.", 400,
- )
+def _store_new_secret(name, secret_string=None, secret_binary=None, description="",
+ tags=None, kms_key_id=None, rotation_lambda_arn=None,
+ rotation_rules=None):
+ """Store a brand-new secret; the caller must have checked *name* is free.
+ Returns ``(arn, version_id)`` of the created secret.
+ """
arn = f"arn:aws:secretsmanager:{get_region()}:{get_account_id()}:secret:{name}-{new_uuid()[:6]}"
vid = new_uuid()
now = int(time.time())
@@ -441,26 +505,49 @@ def _create_secret(data):
_secrets[name] = {
"ARN": arn,
"Name": name,
- "Description": data.get("Description", ""),
- "Tags": list(data.get("Tags", [])),
+ "Description": description,
+ "Tags": list(tags or []),
"CreatedDate": now,
"LastChangedDate": now,
"LastAccessedDate": None,
"DeletedDate": None,
"RotationEnabled": False,
- "RotationLambdaARN": data.get("RotationLambdaARN"),
- "RotationRules": data.get("RotationRules"),
- "KmsKeyId": data.get("KmsKeyId"),
+ "RotationLambdaARN": rotation_lambda_arn,
+ "RotationRules": rotation_rules,
+ "KmsKeyId": kms_key_id,
"ReplicationStatus": [],
"Versions": {
vid: {
- "SecretString": data.get("SecretString"),
- "SecretBinary": data.get("SecretBinary"),
+ "SecretString": secret_string,
+ "SecretBinary": secret_binary,
"CreatedDate": now,
"Stages": ["AWSCURRENT"],
}
},
}
+ return arn, vid
+
+
+def _create_secret(data):
+ name = data.get("Name")
+ if not name:
+ return error_response_json("InvalidParameterException", "Name is required.", 400)
+ if name in _secrets:
+ return error_response_json(
+ "ResourceExistsException",
+ f"The operation failed because the secret {name} already exists.", 400,
+ )
+
+ arn, vid = _store_new_secret(
+ name,
+ secret_string=data.get("SecretString"),
+ secret_binary=data.get("SecretBinary"),
+ description=data.get("Description", ""),
+ tags=data.get("Tags"),
+ kms_key_id=data.get("KmsKeyId"),
+ rotation_lambda_arn=data.get("RotationLambdaARN"),
+ rotation_rules=data.get("RotationRules"),
+ )
return json_response({"ARN": arn, "Name": name, "VersionId": vid})
@@ -635,13 +722,11 @@ def _delete_secret(data):
if force:
arn, sname = secret["ARN"], secret["Name"]
- _delete_replicas(secret)
- del _secrets[key]
- # Clean up any associated resource policy too — otherwise it
- # lingers as an orphan keyed by the now-deleted ARN, invisible
- # to the API but still consuming memory and surviving warm
- # boot via the persistence path.
- _resource_policies.pop(arn, None)
+ # _purge_secret also cleans up any associated resource policy —
+ # otherwise it lingers as an orphan keyed by the now-deleted ARN,
+ # invisible to the API but still consuming memory and surviving
+ # warm boot via the persistence path.
+ _purge_secret(key, secret)
return json_response({"ARN": arn, "Name": sname, "DeletionDate": deletion_date})
secret["DeletedDate"] = deletion_date
@@ -696,17 +781,11 @@ def _update_secret(data):
_sync_replicas(secret)
return json_response({"ARN": secret["ARN"], "Name": secret["Name"]})
- vid = new_uuid()
- now = int(time.time())
- secret["Versions"][vid] = {
- "SecretString": data.get("SecretString"),
- "SecretBinary": data.get("SecretBinary"),
- "CreatedDate": now,
- "Stages": [],
- }
- _apply_current_promotion(secret, vid)
- secret["LastChangedDate"] = now
- _sync_replicas(secret)
+ vid = _publish_new_version(
+ secret,
+ secret_string=data.get("SecretString"),
+ secret_binary=data.get("SecretBinary"),
+ )
return json_response({"ARN": secret["ARN"], "Name": secret["Name"], "VersionId": vid})
diff --git a/tests/test_rds.py b/tests/test_rds.py
index 76e87b50..6d5eaf52 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -8708,3 +8708,338 @@ def test_aurora_mysql_global_replication_replays_and_streams_rows():
_delete_cluster(west, secondary_id)
_delete_cluster(east, primary_id)
_delete_global_cluster(east, global_id)
+
+
+# ---------------------------------------------------------------------------
+# ManageMasterUserPassword — RDS-managed master user secrets
+# ---------------------------------------------------------------------------
+
+def test_rds_manage_master_user_password_creates_secret(rds, sm):
+ """CreateDBCluster(ManageMasterUserPassword=True) returns MasterUserSecret
+ and stores real credentials in Secrets Manager as {username, password}."""
+ cluster_id = "managed-secret-cluster"
+ resp = rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ ManageMasterUserPassword=True,
+ )
+ try:
+ secret_meta = resp["DBCluster"]["MasterUserSecret"]
+ assert secret_meta["SecretStatus"] == "active"
+ arn = secret_meta["SecretArn"]
+ assert arn.startswith("arn:aws:secretsmanager:")
+ assert "rds!cluster-" in arn
+ assert secret_meta["KmsKeyId"]
+
+ # Round-trips through DescribeDBClusters.
+ described = rds.describe_db_clusters(DBClusterIdentifier=cluster_id)
+ assert described["DBClusters"][0]["MasterUserSecret"] == secret_meta
+
+ value = sm.get_secret_value(SecretId=arn)
+ creds = json.loads(value["SecretString"])
+ assert creds["username"] == "admin"
+ assert creds["password"]
+ described_secret = sm.describe_secret(SecretId=arn)
+ assert cluster_id in described_secret["Description"]
+ finally:
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+
+
+def test_rds_manage_master_user_password_rejects_explicit_password(rds):
+ """ManageMasterUserPassword and MasterUserPassword are mutually exclusive."""
+ with pytest.raises(ClientError) as exc:
+ rds.create_db_cluster(
+ DBClusterIdentifier="managed-vs-explicit",
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ MasterUserPassword="password123",
+ ManageMasterUserPassword=True,
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"
+
+
+def test_rds_modify_rejects_explicit_password_on_managed_cluster(rds):
+ """A cluster with an RDS-managed secret can't take an explicit password."""
+ cluster_id = "managed-no-explicit-modify"
+ rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ ManageMasterUserPassword=True,
+ )
+ try:
+ with pytest.raises(ClientError) as exc:
+ rds.modify_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ MasterUserPassword="explicit-password",
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"
+ finally:
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+
+
+def test_rds_rotate_master_password_requires_managed_secret(rds):
+ """RotateMasterUserPassword on a cluster without a managed secret rejects."""
+ cluster_id = "unmanaged-rotate"
+ rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ MasterUserPassword="password123",
+ )
+ try:
+ with pytest.raises(ClientError) as exc:
+ rds.modify_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ RotateMasterUserPassword=True,
+ ApplyImmediately=True,
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"
+ finally:
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+
+
+def test_rds_rotate_master_password_requires_apply_immediately(rds):
+ """Rotation must be requested with ApplyImmediately, as on real AWS."""
+ cluster_id = "managed-rotate-no-apply"
+ rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ ManageMasterUserPassword=True,
+ )
+ try:
+ with pytest.raises(ClientError) as exc:
+ rds.modify_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ RotateMasterUserPassword=True,
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterCombination"
+ finally:
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+
+
+def test_rds_rotate_master_password_rejects_explicit_password_combo():
+ """MasterUserPassword and RotateMasterUserPassword can't share a request,
+ and the rejected request must not half-apply the explicit password."""
+ from ministack.services import rds as m
+
+ m._clusters.clear()
+ try:
+ m._create_db_cluster({
+ "DBClusterIdentifier": "rotate-explicit-combo",
+ "Engine": "aurora-postgresql",
+ "MasterUsername": "admin",
+ "MasterUserPassword": "password123",
+ })
+ status, _headers, body = m._modify_db_cluster({
+ "DBClusterIdentifier": "rotate-explicit-combo",
+ "MasterUserPassword": "new-password",
+ "RotateMasterUserPassword": "true",
+ "ApplyImmediately": "true",
+ })
+ assert status == 400
+ assert b"InvalidParameterCombination" in body
+ cluster = m._clusters.get("rotate-explicit-combo")
+ assert cluster["_MasterUserPassword"] == "password123"
+ finally:
+ m._clusters.clear()
+
+
+def test_rds_rotate_master_password_promotes_new_secret_version(rds, sm):
+ """Managed rotation publishes a fresh AWSCURRENT and keeps the previous
+ credentials reachable as AWSPREVIOUS."""
+ cluster_id = "managed-rotate-cluster"
+ resp = rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ ManageMasterUserPassword=True,
+ )
+ arn = resp["DBCluster"]["MasterUserSecret"]["SecretArn"]
+ try:
+ before = json.loads(
+ sm.get_secret_value(SecretId=arn)["SecretString"])
+
+ rds.modify_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ RotateMasterUserPassword=True,
+ ApplyImmediately=True,
+ )
+
+ after = json.loads(
+ sm.get_secret_value(SecretId=arn)["SecretString"])
+ assert after["username"] == "admin"
+ assert after["password"] != before["password"]
+
+ previous = json.loads(sm.get_secret_value(
+ SecretId=arn, VersionStage="AWSPREVIOUS")["SecretString"])
+ assert previous == before
+ finally:
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+
+
+def test_rds_rotate_master_password_rotates_real_login(monkeypatch):
+ """With live compute, managed rotation drives the real database password
+ change through the same path as an explicit MasterUserPassword change."""
+ from ministack.services import rds as m
+ from ministack.services import secretsmanager as sm
+
+ rotations = []
+
+ def _rotate(_cluster, old_password, new_password):
+ rotations.append((old_password, new_password))
+ return True
+
+ monkeypatch.setattr(m, "_rotate_real_password", _rotate)
+
+ m._clusters.clear()
+ try:
+ m._create_db_cluster({
+ "DBClusterIdentifier": "managed-live-rotate",
+ "Engine": "aurora-postgresql",
+ "MasterUsername": "admin",
+ "ManageMasterUserPassword": "true",
+ })
+ cluster = m._clusters.get("managed-live-rotate")
+ old_pass = cluster["_MasterUserPassword"]
+ cluster.update({
+ "DBClusterMembers": [{
+ "DBInstanceIdentifier": "managed-live-writer",
+ "IsClusterWriter": True,
+ }],
+ "_shared_container_id": "managed-live-container",
+ "_shared_container_ready": True,
+ })
+
+ m._modify_db_cluster({
+ "DBClusterIdentifier": "managed-live-rotate",
+ "RotateMasterUserPassword": "true",
+ "ApplyImmediately": "true",
+ })
+
+ new_pass = cluster["_MasterUserPassword"]
+ assert rotations == [(old_pass, new_pass)]
+ assert new_pass != old_pass
+ assert "_pending_master_password_rotation" not in cluster
+
+ # The secret's AWSCURRENT matches what the database now accepts.
+ secret_string = sm.resolve_secret_string(
+ cluster["MasterUserSecret"]["SecretArn"])
+ assert json.loads(secret_string)["password"] == new_pass
+ finally:
+ arn = (m._clusters.get("managed-live-rotate") or {}).get(
+ "MasterUserSecret", {})
+ if arn and arn.get("SecretArn"):
+ sm.delete_secret_in_process(arn["SecretArn"])
+ m._clusters.clear()
+
+
+def test_rds_rotate_master_password_parks_pending_without_compute(monkeypatch):
+ """When compute is stopped but storage survives, managed rotation parks the
+ change as a pending rotation exactly like an explicit password change."""
+ from ministack.services import rds as m
+ from ministack.services import secretsmanager as sm
+
+ monkeypatch.setattr(m, "_rotate_real_password", lambda *_args: False)
+
+ m._clusters.clear()
+ try:
+ m._create_db_cluster({
+ "DBClusterIdentifier": "managed-pending-rotate",
+ "Engine": "aurora-postgresql",
+ "MasterUsername": "admin",
+ "ManageMasterUserPassword": "true",
+ })
+ cluster = m._clusters.get("managed-pending-rotate")
+ old_pass = cluster["_MasterUserPassword"]
+ cluster["_shared_storage_initialized"] = True
+
+ m._modify_db_cluster({
+ "DBClusterIdentifier": "managed-pending-rotate",
+ "RotateMasterUserPassword": "true",
+ "ApplyImmediately": "true",
+ })
+
+ new_pass = cluster["_MasterUserPassword"]
+ assert new_pass != old_pass
+ assert cluster["_pending_master_password_rotation"] == {
+ "old_password": old_pass,
+ "new_password": new_pass,
+ }
+ finally:
+ arn = (m._clusters.get("managed-pending-rotate") or {}).get(
+ "MasterUserSecret", {})
+ if arn and arn.get("SecretArn"):
+ sm.delete_secret_in_process(arn["SecretArn"])
+ m._clusters.clear()
+
+
+def test_rds_rotate_master_password_deleted_secret_reports_impaired(rds, sm):
+ """Rotation after the managed secret was deleted out from under RDS fails
+ and flips SecretStatus to impaired, mirroring AWS's impaired state."""
+ cluster_id = "managed-impaired-cluster"
+ resp = rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ ManageMasterUserPassword=True,
+ )
+ arn = resp["DBCluster"]["MasterUserSecret"]["SecretArn"]
+ try:
+ sm.delete_secret(SecretId=arn, ForceDeleteWithoutRecovery=True)
+ with pytest.raises(ClientError) as exc:
+ rds.modify_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ RotateMasterUserPassword=True,
+ ApplyImmediately=True,
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidDBClusterStateFault"
+ cluster = rds.describe_db_clusters(
+ DBClusterIdentifier=cluster_id)["DBClusters"][0]
+ assert cluster["MasterUserSecret"]["SecretStatus"] == "impaired"
+ finally:
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+
+
+def test_rds_delete_cluster_removes_managed_secret(rds, sm):
+ """DeleteDBCluster deletes the RDS-managed secret with the cluster."""
+ cluster_id = "managed-delete-cluster"
+ resp = rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ ManageMasterUserPassword=True,
+ )
+ arn = resp["DBCluster"]["MasterUserSecret"]["SecretArn"]
+ sm.get_secret_value(SecretId=arn) # exists before delete
+
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+
+ with pytest.raises(ClientError) as exc:
+ sm.get_secret_value(SecretId=arn)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_rds_delete_protected_cluster_keeps_managed_secret(rds, sm):
+ """A rejected DeleteDBCluster must not delete the managed secret."""
+ cluster_id = "managed-protected-cluster"
+ resp = rds.create_db_cluster(
+ DBClusterIdentifier=cluster_id,
+ Engine="aurora-postgresql",
+ MasterUsername="admin",
+ ManageMasterUserPassword=True,
+ DeletionProtection=True,
+ )
+ arn = resp["DBCluster"]["MasterUserSecret"]["SecretArn"]
+ try:
+ with pytest.raises(ClientError):
+ rds.delete_db_cluster(
+ DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)
+ # Secret survives the rejected delete.
+ sm.get_secret_value(SecretId=arn)
+ finally:
+ rds.modify_db_cluster(
+ DBClusterIdentifier=cluster_id, DeletionProtection=False)
+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)