mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): resolve dynamic references in RDS credentials (#1809)
* feat(cloudformation): resolve dynamic references in RDS credentials * test(cloudformation): pin secret resolution failures --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
This commit is contained in:
1 parent
82f80165fb
commit
d9e4447aeb
4 files changed
+1062
-5
No files matched your search
+272
@@ -0,0 +1,272 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
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 software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.cloudformation.model.StackStatus;
|
||||
import software.amazon.awssdk.services.rds.RdsClient;
|
||||
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesRequest;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.DeleteParameterRequest;
|
||||
import software.amazon.awssdk.services.ssm.model.ParameterType;
|
||||
import software.amazon.awssdk.services.ssm.model.PutParameterRequest;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
@DisplayName("CloudFormation RDS credential dynamic references")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CloudFormationRdsDynamicReferenceTest {
|
||||
|
||||
private static final String USERNAME = "viewer";
|
||||
private static final String PASSWORD = "compat-secret-123";
|
||||
private static final String DATABASE = "app";
|
||||
private static final List<String> STACK_NAMES = new ArrayList<>();
|
||||
|
||||
private static CloudFormationClient cloudFormation;
|
||||
private static RdsClient rds;
|
||||
private static SsmClient ssm;
|
||||
private static String secureParameterName;
|
||||
private static String plainParameterName;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
cloudFormation = TestFixtures.cloudFormationClient();
|
||||
rds = TestFixtures.rdsClient();
|
||||
ssm = TestFixtures.ssmClient();
|
||||
|
||||
String suffix = TestFixtures.uniqueName("cfn-rds-ref");
|
||||
secureParameterName = "/" + suffix + "/secure";
|
||||
plainParameterName = "/" + suffix + "/plain";
|
||||
|
||||
ssm.putParameter(PutParameterRequest.builder()
|
||||
.name(secureParameterName)
|
||||
.type(ParameterType.SECURE_STRING)
|
||||
.value(PASSWORD)
|
||||
.build());
|
||||
ssm.putParameter(PutParameterRequest.builder()
|
||||
.name(plainParameterName)
|
||||
.type(ParameterType.STRING)
|
||||
.value(PASSWORD)
|
||||
.build());
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (cloudFormation != null) {
|
||||
for (String stackName : STACK_NAMES) {
|
||||
try {
|
||||
cloudFormation.deleteStack(DeleteStackRequest.builder()
|
||||
.stackName(stackName)
|
||||
.build());
|
||||
} catch (Exception e) {
|
||||
System.err.printf("Unable to delete compatibility stack %s: %s%n",
|
||||
stackName, e.getMessage());
|
||||
}
|
||||
}
|
||||
cloudFormation.close();
|
||||
}
|
||||
if (ssm != null) {
|
||||
deleteParameter(secureParameterName);
|
||||
deleteParameter(plainParameterName);
|
||||
ssm.close();
|
||||
}
|
||||
if (rds != null) {
|
||||
rds.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
@DisplayName("ssm-secure resolves into an RDS master password")
|
||||
void resolvesSecureSsmMasterPassword() throws Exception {
|
||||
assumeTrue(!Boolean.parseBoolean(System.getenv()
|
||||
.getOrDefault("FLOCI_SERVICES_RDS_MOCK", "false")),
|
||||
"Container-backed RDS is required for the credential compatibility test");
|
||||
assumeTrue(TestFixtures.isLambdaDispatchAvailable(),
|
||||
"Docker dispatch is unavailable for the RDS container compatibility test");
|
||||
|
||||
String stackName = TestFixtures.uniqueName("cfn-rds-secure");
|
||||
String instanceId = TestFixtures.uniqueName("cfn-rds-secure");
|
||||
STACK_NAMES.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Database": {
|
||||
"Type": "AWS::RDS::DBInstance",
|
||||
"Properties": {
|
||||
"DBInstanceIdentifier": "%s",
|
||||
"DBInstanceClass": "db.t3.micro",
|
||||
"AllocatedStorage": 20,
|
||||
"Engine": "postgres",
|
||||
"DBName": "%s",
|
||||
"MasterUsername": "%s",
|
||||
"MasterUserPassword": "{{resolve:ssm-secure:%s}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(instanceId, DATABASE, USERNAME, secureParameterName);
|
||||
|
||||
cloudFormation.createStack(CreateStackRequest.builder()
|
||||
.stackName(stackName)
|
||||
.templateBody(template)
|
||||
.build());
|
||||
|
||||
assertThat(waitForTerminal(stackName, Duration.ofSeconds(90)))
|
||||
.isEqualTo(StackStatus.CREATE_COMPLETE);
|
||||
|
||||
int port = rds.describeDBInstances(DescribeDbInstancesRequest.builder()
|
||||
.dbInstanceIdentifier(instanceId)
|
||||
.build())
|
||||
.dbInstances()
|
||||
.get(0)
|
||||
.endpoint()
|
||||
.port();
|
||||
try (Connection connection = awaitPostgresConnection(port)) {
|
||||
assertThat(connection.isValid(5)).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
@DisplayName("ssm-secure is rejected for RDS MasterUsername")
|
||||
void rejectsSecureSsmMasterUsername() throws InterruptedException {
|
||||
String stackName = TestFixtures.uniqueName("cfn-rds-secure-user");
|
||||
String instanceId = TestFixtures.uniqueName("cfn-rds-secure-user");
|
||||
STACK_NAMES.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Database": {
|
||||
"Type": "AWS::RDS::DBInstance",
|
||||
"Properties": {
|
||||
"DBInstanceIdentifier": "%s",
|
||||
"DBInstanceClass": "db.t3.micro",
|
||||
"AllocatedStorage": 20,
|
||||
"Engine": "postgres",
|
||||
"MasterUsername": "{{resolve:ssm-secure:%s}}",
|
||||
"MasterUserPassword": "%s"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(instanceId, secureParameterName, PASSWORD);
|
||||
|
||||
cloudFormation.createStack(CreateStackRequest.builder()
|
||||
.stackName(stackName)
|
||||
.templateBody(template)
|
||||
.build());
|
||||
|
||||
assertThat(waitForTerminal(stackName, Duration.ofSeconds(30)))
|
||||
.isEqualTo(StackStatus.ROLLBACK_COMPLETE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
@DisplayName("ssm-secure requires a SecureString parameter")
|
||||
void rejectsPlaintextParameterForSecureReference() throws InterruptedException {
|
||||
String stackName = TestFixtures.uniqueName("cfn-rds-wrong-type");
|
||||
String instanceId = TestFixtures.uniqueName("cfn-rds-wrong-type");
|
||||
STACK_NAMES.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Database": {
|
||||
"Type": "AWS::RDS::DBInstance",
|
||||
"Properties": {
|
||||
"DBInstanceIdentifier": "%s",
|
||||
"DBInstanceClass": "db.t3.micro",
|
||||
"AllocatedStorage": 20,
|
||||
"Engine": "postgres",
|
||||
"MasterUsername": "%s",
|
||||
"MasterUserPassword": "{{resolve:ssm-secure:%s}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(instanceId, USERNAME, plainParameterName);
|
||||
|
||||
cloudFormation.createStack(CreateStackRequest.builder()
|
||||
.stackName(stackName)
|
||||
.templateBody(template)
|
||||
.build());
|
||||
|
||||
assertThat(waitForTerminal(stackName, Duration.ofSeconds(30)))
|
||||
.isEqualTo(StackStatus.ROLLBACK_COMPLETE);
|
||||
}
|
||||
|
||||
private static StackStatus waitForTerminal(String stackName, Duration timeout)
|
||||
throws InterruptedException {
|
||||
Instant deadline = Instant.now().plus(timeout);
|
||||
while (Instant.now().isBefore(deadline)) {
|
||||
List<Stack> stacks = cloudFormation.describeStacks(DescribeStacksRequest.builder()
|
||||
.stackName(stackName)
|
||||
.build())
|
||||
.stacks();
|
||||
if (!stacks.isEmpty() && !stacks.get(0).stackStatusAsString().endsWith("_IN_PROGRESS")) {
|
||||
return stacks.get(0).stackStatus();
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
throw new AssertionError("Stack " + stackName + " did not reach a terminal state within " + timeout);
|
||||
}
|
||||
|
||||
private static Connection awaitPostgresConnection(int port) throws Exception {
|
||||
Instant deadline = Instant.now().plus(Duration.ofSeconds(60));
|
||||
SQLException lastFailure = null;
|
||||
while (Instant.now().isBefore(deadline)) {
|
||||
try {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", USERNAME);
|
||||
properties.setProperty("password", PASSWORD);
|
||||
properties.setProperty("sslmode", "disable");
|
||||
properties.setProperty("connectTimeout", "5");
|
||||
return DriverManager.getConnection(
|
||||
"jdbc:postgresql://" + TestFixtures.proxyHost() + ":" + port + "/" + DATABASE,
|
||||
properties);
|
||||
} catch (SQLException e) {
|
||||
lastFailure = e;
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
}
|
||||
throw lastFailure != null
|
||||
? lastFailure
|
||||
: new SQLException("Timed out waiting for the RDS proxy");
|
||||
}
|
||||
|
||||
private static void deleteParameter(String parameterName) {
|
||||
if (parameterName == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ssm.deleteParameter(DeleteParameterRequest.builder()
|
||||
.name(parameterName)
|
||||
.build());
|
||||
} catch (Exception e) {
|
||||
System.err.printf("Unable to delete compatibility parameter %s: %s%n",
|
||||
parameterName, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,17 @@ data and attachment ownership.
|
||||
- Replacement-only changes such as `FunctionName` or `PackageType` changes create a replacement function and remove the old one.
|
||||
- S3-backed code stays linked through `S3Bucket` / `S3Key`, so Lambda's reactive S3 sync continues to work for functions created by CloudFormation or CDK.
|
||||
|
||||
## RDS Credential Dynamic References
|
||||
|
||||
`AWS::RDS::DBInstance` and `AWS::RDS::DBCluster` resolve CloudFormation dynamic
|
||||
references in `MasterUsername` and `MasterUserPassword` during resource creation:
|
||||
|
||||
- `secretsmanager` references support whole secret strings, JSON keys, version stages, and version IDs.
|
||||
- `ssm` references accept `String` and `StringList` parameters, using either the latest value or an explicit positive version.
|
||||
- `ssm-secure` references require a `SecureString` parameter and are supported only for `MasterUserPassword`, matching the AWS resource-property allowlist.
|
||||
|
||||
Dynamic-reference expansion is currently scoped to these RDS credential properties.
|
||||
|
||||
## Account-Aware Provisioning
|
||||
|
||||
Resources provisioned by `CreateStack` / `UpdateStack` land in the **caller's account** namespace
|
||||
|
||||
+197
-4
@@ -79,6 +79,8 @@ import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import io.github.hectorvent.floci.services.ssm.model.Parameter;
|
||||
import io.github.hectorvent.floci.services.ssm.model.ParameterHistory;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
|
||||
@@ -108,6 +110,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
@@ -1209,8 +1212,8 @@ public class CloudFormationResourceProvisioner {
|
||||
id,
|
||||
resolveOptional(props, "Engine", engine),
|
||||
resolveOptional(props, "EngineVersion", engine),
|
||||
resolveOptional(props, "MasterUsername", engine),
|
||||
resolveOptional(props, "MasterUserPassword", engine),
|
||||
resolveDynamicReferences(resolveOptional(props, "MasterUsername", engine), region, false),
|
||||
resolveDynamicReferences(resolveOptional(props, "MasterUserPassword", engine), region, true),
|
||||
resolveOptional(props, "DBName", engine),
|
||||
firstNonBlank(resolveOptional(props, "DBInstanceClass", engine), "db.t3.micro"),
|
||||
parseIntProp(props, "AllocatedStorage", engine, 20),
|
||||
@@ -1240,8 +1243,8 @@ public class CloudFormationResourceProvisioner {
|
||||
id,
|
||||
resolveOptional(props, "Engine", engine),
|
||||
resolveOptional(props, "EngineVersion", engine),
|
||||
resolveOptional(props, "MasterUsername", engine),
|
||||
resolveOptional(props, "MasterUserPassword", engine),
|
||||
resolveDynamicReferences(resolveOptional(props, "MasterUsername", engine), region, false),
|
||||
resolveDynamicReferences(resolveOptional(props, "MasterUserPassword", engine), region, true),
|
||||
resolveOptional(props, "DatabaseName", engine),
|
||||
parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine),
|
||||
resolveOptional(props, "DBClusterParameterGroupName", engine),
|
||||
@@ -5162,6 +5165,196 @@ public class CloudFormationResourceProvisioner {
|
||||
return engine.resolve(props.get(name));
|
||||
}
|
||||
|
||||
private static final Pattern DYNAMIC_REF = Pattern.compile("\\{\\{resolve:([a-z-]+):(.*?)\\}\\}");
|
||||
private static final Pattern SSM_DYNAMIC_REF_BODY =
|
||||
Pattern.compile("([a-zA-Z0-9_.\\-/]+)(?::([0-9]+))?");
|
||||
|
||||
/**
|
||||
* Resolves CloudFormation dynamic references embedded in a string. Supports
|
||||
* {@code {{resolve:secretsmanager:<secret-id-or-arn>:SecretString:<json-key>:<stage>:<version>}}}
|
||||
* and {@code {{resolve:ssm:<name>:<version>}}} / {@code {{resolve:ssm-secure:<name>:<version>}}},
|
||||
* which CloudFormation substitutes with the live value at deploy time (e.g. an RDS
|
||||
* MasterUserPassword sourced from a generated secret). Unsupported services are left verbatim.
|
||||
*/
|
||||
private String resolveDynamicReferences(String value, String region, boolean allowSsmSecure) {
|
||||
if (value == null || !value.contains("{{resolve:")) {
|
||||
return value;
|
||||
}
|
||||
Matcher m = DYNAMIC_REF.matcher(value);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int previousEnd = 0;
|
||||
while (m.find()) {
|
||||
rejectUnclosedDynamicReference(value.substring(previousEnd, m.start()));
|
||||
String replacement = resolveDynamicRef(m.group(1), m.group(2), region, allowSsmSecure);
|
||||
m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
|
||||
previousEnd = m.end();
|
||||
}
|
||||
rejectUnclosedDynamicReference(value.substring(previousEnd));
|
||||
m.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String resolveDynamicRef(String service, String body, String region, boolean allowSsmSecure) {
|
||||
if ("secretsmanager".equals(service)) {
|
||||
// body = <secret-id-or-arn>:SecretString:<json-key>:<version-stage>:<version-id>. The
|
||||
// secret id may be an ARN (which itself contains colons), so split on the ":SecretString"
|
||||
// marker rather than on ":". AWS also accepts <secret-id-or-arn>:::: as shorthand for
|
||||
// retrieving the whole current SecretString with the optional fields omitted.
|
||||
String secretId;
|
||||
String[] parts;
|
||||
if (body.endsWith("::::")) {
|
||||
secretId = body.substring(0, body.length() - 4);
|
||||
parts = new String[0];
|
||||
} else if (isValidSecretsManagerSecretId(body)) {
|
||||
secretId = body;
|
||||
parts = new String[0];
|
||||
} else {
|
||||
int marker = body.lastIndexOf(":SecretString");
|
||||
if (marker < 0) {
|
||||
throw invalidSecretsManagerDynamicReference();
|
||||
}
|
||||
secretId = body.substring(0, marker);
|
||||
String rest = body.substring(marker + ":SecretString".length());
|
||||
if (!rest.isEmpty() && !rest.startsWith(":")) {
|
||||
throw invalidSecretsManagerDynamicReference();
|
||||
}
|
||||
parts = rest.startsWith(":")
|
||||
? rest.substring(1).split(":", -1)
|
||||
: new String[0];
|
||||
}
|
||||
if (!isValidSecretsManagerSecretId(secretId) || parts.length > 3) {
|
||||
throw invalidSecretsManagerDynamicReference();
|
||||
}
|
||||
String jsonKey = parts.length > 0 ? parts[0] : "";
|
||||
String versionStage = parts.length > 1 && !parts[1].isBlank() ? parts[1] : null;
|
||||
String versionId = parts.length > 2 && !parts[2].isBlank() ? parts[2] : null;
|
||||
if (versionStage != null && versionId != null) {
|
||||
throw new AwsException("ValidationError",
|
||||
"version-stage and version-id cannot both be specified", 400);
|
||||
}
|
||||
String secretRegion = AwsArnUtils.regionOrDefault(secretId, region);
|
||||
String secretString = secretsManagerService
|
||||
.getSecretValue(secretId, versionId, versionStage, secretRegion).getSecretString();
|
||||
if (secretString == null) {
|
||||
// A binary-only secret has no SecretString to substitute, so resource creation fails.
|
||||
throw new IllegalStateException(
|
||||
"secret " + secretId + " has no SecretString value to resolve");
|
||||
}
|
||||
if (jsonKey.isBlank()) {
|
||||
return secretString;
|
||||
}
|
||||
JsonNode json;
|
||||
try {
|
||||
json = objectMapper.readTree(secretString);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("ValidationError",
|
||||
"secret " + secretId + " does not contain valid JSON", 400);
|
||||
}
|
||||
if (!json.has(jsonKey)) {
|
||||
// A missing key would otherwise resolve to "" — silently provisioning e.g. a blank
|
||||
// MasterUserPassword. Fail resource creation instead.
|
||||
throw new IllegalStateException(
|
||||
"JSON key '" + jsonKey + "' not found in secret " + secretId);
|
||||
}
|
||||
return json.get(jsonKey).asText();
|
||||
}
|
||||
if ("ssm".equals(service) || "ssm-secure".equals(service)) {
|
||||
if ("ssm-secure".equals(service) && !allowSsmSecure) {
|
||||
throw new AwsException("ValidationError",
|
||||
"ssm-secure dynamic references are supported only for MasterUserPassword "
|
||||
+ "on AWS::RDS::DBInstance and AWS::RDS::DBCluster", 400);
|
||||
}
|
||||
Matcher reference = SSM_DYNAMIC_REF_BODY.matcher(body);
|
||||
if (!reference.matches()) {
|
||||
throw invalidSsmDynamicReference();
|
||||
}
|
||||
String parameterName = reference.group(1);
|
||||
String version = reference.group(2);
|
||||
if (version != null) {
|
||||
long wantedVersion;
|
||||
try {
|
||||
wantedVersion = Long.parseLong(version);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SSM parameter version must be a positive integer: " + version, 400);
|
||||
}
|
||||
if (wantedVersion < 1) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SSM parameter version must be a positive integer: " + version, 400);
|
||||
}
|
||||
ParameterHistory parameter = ssmService.getParameterHistory(parameterName, region).stream()
|
||||
.filter(h -> h.getVersion() == wantedVersion)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException(
|
||||
"ParameterVersionNotFound",
|
||||
"Parameter version " + wantedVersion + " not found.", 400));
|
||||
return validatedSsmParameterValue(
|
||||
service, parameterName, parameter.getType(), parameter.getValue());
|
||||
}
|
||||
Parameter parameter = ssmService.getParameter(parameterName, region);
|
||||
return validatedSsmParameterValue(
|
||||
service, parameterName, parameter.getType(), parameter.getValue());
|
||||
}
|
||||
// Other dynamic-reference services are not resolved here; leave verbatim.
|
||||
return "{{resolve:" + service + ":" + body + "}}";
|
||||
}
|
||||
|
||||
private static boolean isValidSecretsManagerSecretId(String secretId) {
|
||||
if (secretId == null || secretId.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
if (!secretId.contains(":")) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(secretId);
|
||||
String resource = arn.resource();
|
||||
return "secretsmanager".equals(arn.service())
|
||||
&& !arn.region().isBlank()
|
||||
&& !arn.accountId().isBlank()
|
||||
&& resource.startsWith("secret:")
|
||||
&& resource.length() > "secret:".length()
|
||||
&& !resource.substring("secret:".length()).contains(":");
|
||||
} catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalidSecretsManagerDynamicReference() {
|
||||
return new AwsException("ValidationError",
|
||||
"Invalid Secrets Manager dynamic reference", 400);
|
||||
}
|
||||
|
||||
private static void rejectUnclosedDynamicReference(String value) {
|
||||
if (value.contains("{{resolve:secretsmanager:")) {
|
||||
throw invalidSecretsManagerDynamicReference();
|
||||
}
|
||||
if (value.contains("{{resolve:ssm:") || value.contains("{{resolve:ssm-secure:")) {
|
||||
throw invalidSsmDynamicReference();
|
||||
}
|
||||
}
|
||||
|
||||
private static String validatedSsmParameterValue(
|
||||
String service, String parameterName, String parameterType, String value) {
|
||||
boolean validType = "ssm-secure".equals(service)
|
||||
? "SecureString".equals(parameterType)
|
||||
: "String".equals(parameterType) || "StringList".equals(parameterType);
|
||||
if (!validType) {
|
||||
String expectedType = "ssm-secure".equals(service)
|
||||
? "SecureString"
|
||||
: "String or StringList";
|
||||
throw new AwsException("ValidationError",
|
||||
"SSM parameter " + parameterName + " must be type " + expectedType
|
||||
+ " for an " + service + " dynamic reference", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static AwsException invalidSsmDynamicReference() {
|
||||
return new AwsException("ValidationError",
|
||||
"Invalid SSM dynamic reference", 400);
|
||||
}
|
||||
|
||||
private String resolveOrDefault(JsonNode props, String name,
|
||||
CloudFormationTemplateEngine engine, String defaultValue) {
|
||||
String value = resolveOptional(props, name, engine);
|
||||
|
||||
+582
-1
@@ -9,22 +9,34 @@ import io.github.hectorvent.floci.services.rds.model.DbEndpoint;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbInstance;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import io.github.hectorvent.floci.services.ssm.model.Parameter;
|
||||
import io.github.hectorvent.floci.services.ssm.model.ParameterHistory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.nullable;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -36,13 +48,17 @@ class RdsCfnProvisionerTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private RdsService rdsService;
|
||||
private SecretsManagerService secretsManagerService;
|
||||
private SsmService ssmService;
|
||||
private CloudFormationResourceProvisioner provisioner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rdsService = mock(RdsService.class);
|
||||
secretsManagerService = mock(SecretsManagerService.class);
|
||||
ssmService = mock(SsmService.class);
|
||||
provisioner = new CloudFormationResourceProvisioner(
|
||||
null, null, null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, ssmService, null, secretsManagerService, null,
|
||||
null, null, null, null, null, null,
|
||||
mapper,
|
||||
null, null, null, null, null, null, null,
|
||||
@@ -159,6 +175,571 @@ class RdsCfnProvisionerTest {
|
||||
null, null, null, false, null, null, null, false, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesSecretsManagerDynamicReferencesInDbClusterCredentials() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn(
|
||||
"{\"username\":\"resolved-user\",\"password\":\"resolved-secret\"}");
|
||||
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(cluster.getEndpoint()).thenReturn(new DbEndpoint("mycluster.local", 5432));
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql","EngineVersion":"16.3",
|
||||
"MasterUsername":"{{resolve:secretsmanager:my-secret:SecretString:username}}",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret:SecretString:password}}",
|
||||
"DatabaseName":"appdb"}
|
||||
""", "us-west-2");
|
||||
|
||||
verify(rdsService).createDbCluster(eq("mycluster"), eq("aurora-postgresql"), eq("16.3"),
|
||||
eq("resolved-user"), eq("resolved-secret"), eq("appdb"), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any());
|
||||
verify(secretsManagerService, times(2))
|
||||
.getSecretValue("my-secret", null, null, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesSecretsManagerDynamicReferencesInDbInstanceCredentials() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn(
|
||||
"{\"username\":\"resolved-user\",\"password\":\"resolved-secret\"}");
|
||||
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
|
||||
|
||||
DbInstance instance = mock(DbInstance.class);
|
||||
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
|
||||
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
|
||||
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
|
||||
any(), anyMap(), nullable(String.class))).thenReturn(instance);
|
||||
|
||||
provision("Db", "AWS::RDS::DBInstance", """
|
||||
{"DBInstanceIdentifier":"mydb","Engine":"postgres",
|
||||
"MasterUsername":"{{resolve:secretsmanager:my-secret:SecretString:username}}",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret:SecretString:password}}"}
|
||||
""", "us-west-2");
|
||||
|
||||
verify(rdsService).createDbInstance(
|
||||
eq("mydb"), eq("postgres"), any(), eq("resolved-user"), eq("resolved-secret"),
|
||||
any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(),
|
||||
anyBoolean(), anyBoolean(), any(), anyMap(), eq("us-west-2"));
|
||||
verify(secretsManagerService, times(2))
|
||||
.getSecretValue("my-secret", null, null, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesSecretsManagerWholeSecretShorthand() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn("resolved-secret");
|
||||
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret::::}}"}
|
||||
""");
|
||||
|
||||
verify(rdsService).createDbCluster(
|
||||
eq("mycluster"), eq("aurora-postgresql"), any(), eq("admin"),
|
||||
eq("resolved-secret"), any(), anyBoolean(), any(), any(), any(),
|
||||
anyBoolean(), eq("us-east-1"));
|
||||
verify(secretsManagerService)
|
||||
.getSecretValue("my-secret", null, null, "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesSecretsManagerArnWholeSecretShorthandInArnRegion() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn("resolved-secret");
|
||||
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
String secretArn =
|
||||
"arn:aws:secretsmanager:us-west-2:000000000000:secret:MySecret";
|
||||
provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:%s::::}}"}
|
||||
""".formatted(secretArn));
|
||||
|
||||
verify(rdsService).createDbCluster(
|
||||
eq("mycluster"), eq("aurora-postgresql"), any(), eq("admin"),
|
||||
eq("resolved-secret"), any(), anyBoolean(), any(), any(), any(),
|
||||
anyBoolean(), eq("us-east-1"));
|
||||
verify(secretsManagerService)
|
||||
.getSecretValue(secretArn, null, null, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesWholeSecretArnWhoseNameIsSecretString() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn("resolved-secret");
|
||||
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
String secretArn =
|
||||
"arn:aws:secretsmanager:us-west-2:000000000000:secret:SecretString";
|
||||
provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:%s}}"}
|
||||
""".formatted(secretArn));
|
||||
|
||||
verify(rdsService).createDbCluster(
|
||||
eq("mycluster"), eq("aurora-postgresql"), any(), eq("admin"),
|
||||
eq("resolved-secret"), any(), anyBoolean(), any(), any(), any(),
|
||||
anyBoolean(), eq("us-east-1"));
|
||||
verify(secretsManagerService)
|
||||
.getSecretValue(secretArn, null, null, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesJsonKeyFromArnWhoseNameStartsWithSecretString() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn("{\"password\":\"resolved-secret\"}");
|
||||
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
String secretArn =
|
||||
"arn:aws:secretsmanager:us-west-2:000000000000:secret:SecretStringName";
|
||||
provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:%s:SecretString:password}}"}
|
||||
""".formatted(secretArn));
|
||||
|
||||
verify(rdsService).createDbCluster(
|
||||
eq("mycluster"), eq("aurora-postgresql"), any(), eq("admin"),
|
||||
eq("resolved-secret"), any(), anyBoolean(), any(), any(), any(),
|
||||
anyBoolean(), eq("us-east-1"));
|
||||
verify(secretsManagerService)
|
||||
.getSecretValue(secretArn, null, null, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void binaryOnlySecretFailsBeforeRdsProvisioning() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn(null);
|
||||
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"secret my-secret has no SecretString value to resolve"));
|
||||
verifyNoInteractions(rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingSecretJsonKeyFailsBeforeRdsProvisioning() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn("{\"username\":\"admin\"}");
|
||||
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret:SecretString:password}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"JSON key 'password' not found in secret my-secret"));
|
||||
verifyNoInteractions(rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extraSecretsManagerSuffixFailsWithoutReadingSecretOrCreatingDatabase() {
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret:SecretString:password:::extra}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"Invalid Secrets Manager dynamic reference"));
|
||||
verifyNoInteractions(secretsManagerService, rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedSecretsManagerSecretStringTypeFailsBeforeSecretLookup() {
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret:SecretBinary:password}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"Invalid Secrets Manager dynamic reference"));
|
||||
verifyNoInteractions(secretsManagerService, rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesSsmDynamicReferenceInMasterPassword() {
|
||||
Parameter param = mock(Parameter.class);
|
||||
when(param.getValue()).thenReturn("resolved-ssm");
|
||||
when(param.getType()).thenReturn("String");
|
||||
when(ssmService.getParameter(eq("/db/password"), any())).thenReturn(param);
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(cluster.getEndpoint()).thenReturn(new DbEndpoint("mycluster.local", 5432));
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql","EngineVersion":"16.3",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password}}",
|
||||
"DatabaseName":"appdb"}
|
||||
""");
|
||||
|
||||
// The {{resolve:ssm:<name>}} dynamic reference is substituted with the parameter value.
|
||||
verify(rdsService).createDbCluster(eq("mycluster"), eq("aurora-postgresql"), eq("16.3"),
|
||||
eq("admin"), eq("resolved-ssm"), eq("appdb"), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesPlaintextSsmDynamicReferenceInMasterUsername() {
|
||||
Parameter param = new Parameter("/db/username", "resolved-user", "String");
|
||||
when(ssmService.getParameter("/db/username", "us-east-1")).thenReturn(param);
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"{{resolve:ssm:/db/username}}",
|
||||
"MasterUserPassword":"secret"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
verify(rdsService).createDbCluster(eq("mycluster"), eq("aurora-postgresql"), any(),
|
||||
eq("resolved-user"), eq("secret"), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesStringListSsmDynamicReference() {
|
||||
Parameter param = new Parameter("/db/password-list", "first,second", "StringList");
|
||||
when(ssmService.getParameter("/db/password-list", "us-east-1")).thenReturn(param);
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password-list}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
verify(rdsService).createDbCluster(eq("mycluster"), eq("aurora-postgresql"), any(),
|
||||
eq("admin"), eq("first,second"), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesSecureSsmDynamicReferenceInMasterPassword() {
|
||||
Parameter param = new Parameter("/db/password", "resolved-secure", "SecureString");
|
||||
when(ssmService.getParameter("/db/password", "us-east-1")).thenReturn(param);
|
||||
|
||||
DbInstance instance = mock(DbInstance.class);
|
||||
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
|
||||
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
|
||||
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
|
||||
any(), anyMap(), nullable(String.class))).thenReturn(instance);
|
||||
|
||||
StackResource resource = provision("Db", "AWS::RDS::DBInstance", """
|
||||
{"DBInstanceIdentifier":"mydb","Engine":"postgres",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm-secure:/db/password}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
verify(rdsService).createDbInstance(
|
||||
eq("mydb"), eq("postgres"), any(), eq("admin"), eq("resolved-secure"),
|
||||
any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(),
|
||||
anyBoolean(), anyBoolean(), any(), anyMap(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"AWS::RDS::DBInstance", "AWS::RDS::DBCluster"})
|
||||
void rejectsSecureSsmDynamicReferenceInMasterUsername(String resourceType) {
|
||||
StackResource resource = provision("Database", resourceType, """
|
||||
{"Engine":"postgres",
|
||||
"MasterUsername":"{{resolve:ssm-secure:/db/username}}",
|
||||
"MasterUserPassword":"secret"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"ssm-secure dynamic references are supported only for MasterUserPassword"));
|
||||
verifyNoInteractions(ssmService, rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSecureStringParameterForPlaintextSsmDynamicReference() {
|
||||
Parameter param = new Parameter("/db/password", "resolved-secure", "SecureString");
|
||||
when(ssmService.getParameter("/db/password", "us-east-1")).thenReturn(param);
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"must be type String or StringList for an ssm dynamic reference"));
|
||||
verifyNoInteractions(rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsPlaintextParameterForSecureSsmDynamicReference() {
|
||||
Parameter param = new Parameter("/db/password", "resolved-plain", "String");
|
||||
when(ssmService.getParameter("/db/password", "us-east-1")).thenReturn(param);
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm-secure:/db/password}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"must be type SecureString for an ssm-secure dynamic reference"));
|
||||
verifyNoInteractions(rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesPinnedSsmVersionInStackRegion() {
|
||||
ParameterHistory versionOne = new ParameterHistory();
|
||||
versionOne.setVersion(1);
|
||||
versionOne.setValue("first-password");
|
||||
versionOne.setType("String");
|
||||
ParameterHistory versionTwo = new ParameterHistory();
|
||||
versionTwo.setVersion(2);
|
||||
versionTwo.setValue("latest-password");
|
||||
versionTwo.setType("String");
|
||||
when(ssmService.getParameterHistory("/db/password", "us-west-2"))
|
||||
.thenReturn(List.of(versionOne, versionTwo));
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password:1}}"}
|
||||
""", "us-west-2");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
verify(rdsService).createDbCluster(eq("mycluster"), eq("aurora-postgresql"), any(),
|
||||
eq("admin"), eq("first-password"), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), eq("us-west-2"));
|
||||
verify(ssmService, never()).getParameter(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesPinnedSecureSsmVersionInStackRegion() {
|
||||
ParameterHistory versionOne = new ParameterHistory();
|
||||
versionOne.setVersion(1);
|
||||
versionOne.setValue("first-password");
|
||||
versionOne.setType("SecureString");
|
||||
when(ssmService.getParameterHistory("/db/password", "us-west-2"))
|
||||
.thenReturn(List.of(versionOne));
|
||||
|
||||
DbCluster cluster = mock(DbCluster.class);
|
||||
when(cluster.getDbClusterIdentifier()).thenReturn("mycluster");
|
||||
when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(cluster);
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm-secure:/db/password:1}}"}
|
||||
""", "us-west-2");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
verify(rdsService).createDbCluster(eq("mycluster"), eq("aurora-postgresql"), any(),
|
||||
eq("admin"), eq("first-password"), any(), anyBoolean(), any(),
|
||||
any(), any(), anyBoolean(), eq("us-west-2"));
|
||||
verify(ssmService, never()).getParameter(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMismatchedPinnedSsmParameterType() {
|
||||
ParameterHistory versionOne = new ParameterHistory();
|
||||
versionOne.setVersion(1);
|
||||
versionOne.setValue("first-password");
|
||||
versionOne.setType("SecureString");
|
||||
when(ssmService.getParameterHistory("/db/password", "us-east-1"))
|
||||
.thenReturn(List.of(versionOne));
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password:1}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"must be type String or StringList for an ssm dynamic reference"));
|
||||
verifyNoInteractions(rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingPinnedSsmVersionFailsResourceWithoutUsingLatestValue() {
|
||||
ParameterHistory versionOne = new ParameterHistory();
|
||||
versionOne.setVersion(1);
|
||||
versionOne.setValue("first-password");
|
||||
versionOne.setType("String");
|
||||
when(ssmService.getParameterHistory("/db/password", "us-east-1"))
|
||||
.thenReturn(List.of(versionOne));
|
||||
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password:99}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains("Parameter version 99 not found"));
|
||||
verify(ssmService, never()).getParameter(any(), any());
|
||||
verifyNoInteractions(rdsService);
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "malformed SSM version suffix [{0}]")
|
||||
@ValueSource(strings = {
|
||||
"", "+1", " ", " 1", "1 ", "-1", "not-a-version", "1:2"
|
||||
})
|
||||
void malformedPinnedSsmVersionFailsWithValidationError(String version) {
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password:%s}}"}
|
||||
""".formatted(version));
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"Invalid SSM dynamic reference"));
|
||||
verifyNoInteractions(ssmService, rdsService);
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "invalid numeric SSM version suffix [{0}]")
|
||||
@ValueSource(strings = {"0", "9223372036854775808"})
|
||||
void invalidNumericPinnedSsmVersionFailsWithValidationError(String version) {
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password:%s}}"}
|
||||
""".formatted(version));
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"SSM parameter version must be a positive integer"));
|
||||
verifyNoInteractions(ssmService, rdsService);
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "invalid SSM parameter name [{0}]")
|
||||
@ValueSource(strings = {"", "invalid name", "/db/password+extra", "/db/password?extra", "/db/password:label"})
|
||||
void invalidSsmParameterNameFailsBeforeParameterLookup(String parameterName) {
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:%s}}"}
|
||||
""".formatted(parameterName));
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"Invalid SSM dynamic reference"));
|
||||
verifyNoInteractions(ssmService, rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unclosedSsmDynamicReferenceFailsBeforeParameterLookup() {
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:ssm:/db/password"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"Invalid SSM dynamic reference"));
|
||||
verifyNoInteractions(ssmService, rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unclosedSecretsManagerDynamicReferenceFailsBeforeSecretLookup() {
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains(
|
||||
"Invalid Secrets Manager dynamic reference"));
|
||||
verifyNoInteractions(secretsManagerService, rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsManagerStageAndVersionIdTogetherFailResource() {
|
||||
StackResource resource = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
|
||||
"MasterUsername":"admin",
|
||||
"MasterUserPassword":"{{resolve:secretsmanager:my-secret:SecretString:password:AWSCURRENT:version-id}}"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertTrue(resource.getStatusReason().contains("cannot both be specified"));
|
||||
verifyNoInteractions(secretsManagerService, rdsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionsDbSubnetGroupWithResolvedSubnetIds() {
|
||||
DbSubnetGroup group = mock(DbSubnetGroup.class);
|
||||
|
||||
Reference in new issue
Block a user