Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(vault): Add vault secrets support #430

Merged
merged 4 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ The **`generateDrivenAdapter | gda`** task will generate a module in Infrastruct
| restconsumer | Rest Client Consumer | --url [url] --from-swagger swagger.yaml | ☑ | ☑ |
| rsocket | RSocket Requester | | ☑ | ☑ |
| s3 | AWS Simple Storage Service | | ☑ | ☑ |
| secrets | Secrets Manager Bancolombia | | ☑ | ☑ |
| secrets | Secrets Manager Bancolombia | --secrets-backend [backend] <br> Valid options for backend are "aws_secrets_manager" (default) or "vault". | &#9745; | &#9745; |
| sqs | SQS message sender | | &#9745; | &#9745; |


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ dependencies {
implementation project(':model')
implementation 'jakarta.persistence:jakarta.persistence-api'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'com.github.bancolombia:aws-secrets-manager-sync:4.1.0'
implementation 'com.github.bancolombia:aws-secrets-manager-sync:4.4.0'
implementation 'org.reactivecommons.utils:object-mapper-api:0.1.0'
testImplementation 'org.reactivecommons.utils:object-mapper:0.1.0'
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.gradle.testkit.runner.GradleRunner;
import org.gradle.testkit.runner.TaskOutcome;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

Expand Down Expand Up @@ -66,6 +67,9 @@ public class PluginCleanFunctionalTest {
COMPILE_EXCLUDE_GROUP_ORG_SPRINGFRAMEWORK_BOOT_MODULE_SPRING_BOOT_STARTER_TOMCAT =
"implementation.exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'";
public static final String ASYNCEVENTBUS = "ASYNCEVENTBUS";

public static final String SECRETS = "SECRETS";

public static final String RESTMVC = "restmvc";
public static final String SERVER = "--server=";
public static final String VALIDATE_STRUCTURE = "validateStructure";
Expand Down Expand Up @@ -250,6 +254,68 @@ public void canRunTaskGenerateStructureWithOutParameters() {
assertEquals(result.task(":" + task).getOutcome(), TaskOutcome.SUCCESS);
}

@Test
public void canRunTaskGenerateStructureImperative() {

String task = "ca";

runner.withArguments(task, TYPE + "imperative");
runner.withProjectDir(projectDir);
BuildResult result = runner.build();
// Verify the result
assertTrue(new File(BUILD_FUNCTIONAL_TEST_README_MD).exists());
assertTrue(new File(BUILD_FUNCTIONAL_TEST_GITIGNORE).exists());
assertTrue(new File(BUILD_FUNCTIONAL_TEST_BUILD_GRADLE).exists());
assertTrue(new File("build/functionalTest/lombok.config").exists());
assertTrue(new File(BUILD_FUNCTIONAL_TEST_MAIN_GRADLE).exists());
assertTrue(new File(BUILD_FUNCTIONAL_TEST_SETTINGS_GRADLE).exists());

assertTrue(new File(BUILD_FUNCTIONAL_TEST_INFRASTRUCTURE_DRIVEN_ADAPTERS).exists());
assertTrue(new File(BUILD_FUNCTIONAL_TEST_INFRASTRUCTURE_ENTRY_POINTS).exists());
assertTrue(new File(BUILD_FUNCTIONAL_TEST_INFRASTRUCTURE_HELPERS).exists());

assertTrue(
new File("build/functionalTest/domain/model/src/main/java/co/com/bancolombia/model")
.exists());
assertTrue(
new File("build/functionalTest/domain/model/src/test/java/co/com/bancolombia/model")
.exists());
assertTrue(new File(BUILD_FUNCTIONAL_TEST_DOMAIN_MODEL_BUILD_GRADLE).exists());
assertTrue(
new File("build/functionalTest/domain/usecase/src/main/java/co/com/bancolombia/usecase")
.exists());
assertTrue(
new File("build/functionalTest/domain/usecase/src/test/java/co/com/bancolombia/usecase")
.exists());
assertTrue(new File(BUILD_FUNCTIONAL_TEST_DOMAIN_USECASE_BUILD_GRADLE).exists());

assertTrue(new File(BUILD_FUNCTIONAL_TEST_APPLICATIONS_APP_SERVICE_BUILD_GRADLE).exists());
assertTrue(
new File(
"build/functionalTest/applications/app-service/src/main/java/co/com/bancolombia/MainApplication.java")
.exists());
assertTrue(
new File(
"build/functionalTest/applications/app-service/src/main/java/co/com/bancolombia/config/UseCasesConfig.java")
.exists());
assertTrue(
new File(
"build/functionalTest/applications/app-service/src/main/java/co/com/bancolombia/config")
.exists());
assertTrue(
new File(BUILD_FUNCTIONAL_TEST_APPLICATIONS_APP_SERVICE_SRC_MAIN_RESOURCES_APPLICATION_YAML)
.exists());
assertTrue(
new File(
BUILD_FUNCTIONAL_TEST_APPLICATIONS_APP_SERVICE_SRC_MAIN_RESOURCES_LOG_4_J_2_PROPERTIES)
.exists());
assertTrue(
new File("build/functionalTest/applications/app-service/src/test/java/co/com/bancolombia")
.exists());

assertEquals(result.task(":" + task).getOutcome(), TaskOutcome.SUCCESS);
}

public void canRunTaskGenerateStructureWithOutParametersValidator() {

runner.withArguments("ca", "--lombok=" + "false");
Expand Down Expand Up @@ -643,15 +709,52 @@ public void canRunTaskGenerateDrivenAdapterEventBusTest() {
assertEquals(result.task(":" + task).getOutcome(), TaskOutcome.SUCCESS);
}

@Test(expected = Exception.class)
@Test
public void shouldFailTaskGenerateDrivenAdapterEventBusForNonReactiveTest() {
canRunTaskGenerateStructureWithOutParameters();
canRunTaskGenerateStructureImperative();
String task = GENERATE_DRIVEN_ADAPTER;
String valueDrivenAdapter = ASYNCEVENTBUS;

runner.withArguments(task, TYPE + valueDrivenAdapter);
runner.withProjectDir(projectDir);

try {
runner.build();
} catch (Exception e) {
Assert.assertTrue(
e.getMessage().contains("This module is only available for reactive projects"));
}
}

@Test
public void shouldGenerateDrivenAdapterSecretsForVaultInReactiveTest() throws IOException {
canRunTaskGenerateStructureWithOutParameters();
String task = GENERATE_DRIVEN_ADAPTER;
String valueDrivenAdapter = SECRETS;
runner.withArguments(task, TYPE + valueDrivenAdapter, "--secrets-backend=VAULT");
runner.withProjectDir(projectDir);
runner.build();

assertTrue(
FileUtils.readFileToString(
new File(BUILD_FUNCTIONAL_TEST_APPLICATIONS_APP_SERVICE_BUILD_GRADLE),
StandardCharsets.UTF_8)
.contains("implementation 'com.github.bancolombia:vault-async:"));
}

@Test
public void shouldGenerateDrivenAdapterSecretsForAWSInReactiveTest() throws IOException {
canRunTaskGenerateStructureWithOutParameters();
String task = GENERATE_DRIVEN_ADAPTER;
String valueDrivenAdapter = SECRETS;
runner.withArguments(task, TYPE + valueDrivenAdapter, "--secrets-backend=AWS_SECRETS_MANAGER");
runner.withProjectDir(projectDir);
runner.build();

assertTrue(
FileUtils.readFileToString(
new File(BUILD_FUNCTIONAL_TEST_APPLICATIONS_APP_SERVICE_BUILD_GRADLE),
StandardCharsets.UTF_8)
.contains("implementation 'com.github.bancolombia:aws-secrets-manager-async"));
}

@Test
Expand Down
46 changes: 35 additions & 11 deletions src/main/java/co/com/bancolombia/factory/ModuleBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
import static co.com.bancolombia.Constants.MainFiles.KTS;
import static co.com.bancolombia.task.GenerateStructureTask.Language.JAVA;
import static co.com.bancolombia.task.GenerateStructureTask.Language.KOTLIN;
import static org.gradle.internal.logging.text.StyledTextOutput.Style.Description;
import static org.gradle.internal.logging.text.StyledTextOutput.Style.Header;
import static org.gradle.internal.logging.text.StyledTextOutput.Style.Normal;
import static org.gradle.internal.logging.text.StyledTextOutput.Style.Success;
import static org.gradle.internal.logging.text.StyledTextOutput.Style.*;

import co.com.bancolombia.Constants;
import co.com.bancolombia.exceptions.CleanException;
import co.com.bancolombia.exceptions.ParamNotFoundException;
import co.com.bancolombia.exceptions.ValidationException;
import co.com.bancolombia.factory.adapters.DrivenAdapterSecrets;
import co.com.bancolombia.factory.validations.Validation;
import co.com.bancolombia.models.FileModel;
import co.com.bancolombia.models.Release;
import co.com.bancolombia.models.TemplateDefinition;
import co.com.bancolombia.task.AbstractCleanArchitectureDefaultTask;
import co.com.bancolombia.utils.FileUpdater;
import co.com.bancolombia.utils.FileUtils;
import co.com.bancolombia.utils.Utils;
Expand All @@ -33,13 +33,7 @@
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -213,6 +207,36 @@ public Set<String> findExpressions(String path, String regex) {
.collect(Collectors.toSet());
}

public String getSecretsBackendEnabled() {
String fileName = "applications/app-service/build.gradle";
if (isKotlin()) {
fileName += ".kts";
}
if (!findExpressions(fileName, "com.github.bancolombia:aws-secrets").isEmpty()) {
return "AWS_SECRETS_MANAGER";
} else if (!findExpressions(fileName, "com.github.bancolombia:vault").isEmpty()) {
return "VAULT";
} else {
return "NONE";
}
}

public void setUpSecretsInAdapter() throws CleanException, IOException {
boolean includeSecrets = Boolean.TRUE.equals(getBooleanParam("include-secret"));
if (!includeSecrets) {
return;
}
String secretsBackend = getSecretsBackendEnabled();
if (secretsBackend.equals("NONE")) {
new DrivenAdapterSecrets().buildModule(this);
// when new secrets backend is added, the default is aws
addParam("include-awssecrets", AbstractCleanArchitectureDefaultTask.BooleanOption.TRUE);
} else {
addParam("include-awssecrets", "AWS_SECRETS_MANAGER".equalsIgnoreCase(secretsBackend));
addParam("include-vaultsecrets", "VAULT".equalsIgnoreCase(secretsBackend));
}
}

public void appendDependencyToModule(String module, String dependency) throws IOException {
String buildFilePath = project.getChildProjects().get(module).getBuildFile().getPath();
buildFilePath = buildFilePath.replace(project.getProjectDir().getPath(), ".");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
public class DrivenAdapterJPA implements ModuleFactory {
@Override
public void buildModule(ModuleBuilder builder) throws IOException, CleanException {

builder.setUpSecretsInAdapter();

builder.setupFromTemplate("driven-adapter/jpa-repository");
builder.appendToSettings("jpa-repository", "infrastructure/driven-adapters");
builder
Expand All @@ -25,9 +28,7 @@ public void buildModule(ModuleBuilder builder) throws IOException, CleanExceptio
.put("databasePlatform", "org.hibernate.dialect.H2Dialect");
String dependency = buildImplementationFromProject(builder.isKotlin(), ":jpa-repository");
builder.appendDependencyToModule(APP_SERVICE, dependency);
if (Boolean.TRUE.equals(builder.getBooleanParam("include-secret"))) {
new DrivenAdapterSecrets().buildModule(builder);
}

new ObjectMapperFactory().buildModule(builder);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,22 @@ public class DrivenAdapterMongoDB implements ModuleFactory {
@Override
public void buildModule(ModuleBuilder builder) throws IOException, CleanException {
Logger logger = builder.getProject().getLogger();

builder.setUpSecretsInAdapter();

if (Boolean.TRUE.equals(builder.isReactive())) {
logger.lifecycle("Generating for reactive project");
builder.setupFromTemplate("driven-adapter/mongo-reactive");
} else {
logger.lifecycle("Generating for imperative project");
builder.setupFromTemplate("driven-adapter/mongo-repository");
}

builder.appendToSettings("mongo-repository", "infrastructure/driven-adapters");
builder.appendToProperties("spring.data.mongodb").put("uri", "mongodb://localhost:27017/test");
String dependency = buildImplementationFromProject(builder.isKotlin(), ":mongo-repository");
builder.appendDependencyToModule(APP_SERVICE, dependency);
if (Boolean.TRUE.equals(builder.getBooleanParam("include-secret"))) {
new DrivenAdapterSecrets().buildModule(builder);
}

new ObjectMapperFactory().buildModule(builder);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ public void buildModule(ModuleBuilder builder) throws IOException, CleanExceptio
Logger logger = builder.getProject().getLogger();
String typePath = getPathType(builder.isReactive());
String modePath = getPathMode((Mode) builder.getParam(PARAM_MODE));

builder.setUpSecretsInAdapter();

logger.lifecycle("Generating {} in {} mode", typePath, modePath);
builder.setupFromTemplate("driven-adapter/" + typePath + "/" + modePath);
builder.appendToSettings("redis", "infrastructure/driven-adapters");
Expand All @@ -34,9 +37,7 @@ public void buildModule(ModuleBuilder builder) throws IOException, CleanExceptio
}
String dependency = buildImplementationFromProject(builder.isKotlin(), ":redis");
builder.appendDependencyToModule(APP_SERVICE, dependency);
if (Boolean.TRUE.equals(builder.getBooleanParam("include-secret"))) {
new DrivenAdapterSecrets().buildModule(builder);
}

new ObjectMapperFactory().buildModule(builder);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,47 @@ public class DrivenAdapterSecrets implements ModuleFactory {
@Override
public void buildModule(ModuleBuilder builder) throws IOException, CleanException {
Logger logger = builder.getProject().getLogger();

String secretLibrary = "";
if (Boolean.TRUE.equals(builder.isReactive())) {
secretLibrary = "aws-secrets-manager-async";
builder.setupFromTemplate("driven-adapter/secrets-reactive");
SecretsBackend secretsBackend = (SecretsBackend) builder.getParam("secrets-backend");
if (secretsBackend == null || secretsBackend.equals(SecretsBackend.AWS_SECRETS_MANAGER)) {
if (Boolean.TRUE.equals(builder.isReactive())) {
secretLibrary = "aws-secrets-manager-async";
builder.setupFromTemplate("driven-adapter/secrets-reactive");
} else {
secretLibrary = "aws-secrets-manager-sync";
builder.setupFromTemplate("driven-adapter/secrets");
}
logger.lifecycle("Generating mode for aws secrets");
builder.appendToProperties("aws").put("region", "us-east-1").put("secretName", "my-secret");
GenericModule.addAwsBom(builder);
} else {
secretLibrary = "aws-secrets-manager-sync";
builder.setupFromTemplate("driven-adapter/secrets");
if (Boolean.TRUE.equals(builder.isReactive())) {
secretLibrary = "vault-async";
builder.setupFromTemplate("driven-adapter/secrets-vault-reactive");
} else {
secretLibrary = "vault-sync";
builder.setupFromTemplate("driven-adapter/secrets-vault");
}
builder
.appendToProperties("vault")
.put("host", "localhost")
.put("port", 8200)
.put("roleId", "<set your roleId>")
.put("secretId", "<set your secretId>")
.put("secretName", "my-secret");
logger.lifecycle("Generating mode for vault secrets");
}
logger.lifecycle("Generating mode");
GenericModule.addAwsBom(builder);
String dependency =
buildImplementation(
builder.isKotlin(),
"com.github.bancolombia:" + secretLibrary + ":" + Constants.SECRETS_VERSION);
builder.appendDependencyToModule(APP_SERVICE, dependency);
builder.appendToProperties("aws").put("region", "us-east-1").put("secretName", "my-secret");
}

public enum SecretsBackend {
AWS_SECRETS_MANAGER,
VAULT,
NONE
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import co.com.bancolombia.factory.adapters.DrivenAdapterBinStash;
import co.com.bancolombia.factory.adapters.DrivenAdapterRedis;
import co.com.bancolombia.factory.adapters.DrivenAdapterSecrets;
import co.com.bancolombia.task.annotations.CATask;
import java.util.Arrays;
import java.util.List;
Expand All @@ -15,6 +16,9 @@
public class GenerateDrivenAdapterTask extends AbstractResolvableTypeTask {
private String url = "http://localhost:8080";
private String swaggerFile = null;
private DrivenAdapterSecrets.SecretsBackend secretsBackend =
DrivenAdapterSecrets.SecretsBackend.AWS_SECRETS_MANAGER;

private DrivenAdapterRedis.Mode mode = DrivenAdapterRedis.Mode.TEMPLATE;
private DrivenAdapterBinStash.CacheMode cacheMode = DrivenAdapterBinStash.CacheMode.LOCAL;

Expand Down Expand Up @@ -61,6 +65,11 @@ public void setFromSwagger(String swaggerFile) {
this.swaggerFile = swaggerFile;
}

@Option(option = "secrets-backend", description = "Set secrets backend")
public void setSecretsBackend(DrivenAdapterSecrets.SecretsBackend secretsBackend) {
this.secretsBackend = secretsBackend;
}

@Override
protected void prepareParams() {
builder.addParam("task-param-cache-mode", cacheMode);
Expand All @@ -69,6 +78,7 @@ protected void prepareParams() {
builder.addParam(DrivenAdapterRedis.PARAM_MODE, mode);
builder.addParam("task-param-url", url);
builder.addParam("swagger-file", swaggerFile);
builder.addParam("secrets-backend", secretsBackend);
}

@Override
Expand Down
Loading
Loading