mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 10:17:48 -05:00
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:
5 files changed
+807
-96
No files matched your search
+69
-5
@@ -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,
|
||||
|
||||
+127
@@ -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;
|
||||
}
|
||||
}
|
||||
+7
-89
@@ -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) {
|
||||
|
||||
+430
-2
@@ -7,17 +7,22 @@ import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.matchesRegex;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
@QuarkusTest
|
||||
@@ -25,13 +30,16 @@ class CloudFormationIntegrationTest {
|
||||
|
||||
private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssured.config = RestAssured.config().encoderConfig(
|
||||
EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs(DYNAMODB_CONTENT_TYPE, ContentType.TEXT)
|
||||
.encodeContentTypeAs(SSM_CONTENT_TYPE, ContentType.TEXT));
|
||||
.encodeContentTypeAs(SSM_CONTENT_TYPE, ContentType.TEXT)
|
||||
.encodeContentTypeAs(SM_CONTENT_TYPE, ContentType.TEXT));
|
||||
}
|
||||
|
||||
private static byte[] buildHandlerZip() {
|
||||
@@ -1018,4 +1026,424 @@ class CloudFormationIntegrationTest {
|
||||
.body(containsString("ecr-upper-stack-myrepo-"))
|
||||
.body(not(containsString("ECR-Upper-Stack-MyRepo-")));
|
||||
}
|
||||
|
||||
// ── Secrets Manager: GenerateSecretString + Description ──────────────────
|
||||
|
||||
@Test
|
||||
void createStack_secretWithGenerateSecretString_defaultPassword() {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MySecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"Name": "cfn-gen-default",
|
||||
"GenerateSecretString": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "gen-secret-default")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
// Verify secret was created and has a generated value (default 32 chars)
|
||||
String body = given()
|
||||
.header("X-Amz-Target", "secretsmanager.GetSecretValue")
|
||||
.contentType(SM_CONTENT_TYPE)
|
||||
.body("{\"SecretId\": \"cfn-gen-default\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
|
||||
try {
|
||||
JsonNode json = OBJECT_MAPPER.readTree(body);
|
||||
String secretString = json.get("SecretString").asText();
|
||||
assertThat(secretString, notNullValue());
|
||||
assertThat(secretString.length(), equalTo(32));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_secretWithGenerateSecretString_customLength() {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MySecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"Name": "cfn-gen-len64",
|
||||
"GenerateSecretString": {
|
||||
"PasswordLength": 64,
|
||||
"ExcludePunctuation": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "gen-secret-len64")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String body = given()
|
||||
.header("X-Amz-Target", "secretsmanager.GetSecretValue")
|
||||
.contentType(SM_CONTENT_TYPE)
|
||||
.body("{\"SecretId\": \"cfn-gen-len64\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
|
||||
try {
|
||||
JsonNode json = OBJECT_MAPPER.readTree(body);
|
||||
String secretString = json.get("SecretString").asText();
|
||||
assertThat(secretString.length(), equalTo(64));
|
||||
// No punctuation
|
||||
assertThat(secretString, not(matchesRegex(".*[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~].*")));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_secretWithGenerateSecretString_templateAndKey() {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MySecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"Name": "cfn-gen-template",
|
||||
"GenerateSecretString": {
|
||||
"SecretStringTemplate": "{\\"username\\": \\"admin\\"}",
|
||||
"GenerateStringKey": "password",
|
||||
"PasswordLength": 20,
|
||||
"ExcludePunctuation": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "gen-secret-tpl")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String body = given()
|
||||
.header("X-Amz-Target", "secretsmanager.GetSecretValue")
|
||||
.contentType(SM_CONTENT_TYPE)
|
||||
.body("{\"SecretId\": \"cfn-gen-template\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
|
||||
try {
|
||||
JsonNode json = OBJECT_MAPPER.readTree(body);
|
||||
String secretString = json.get("SecretString").asText();
|
||||
assertThat(secretString, notNullValue());
|
||||
// Parse the secret value as JSON
|
||||
JsonNode secretJson = OBJECT_MAPPER.readTree(secretString);
|
||||
assertThat(secretJson.get("username").asText(), equalTo("admin"));
|
||||
assertThat(secretJson.has("password"), equalTo(true));
|
||||
assertThat(secretJson.get("password").asText().length(), equalTo(20));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_secretWithDescription() {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MySecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"Name": "cfn-desc-secret",
|
||||
"Description": "My test secret description",
|
||||
"SecretString": "my-value"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "desc-secret-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Verify description via DescribeSecret
|
||||
given()
|
||||
.header("X-Amz-Target", "secretsmanager.DescribeSecret")
|
||||
.contentType(SM_CONTENT_TYPE)
|
||||
.body("{\"SecretId\": \"cfn-desc-secret\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Description", equalTo("My test secret description"))
|
||||
.body("Name", equalTo("cfn-desc-secret"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_secretWithDescriptionAndGenerateSecretString() {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MySecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"Name": "cfn-desc-gen-secret",
|
||||
"Description": "Generated secret with desc",
|
||||
"GenerateSecretString": {
|
||||
"PasswordLength": 16,
|
||||
"ExcludeNumbers": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "desc-gen-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Verify description
|
||||
given()
|
||||
.header("X-Amz-Target", "secretsmanager.DescribeSecret")
|
||||
.contentType(SM_CONTENT_TYPE)
|
||||
.body("{\"SecretId\": \"cfn-desc-gen-secret\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Description", equalTo("Generated secret with desc"));
|
||||
|
||||
// Verify generated value
|
||||
String body = given()
|
||||
.header("X-Amz-Target", "secretsmanager.GetSecretValue")
|
||||
.contentType(SM_CONTENT_TYPE)
|
||||
.body("{\"SecretId\": \"cfn-desc-gen-secret\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
|
||||
try {
|
||||
JsonNode json = OBJECT_MAPPER.readTree(body);
|
||||
String secretString = json.get("SecretString").asText();
|
||||
assertThat(secretString.length(), equalTo(16));
|
||||
assertThat(secretString, not(matchesRegex(".*[0-9].*")));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_secretWithBothSecretStringAndGenerateSecretString_fails() {
|
||||
// AWS rejects when both SecretString and GenerateSecretString are specified
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MySecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"Name": "cfn-both-secret",
|
||||
"SecretString": "explicit-value",
|
||||
"GenerateSecretString": {
|
||||
"PasswordLength": 64
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "both-secret-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// The resource should have failed provisioning
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackResources")
|
||||
.formParam("StackName", "both-secret-stack")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("CREATE_FAILED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_secretWithNoSecretStringOrGenerate_defaultsEmptyJson() {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MySecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"Name": "cfn-no-value-secret"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "no-value-secret-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "secretsmanager.GetSecretValue")
|
||||
.contentType(SM_CONTENT_TYPE)
|
||||
.body("{\"SecretId\": \"cfn-no-value-secret\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("SecretString", equalTo("{}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_secretAutoName_withGenerateSecretString() {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"AutoSecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"GenerateSecretString": {
|
||||
"PasswordLength": 10,
|
||||
"ExcludeLowercase": true,
|
||||
"ExcludeUppercase": true,
|
||||
"ExcludePunctuation": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "auto-gen-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// Verify resource was created with auto-generated name
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackResources")
|
||||
.formParam("StackName", "auto-gen-stack")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("auto-gen-stack-AutoSecret-"))
|
||||
.body(containsString("CREATE_COMPLETE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_secretRefReturnsArn() {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"MySecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"Properties": {
|
||||
"Name": "cfn-ref-secret",
|
||||
"GenerateSecretString": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"SecretArn": {
|
||||
"Value": {"Ref": "MySecret"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", "ref-secret-stack")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", "ref-secret-stack")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("arn:aws:secretsmanager:"));
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package io.github.hectorvent.floci.services.secretsmanager;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class RandomPasswordGeneratorTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void defaultGenerates32Chars() {
|
||||
String password = RandomPasswordGenerator.generate(MAPPER.createObjectNode());
|
||||
assertThat(password, hasLength(32));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullNodeGenerates32Chars() {
|
||||
String password = RandomPasswordGenerator.generate(null);
|
||||
assertThat(password, hasLength(32));
|
||||
}
|
||||
|
||||
@Test
|
||||
void customLength() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("PasswordLength", 64);
|
||||
assertThat(RandomPasswordGenerator.generate(node), hasLength(64));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lengthOfOne_withRequireEachDisabled() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("PasswordLength", 1);
|
||||
node.put("RequireEachIncludedType", false);
|
||||
assertThat(RandomPasswordGenerator.generate(node), hasLength(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lengthOfOne_withRequireEachEnabled_returnsMinimum4() {
|
||||
// RequireEachIncludedType defaults to true, forcing minimum 4 (one per char type)
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("PasswordLength", 1);
|
||||
assertThat(RandomPasswordGenerator.generate(node), hasLength(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lengthAbove4096Throws() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("PasswordLength", 4097);
|
||||
assertThrows(IllegalArgumentException.class, () -> RandomPasswordGenerator.generate(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lengthZeroThrows() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("PasswordLength", 0);
|
||||
assertThrows(IllegalArgumentException.class, () -> RandomPasswordGenerator.generate(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void negativeLengthThrows() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("PasswordLength", -5);
|
||||
assertThrows(IllegalArgumentException.class, () -> RandomPasswordGenerator.generate(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludeLowercase() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("ExcludeLowercase", true);
|
||||
node.put("PasswordLength", 100);
|
||||
assertThat(RandomPasswordGenerator.generate(node), not(matchesPattern(".*[a-z].*")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludeUppercase() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("ExcludeUppercase", true);
|
||||
node.put("PasswordLength", 100);
|
||||
assertThat(RandomPasswordGenerator.generate(node), not(matchesPattern(".*[A-Z].*")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludeNumbers() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("ExcludeNumbers", true);
|
||||
node.put("PasswordLength", 100);
|
||||
assertThat(RandomPasswordGenerator.generate(node), not(matchesPattern(".*[0-9].*")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludePunctuation() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("ExcludePunctuation", true);
|
||||
node.put("PasswordLength", 100);
|
||||
assertThat(RandomPasswordGenerator.generate(node),
|
||||
not(matchesPattern(".*[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~].*")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void includeSpace() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("IncludeSpace", true);
|
||||
node.put("ExcludeLowercase", true);
|
||||
node.put("ExcludeUppercase", true);
|
||||
node.put("ExcludeNumbers", true);
|
||||
node.put("ExcludePunctuation", true);
|
||||
node.put("PasswordLength", 10);
|
||||
assertThat(RandomPasswordGenerator.generate(node), is(" ")); // 10 spaces
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludeCharacters() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("ExcludeCharacters", "abcABC123");
|
||||
node.put("PasswordLength", 100);
|
||||
String password = RandomPasswordGenerator.generate(node);
|
||||
assertThat(password, not(matchesPattern(".*[abcABC123].*")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requireEachIncludedTypeDefaultTrue() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("PasswordLength", 100);
|
||||
String password = RandomPasswordGenerator.generate(node);
|
||||
assertThat(password, matchesPattern(".*[a-z].*"));
|
||||
assertThat(password, matchesPattern(".*[A-Z].*"));
|
||||
assertThat(password, matchesPattern(".*[0-9].*"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requireEachIncludedTypeFalse() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("ExcludeLowercase", true);
|
||||
node.put("ExcludeUppercase", true);
|
||||
node.put("ExcludePunctuation", true);
|
||||
node.put("RequireEachIncludedType", false);
|
||||
node.put("PasswordLength", 32);
|
||||
assertThat(RandomPasswordGenerator.generate(node), matchesPattern("[0-9]+"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyCharsetThrows() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("ExcludeLowercase", true);
|
||||
node.put("ExcludeUppercase", true);
|
||||
node.put("ExcludeNumbers", true);
|
||||
node.put("ExcludePunctuation", true);
|
||||
assertThrows(IllegalArgumentException.class, () -> RandomPasswordGenerator.generate(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxLength4096Works() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("PasswordLength", 4096);
|
||||
assertThat(RandomPasswordGenerator.generate(node), hasLength(4096));
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludeAllButDigitsWithExcludeCharacters() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("ExcludeLowercase", true);
|
||||
node.put("ExcludeUppercase", true);
|
||||
node.put("ExcludePunctuation", true);
|
||||
node.put("ExcludeCharacters", "02468");
|
||||
node.put("PasswordLength", 20);
|
||||
// Only odd digits should remain: 1, 3, 5, 7, 9
|
||||
assertThat(RandomPasswordGenerator.generate(node), matchesPattern("[13579]+"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user