feat: support GenerateSecretString and Description for AWS::SecretsManager::Secret in CloudFormation (#176)

* feat: support GenerateSecretString and Description for AWS::SecretsManager::Secret in CloudFormation
* fix: reject both SecretString and GenerateSecretString per AWS spec
This commit is contained in:
yoyo authored and GitHub committed 2026-04-03 09:03:38 -05:00
1 parent ebc06616e7
commit f994b9545b
5 files changed
+807 -96

No files matched your search

@@ -14,6 +14,7 @@ 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.core.common.AwsException;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -472,16 +473,79 @@ public class CloudFormationResourceProvisioner {
if (name == null || name.isBlank()) {
name = generatePhysicalName(stackName, r.getLogicalId(), 512, false);
}
String value = resolveOptional(props, "SecretString", engine);
if (value == null) {
value = "{}";
}
var secret = secretsManagerService.createSecret(name, value, null, null, null, List.of(), region);
String description = resolveOptional(props, "Description", engine);
String value = resolveSecretValue(props, engine);
var secret = secretsManagerService.createSecret(name, value, null, description, null, List.of(), region);
r.setPhysicalId(secret.getArn());
r.getAttributes().put("Arn", secret.getArn());
r.getAttributes().put("Name", name);
}
/**
* Resolves the secret value from CloudFormation properties.
* SecretString and GenerateSecretString are mutually exclusive per AWS spec.
* If GenerateSecretString is present, a random password is generated.
* If SecretStringTemplate and GenerateStringKey are specified inside
* GenerateSecretString, the generated password is embedded in the template JSON.
*/
private String resolveSecretValue(JsonNode props, CloudFormationTemplateEngine engine) {
if (props == null) {
return "{}";
}
// SecretString takes precedence when explicitly set
String secretString = resolveOptional(props, "SecretString", engine);
JsonNode genNode = props.get("GenerateSecretString");
if (secretString != null && genNode != null && !genNode.isNull()) {
throw new AwsException("ValidationError",
"You can't specify both SecretString and GenerateSecretString", 400);
}
if (secretString != null) {
return secretString;
}
if (genNode != null && !genNode.isNull()) {
return generateSecretString(genNode);
}
return "{}";
}
private String generateSecretString(JsonNode genNode) {
String password = io.github.hectorvent.floci.services.secretsmanager
.RandomPasswordGenerator.generate(genNode);
String template = null;
String key = null;
JsonNode templateNode = genNode.get("SecretStringTemplate");
JsonNode keyNode = genNode.get("GenerateStringKey");
if (templateNode != null && !templateNode.isNull()) {
template = templateNode.asText();
}
if (keyNode != null && !keyNode.isNull()) {
key = keyNode.asText();
}
if (template != null && key != null) {
// Insert the generated password into the template JSON
try {
var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
var tree = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(template);
tree.put(key, password);
return mapper.writeValueAsString(tree);
} catch (Exception e) {
// If the template is not valid JSON, fall back to raw password
LOG.warnv("Failed to parse SecretStringTemplate: {0}", e.getMessage());
return password;
}
}
return password;
}
// ── Nested Stack ──────────────────────────────────────────────────────────
private void provisionNestedStack(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.secretsmanager;
import com.fasterxml.jackson.databind.JsonNode;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Generates random passwords following the same rules as the AWS Secrets Manager
* {@code GetRandomPassword} API. Reused by both the JSON handler and CloudFormation
* {@code GenerateSecretString} provisioning.
*
* @see <a href="https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetRandomPassword.html">
* AWS Secrets Manager – GetRandomPassword</a>
*/
public final class RandomPasswordGenerator {
private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String DIGITS = "0123456789";
private static final String PUNCTUATION = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
private RandomPasswordGenerator() {
}
/**
* Generate a random password from a JSON node that may contain:
* {@code PasswordLength}, {@code ExcludeCharacters}, {@code ExcludeLowercase},
* {@code ExcludeUppercase}, {@code ExcludeNumbers}, {@code ExcludePunctuation},
* {@code IncludeSpace}, {@code RequireEachIncludedType}.
*
* @param node JSON object with optional password-generation fields
* @return the generated password
* @throws IllegalArgumentException if PasswordLength is out of range or the charset is empty
*/
public static String generate(JsonNode node) {
boolean excludeLower = boolField(node, "ExcludeLowercase");
boolean excludeUpper = boolField(node, "ExcludeUppercase");
boolean excludeNumbers = boolField(node, "ExcludeNumbers");
boolean excludePunctuation = boolField(node, "ExcludePunctuation");
boolean includeSpace = boolField(node, "IncludeSpace");
String excludeChars = stringField(node, "ExcludeCharacters");
JsonNode passwordLengthNode = node == null ? null : node.get("PasswordLength");
int length = (passwordLengthNode != null && !passwordLengthNode.isNull())
? passwordLengthNode.asInt(32) : 32;
if (length < 1 || length > 4096) {
throw new IllegalArgumentException("PasswordLength must be between 1 and 4096.");
}
JsonNode reqNode = node == null ? null : node.get("RequireEachIncludedType");
boolean requireEach = reqNode == null || reqNode.isNull() || reqNode.asBoolean();
// Build charset
StringBuilder charset = new StringBuilder();
if (!excludeLower) charset.append(LOWERCASE);
if (!excludeUpper) charset.append(UPPERCASE);
if (!excludeNumbers) charset.append(DIGITS);
if (!excludePunctuation) charset.append(PUNCTUATION);
if (includeSpace) charset.append(" ");
if (excludeChars != null) {
for (int i = charset.length() - 1; i >= 0; i--) {
if (excludeChars.indexOf(charset.charAt(i)) >= 0) {
charset.deleteCharAt(i);
}
}
}
if (charset.isEmpty()) {
throw new IllegalArgumentException("The password charset is empty after applying exclusions.");
}
SecureRandom random = new SecureRandom();
StringBuilder password = new StringBuilder(length);
if (requireEach) {
List<String> types = new ArrayList<>();
if (!excludeLower) types.add(LOWERCASE);
if (!excludeUpper) types.add(UPPERCASE);
if (!excludeNumbers) types.add(DIGITS);
if (!excludePunctuation) types.add(PUNCTUATION);
if (includeSpace) types.add(" ");
if (excludeChars != null) {
types = types.stream()
.map(t -> t.chars()
.filter(c -> excludeChars.indexOf(c) < 0)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString())
.filter(t -> !t.isEmpty())
.collect(Collectors.toList());
}
for (String type : types) {
password.append(type.charAt(random.nextInt(type.length())));
}
}
for (int i = password.length(); i < length; i++) {
password.append(charset.charAt(random.nextInt(charset.length())));
}
// Shuffle so required seed chars aren't always at the start
for (int i = length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
char tmp = password.charAt(i);
password.setCharAt(i, password.charAt(j));
password.setCharAt(j, tmp);
}
return password.toString();
}
private static boolean boolField(JsonNode node, String name) {
if (node == null) return false;
JsonNode f = node.get(name);
return f != null && !f.isNull() && f.asBoolean();
}
private static String stringField(JsonNode node, String name) {
if (node == null) return null;
JsonNode f = node.get(name);
return (f != null && !f.isNull()) ? f.asText() : null;
}
}
@@ -325,98 +325,16 @@ public class SecretsManagerJsonHandler {
* @see <a href="https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetRandomPassword.html">AWS Secrets Manager – GetRandomPassword</a>
*/
private Response handleGetRandomPassword(JsonNode request, String region) {
var excludeCharacters = request.get("ExcludeCharacters");
var excludeLowerCase = request.get("ExcludeLowercase");
var excludeNumbers = request.get("ExcludeNumbers");
var excludePunctuation = request.get("ExcludePunctuation");
var excludeUpperCase = request.get("ExcludeUppercase");
var includeSpace = request.get("IncludeSpace");
var passwordLength = request.get("PasswordLength");
var requireEachIncludedType = request.get("RequireEachIncludedType");
int length = (passwordLength != null && !passwordLength.isNull()) ? passwordLength.asInt(32) : 32;
if (length < 1 || length > 4096) {
try {
String password = RandomPasswordGenerator.generate(request);
ObjectNode response = objectMapper.createObjectNode();
response.put("RandomPassword", password);
return Response.ok(response).build();
} catch (IllegalArgumentException e) {
return Response.status(400)
.entity(new AwsErrorResponse("InvalidParameterException", "PasswordLength must be between 1 and 4096."))
.entity(new AwsErrorResponse("InvalidParameterException", e.getMessage()))
.build();
}
StringBuilder charset = new StringBuilder();
if (excludeLowerCase == null || excludeLowerCase.isNull() || !excludeLowerCase.asBoolean()) {
charset.append("abcdefghijklmnopqrstuvwxyz");
}
if (excludeUpperCase == null || excludeUpperCase.isNull() || !excludeUpperCase.asBoolean()) {
charset.append("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
if (excludeNumbers == null || excludeNumbers.isNull() || !excludeNumbers.asBoolean()) {
charset.append("0123456789");
}
if (excludePunctuation == null || excludePunctuation.isNull() || !excludePunctuation.asBoolean()) {
charset.append("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
}
if (includeSpace != null && !includeSpace.isNull() && includeSpace.asBoolean()) {
charset.append(" ");
}
if (excludeCharacters != null && !excludeCharacters.isNull()) {
String excluded = excludeCharacters.asText();
for (int i = charset.length() - 1; i >= 0; i--) {
if (excluded.indexOf(charset.charAt(i)) >= 0) {
charset.deleteCharAt(i);
}
}
}
SecureRandom random = new SecureRandom();
StringBuilder password = new StringBuilder(length);
boolean requireEach = requireEachIncludedType == null || requireEachIncludedType.isNull() || requireEachIncludedType.asBoolean();
if (requireEach) {
List<String> includedTypes = new ArrayList<>();
if (excludeLowerCase == null || excludeLowerCase.isNull() || !excludeLowerCase.asBoolean()) {
includedTypes.add("abcdefghijklmnopqrstuvwxyz");
}
if (excludeUpperCase == null || excludeUpperCase.isNull() || !excludeUpperCase.asBoolean()) {
includedTypes.add("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
if (excludeNumbers == null || excludeNumbers.isNull() || !excludeNumbers.asBoolean()) {
includedTypes.add("0123456789");
}
if (excludePunctuation == null || excludePunctuation.isNull() || !excludePunctuation.asBoolean()) {
includedTypes.add("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
}
if (includeSpace != null && !includeSpace.isNull() && includeSpace.asBoolean()) {
includedTypes.add(" ");
}
if (excludeCharacters != null && !excludeCharacters.isNull()) {
String excluded = excludeCharacters.asText();
includedTypes = includedTypes.stream()
.map(t -> t.chars().filter(c -> excluded.indexOf(c) < 0)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString())
.filter(t -> !t.isEmpty())
.collect(java.util.stream.Collectors.toList());
}
// Seed one char from each required type
for (String type : includedTypes) {
password.append(type.charAt(random.nextInt(type.length())));
}
}
for (int i = password.length(); i < length; i++) {
password.append(charset.charAt(random.nextInt(charset.length())));
}
// Shuffle so required chars aren't always at the start
for (int i = length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
char tmp = password.charAt(i);
password.setCharAt(i, password.charAt(j));
password.setCharAt(j, tmp);
}
ObjectNode response = objectMapper.createObjectNode();
response.put("RandomPassword", password.toString());
return Response.ok(response).build();
}
private List<Secret.Tag> parseTags(JsonNode request) {