fix(secretsmanager,rds): rotate secrets that an AWS service manages (#2378)

* fix(secretsmanager): rotate secrets that an AWS service manages

RotateSecret required a rotation Lambda for every secret, so a secret RDS
manages through ManageMasterUserPassword could never enable rotation:

  InvalidRequestException: You tried to enable rotation on a secret that
  doesn't already have a Lambda function ARN configured and you didn't
  include such an ARN as a parameter in this call.

AWS rotates those secrets itself, so they carry no Lambda at all. It accepts
RotateSecret with rotation rules alone, and refuses a Lambda ARN outright:
"Rotation Lambda ARN is not supported for a service-managed secret."

Key the behaviour off ownership rather than the rds! name prefix, since
anyone may create an ordinary secret called rds!something and that must not
grant it managed-rotation semantics:

- Secret carries an owningService, set by floci services only and never
  settable over the wire
- RDS marks the master user secret it creates as owned by rds, with the two
  tags AWS attaches to it
- RotateSecret needs no Lambda for an owned secret, rejects one, and skips
  the Lambda rotation lifecycle that has nothing to invoke
- DescribeSecret and ListSecrets report OwningService, and the owning-service
  ListSecrets filter matches on it instead of always returning nothing

Covered by unit tests and by a CLI compatibility test that walks the whole
path: create the instance with --manage-master-user-password, describe the
secret it produced, then rotate it with rules and no Lambda ARN.

Behaviour confirmed against a live AWS account: a db.t3.micro postgres
instance created with --manage-master-user-password, then describe-secret and
rotate-secret against the secret it produced.

* fix(secretsmanager): keep managed rotation across restarts, report a real version

Two problems in the previous commit:

A secret persisted before ownership tracking deserializes without an owning
service, so after an upgrade RotateSecret went on rejecting the Lambda-free
call these secrets are rotated with. RDS backfills ownership at startup from
the instances that name those secrets: RDS state is what makes a secret
managed, so that is what the backfill reads, never the secret's name.

RotateSecret answered a service-managed rotation with the request token as
VersionId, while nothing stages a version for that token, so reading the
advertised version failed with "can't find the specified secret version".
Report the current version instead, which exists and holds the value a caller
reads back.

* fix(secretsmanager): back-fill ownership per account, stop claiming a rotation

The startup backfill ran outside any request, so the secrets store resolved the
default account while the instances it read span every account. Secrets owned by
another account were left unmarked, and a same-named default-account secret could
be written instead. The secret's ARN names its own account and region, so
markOwnedByService takes the ARN and addresses that account's store directly.

RotateSecret also recorded LastRotatedDate for a service-managed secret while
neither the master password nor the stored value changed, so the secret claimed a
rotation that GetSecretValue and the database would contradict. floci does not
re-issue the credential, so it no longer reports one: rotation is enabled and
scheduled, and NextRotationDate still follows from the rules.

* fix(rds): never fail startup on the master user secret backfill

The backfill reads persisted state at StartupEvent, so a storage error while
scanning instances would have stopped the emulator from starting over work that
is not needed to serve requests. It now logs and moves on, per instance and for
the scan as a whole.

* fix(rds): run the secret ownership backfill after storage is loaded

The backfill observed StartupEvent, as does EmulatorLifecycle.onStart, which
calls storageFactory.loadAll(). Two observers of one event have no ordering
between them, so under hybrid or WAL storage the backfill could write ownership
into memory that the reload then replaced with the older on-disk secret, leaving
rotation rejected exactly where the backfill exists to help.

It now hangs off restorePersistedRuntime(), which the lifecycle already calls
after loadAll() for the same reason, alongside the other persisted-state fixups.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-18 17:38:11 -04:00
1 parent ba9ce84242
commit 23015a7475
9 files changed
+508 -9

No files matched your search

@@ -276,7 +276,7 @@ class RdsServiceTest {
SecretsManagerService secretsManager = mock(SecretsManagerService.class);
Secret secret = new Secret();
secret.setArn("arn:aws:secretsmanager:us-east-1:123456789012:secret:rds!db-secret");
when(secretsManager.createSecret(any(), any(), eq(null), any(), eq("kms-key-1"), eq(null), eq("us-east-1")))
when(secretsManager.createSecret(any(), any(), eq(null), any(), eq("kms-key-1"), any(), eq("rds"), eq("us-east-1")))
.thenReturn(secret);
RdsService service = newService(containerManager, proxyManager,
new InMemoryStorage<>(), new InMemoryStorage<>(),
@@ -295,11 +295,107 @@ class RdsServiceTest {
ArgumentCaptor<String> secretName = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> secretString = ArgumentCaptor.forClass(String.class);
verify(secretsManager).createSecret(secretName.capture(), secretString.capture(), eq(null), any(), eq("kms-key-1"), eq(null), eq("us-east-1"));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Secret.Tag>> secretTags = ArgumentCaptor.forClass(List.class);
verify(secretsManager).createSecret(secretName.capture(), secretString.capture(), eq(null), any(),
eq("kms-key-1"), secretTags.capture(), eq("rds"), eq("us-east-1"));
assertTrue(secretName.getValue().startsWith("rds!db-"));
assertTrue(secretString.getValue().contains("\"username\":\"admin\""));
assertTrue(secretString.getValue().contains("\"password\":\"" + instance.getMasterPassword() + "\""));
assertTrue(secretString.getValue().contains("\"dbInstanceIdentifier\":\"mydb\""));
// AWS marks the secret it manages with both of these tags, alongside OwningService.
assertTrue(secretTags.getValue().contains(
new Secret.Tag("aws:secretsmanager:owningService", "rds")));
assertTrue(secretTags.getValue().contains(
new Secret.Tag("aws:rds:primaryDBInstanceArn", instance.getDbInstanceArn())));
}
@Test
void backfillMarksMasterUserSecretsOfPersistedInstances() {
SecretsManagerService secretsManager = mock(SecretsManagerService.class);
Secret secret = new Secret();
String secretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:rds!db-secret";
secret.setArn(secretArn);
when(secretsManager.createSecret(any(), any(), eq(null), any(), eq(null), any(), eq("rds"), eq("us-east-1")))
.thenReturn(secret);
RdsService service = newService(containerManager, proxyManager,
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
secretsManager);
service.createDbInstance("mydb", "postgres", "13",
"admin", null, "dbname", "db.t3.micro",
20, true, null, null, null, true, null);
// An instance persisted by a floci that predates ownership tracking still names its
// secret, which is what makes that secret managed — the name never is.
service.backfillManagedSecretOwnership();
verify(secretsManager).markOwnedByService(secretArn, "rds");
}
@Test
void restorePersistedRuntimeRunsTheOwnershipBackfill() {
// The lifecycle calls restorePersistedRuntime() after storageFactory.loadAll(), so the
// backfill hangs off that rather than off its own StartupEvent observer, which would have
// no ordering against the reload.
SecretsManagerService secretsManager = mock(SecretsManagerService.class);
Secret restored = new Secret();
String restoredArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:rds!db-secret";
restored.setArn(restoredArn);
when(secretsManager.createSecret(any(), any(), eq(null), any(), eq(null), any(), eq("rds"), eq("us-east-1")))
.thenReturn(restored);
RdsService service = newService(containerManager, proxyManager,
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
secretsManager);
service.createDbInstance("mydb", "postgres", "13",
"admin", null, "dbname", "db.t3.micro",
20, true, null, null, null, true, null);
service.restorePersistedRuntime();
verify(secretsManager).markOwnedByService(restoredArn, "rds");
}
@Test
void backfillDoesNotStopStartupWhenASecretCannotBeMarked() {
SecretsManagerService secretsManager = mock(SecretsManagerService.class);
Secret secret = new Secret();
secret.setArn("arn:aws:secretsmanager:us-east-1:123456789012:secret:rds!db-secret");
when(secretsManager.createSecret(any(), any(), eq(null), any(), eq(null), any(), eq("rds"), eq("us-east-1")))
.thenReturn(secret);
doThrow(new IllegalStateException("storage unavailable"))
.when(secretsManager).markOwnedByService(any(), any());
RdsService service = newService(containerManager, proxyManager,
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
secretsManager);
service.createDbInstance("mydb", "postgres", "13",
"admin", null, "dbname", "db.t3.micro",
20, true, null, null, null, true, null);
assertDoesNotThrow(() -> service.backfillManagedSecretOwnership());
}
@Test
void backfillIgnoresInstancesWithoutAManagedSecret() {
SecretsManagerService secretsManager = mock(SecretsManagerService.class);
RdsService service = newService(containerManager, proxyManager,
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
secretsManager);
service.createDbInstance("mydb", "postgres", "13",
"admin", "password", "dbname", "db.t3.micro",
20, false, null, null, null);
service.backfillManagedSecretOwnership();
verify(secretsManager, never()).markOwnedByService(any(), any());
}
@Test
@@ -167,6 +167,107 @@ class SecretsManagerJsonHandlerTest {
assertThat(listed.has("TargetAttachmentOwner"), is(false));
}
@Test
void owningServiceIsReportedByDescribeAndList() {
service.createSecret("rds!db-1234", "value", null, null, null, null, "rds", REGION);
ObjectNode describeReq = MAPPER.createObjectNode();
describeReq.put("SecretId", "rds!db-1234");
ObjectNode described = (ObjectNode) handler
.handle("DescribeSecret", describeReq, REGION)
.getEntity();
ObjectNode listed = (ObjectNode) ((ObjectNode) handler
.handle("ListSecrets", MAPPER.createObjectNode(), REGION)
.getEntity())
.path("SecretList")
.path(0);
assertThat(described.get("OwningService").asText(), is("rds"));
assertThat(listed.get("OwningService").asText(), is("rds"));
}
@Test
void listSecretsFiltersByOwningService() {
service.createSecret("rds!db-1234", "value", null, null, null, null, "rds", REGION);
ObjectNode createReq = MAPPER.createObjectNode();
createReq.put("Name", "ordinary-secret");
handler.handle("CreateSecret", createReq, REGION);
ObjectNode listReq = MAPPER.createObjectNode();
listReq.putArray("Filters").addObject().put("Key", "owning-service").putArray("Values").add("rds");
ObjectNode owned = (ObjectNode) handler.handle("ListSecrets", listReq, REGION).getEntity();
assertThat(owned.get("SecretList").size(), is(1));
assertThat(owned.get("SecretList").get(0).get("Name").asText(), is("rds!db-1234"));
// A leading "!" negates a filter, so this selects the secrets no service owns.
ObjectNode negatedReq = MAPPER.createObjectNode();
negatedReq.putArray("Filters").addObject().put("Key", "owning-service").putArray("Values").add("!rds");
ObjectNode unowned = (ObjectNode) handler.handle("ListSecrets", negatedReq, REGION).getEntity();
assertThat(unowned.get("SecretList").size(), is(1));
assertThat(unowned.get("SecretList").get(0).get("Name").asText(), is("ordinary-secret"));
}
@Test
void ownerlessSecretsOmitOwningService() {
ObjectNode createReq = MAPPER.createObjectNode();
createReq.put("Name", "ordinary-secret");
handler.handle("CreateSecret", createReq, REGION);
ObjectNode describeReq = MAPPER.createObjectNode();
describeReq.put("SecretId", "ordinary-secret");
ObjectNode described = (ObjectNode) handler
.handle("DescribeSecret", describeReq, REGION)
.getEntity();
assertThat(described.has("OwningService"), is(false));
}
@Test
void rotateServiceManagedSecretSucceedsOverTheWire() {
service.createSecret("rds!db-5678", "value", null, null, null, null, "rds", REGION);
// The call terraform's aws_secretsmanager_secret_rotation makes for a managed secret:
// rotation rules, no RotationLambdaARN.
ObjectNode rotateReq = MAPPER.createObjectNode();
rotateReq.put("SecretId", "rds!db-5678");
rotateReq.putObject("RotationRules").put("AutomaticallyAfterDays", 7);
Response response = handler.handle("RotateSecret", rotateReq, REGION);
assertThat(response.getStatus(), is(200));
assertThat(((ObjectNode) response.getEntity()).get("Name").asText(), is("rds!db-5678"));
ObjectNode describeReq = MAPPER.createObjectNode();
describeReq.put("SecretId", "rds!db-5678");
ObjectNode described = (ObjectNode) handler
.handle("DescribeSecret", describeReq, REGION)
.getEntity();
assertThat(described.get("RotationEnabled").asBoolean(), is(true));
assertThat(described.path("RotationRules").get("AutomaticallyAfterDays").asInt(), is(7));
assertThat(described.has("RotationLambdaARN"), is(false));
}
@Test
void rotateServiceManagedSecretReturnsAVersionThatResolves() {
service.createSecret("rds!db-9012", "value", null, null, null, null, "rds", REGION);
ObjectNode rotateReq = MAPPER.createObjectNode();
rotateReq.put("SecretId", "rds!db-9012");
rotateReq.putObject("RotationRules").put("AutomaticallyAfterDays", 7);
ObjectNode rotated = (ObjectNode) handler.handle("RotateSecret", rotateReq, REGION).getEntity();
// Nothing stages a version for the request token here, so the reported VersionId has to be
// one a caller can actually read back.
ObjectNode getReq = MAPPER.createObjectNode();
getReq.put("SecretId", "rds!db-9012");
getReq.put("VersionId", rotated.get("VersionId").asText());
Response response = handler.handle("GetSecretValue", getReq, REGION);
assertThat(response.getStatus(), is(200));
assertThat(((ObjectNode) response.getEntity()).get("SecretString").asText(), is("value"));
}
@Test
void listSecretsResponseIncludesKmsKeyId() {
ObjectNode createReq = MAPPER.createObjectNode();
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.secretsmanager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
@@ -326,6 +327,120 @@ class SecretsManagerServiceTest {
org.mockito.Mockito.eq(io.github.hectorvent.floci.services.lambda.model.InvocationType.RequestResponse));
}
@Test
void rotateSecretWithoutLambdaArnThrows() {
service.createSecret("my-secret", "value", null, null, null, null, REGION);
AwsException e = assertThrows(AwsException.class, () ->
service.rotateSecret("my-secret", null, null,
new Secret.RotationRules(30, null, null), true, REGION));
assertEquals("InvalidRequestException", e.getErrorCode());
}
@Test
void rotateServiceManagedSecretNeedsNoLambdaArn() {
io.github.hectorvent.floci.services.lambda.LambdaService mockLambda =
org.mockito.Mockito.mock(io.github.hectorvent.floci.services.lambda.LambdaService.class);
SecretsManagerService svc = new SecretsManagerService(
new InMemoryStorage<String, Secret>(), 30,
new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "000000000000"),
mockLambda, new com.fasterxml.jackson.databind.ObjectMapper());
// The secret RDS manages: rotated by RDS itself, so it carries no rotation Lambda.
svc.createSecret("rds!db-1234", "value", null, null, null, null, "rds", REGION);
Secret rotated = svc.rotateSecret("rds!db-1234", null, null,
new Secret.RotationRules(7, null, null), true, REGION);
assertTrue(rotated.isRotationEnabled());
assertEquals(7, rotated.getRotationRules().automaticallyAfterDays());
// floci does not re-issue the credential, so it must not claim a rotation happened.
assertNull(rotated.getLastRotatedDate());
assertNull(rotated.getRotationLambdaArn());
// No Lambda exists to drive the rotation lifecycle, so none may be invoked.
org.mockito.Mockito.verifyNoInteractions(mockLambda);
}
@Test
void rotateServiceManagedSecretRejectsLambdaArn() {
service.createSecret("rds!db-1234", "value", null, null, null, null, "rds", REGION);
AwsException e = assertThrows(AwsException.class, () ->
service.rotateSecret("rds!db-1234", null,
"arn:aws:lambda:us-east-1:000000000000:function:rotate",
new Secret.RotationRules(7, null, null), true, REGION));
assertEquals("InvalidRequestException", e.getErrorCode());
assertEquals("Rotation Lambda ARN is not supported for a service-managed secret.", e.getMessage());
}
@Test
void markOwnedByServiceLetsAPersistedSecretRotateAsManaged() {
// A secret stored before floci tracked ownership deserializes without an owning service.
String arn = service.createSecret("rds!db-1234", "value", null, null, null, null, REGION).getArn();
assertThrows(AwsException.class, () ->
service.rotateSecret("rds!db-1234", null, null,
new Secret.RotationRules(7, null, null), true, REGION));
service.markOwnedByService(arn, "rds");
assertEquals("rds", service.describeSecret("rds!db-1234", REGION).getOwningService());
assertTrue(service.rotateSecret("rds!db-1234", null, null,
new Secret.RotationRules(7, null, null), true, REGION).isRotationEnabled());
}
@Test
void markOwnedByServiceKeepsAnExistingOwnerAndToleratesAMissingSecret() {
String arn = service.createSecret("rds!db-1234", "value", null, null, null, null, "rds", REGION).getArn();
service.markOwnedByService(arn, "redshift");
assertEquals("rds", service.describeSecret("rds!db-1234", REGION).getOwningService());
// A backfill runs over whatever state it finds, so neither a secret that is gone nor a
// malformed ARN is an error.
assertDoesNotThrow(() -> service.markOwnedByService(
"arn:aws:secretsmanager:" + REGION + ":000000000000:secret:no-such-secret-AbCdEf", "rds"));
assertDoesNotThrow(() -> service.markOwnedByService("not-an-arn", "rds"));
}
@Test
void markOwnedByServiceAddressesTheAccountNamedInTheArn() {
// A backfill runs at startup, outside any request, so the store resolves the default
// account unless the ARN's account is used. Secrets of other accounts must still be found,
// and a same-named default-account secret must be left alone.
AccountAwareStorageBackend<Secret> accountAware =
AccountAwareStorageBackend.inMemory("000000000000");
SecretsManagerService svc = new SecretsManagerService(accountAware, 30);
Secret otherAccount = new Secret();
otherAccount.setName("rds!db-1234");
otherAccount.setArn("arn:aws:secretsmanager:" + REGION + ":111122223333:secret:rds!db-1234-AbCdEf");
accountAware.putForAccount("111122223333", REGION + "::rds!db-1234", otherAccount);
Secret sameNameHere = svc.createSecret("rds!db-1234", "value", null, null, null, null, REGION);
svc.markOwnedByService(otherAccount.getArn(), "rds");
assertEquals("rds",
accountAware.getForAccount("111122223333", REGION + "::rds!db-1234").orElseThrow().getOwningService());
assertNull(sameNameHere.getOwningService());
}
@Test
void ordinarySecretNamedLikeAnRdsSecretStillNeedsALambdaArn() {
// Ownership is a property of the secret, not of its name: anyone may create a secret
// called rds!something, and that must not grant it service-managed rotation.
service.createSecret("rds!db-impostor", "value", null, null, null, null, REGION);
AwsException e = assertThrows(AwsException.class, () ->
service.rotateSecret("rds!db-impostor", null, null,
new Secret.RotationRules(7, null, null), true, REGION));
assertEquals("InvalidRequestException", e.getErrorCode());
assertTrue(e.getMessage().contains("doesn't already have a Lambda function ARN configured"));
}
@Test
void tagAndUntagResource() {
service.createSecret("my-secret", "value", null, null, null,