From e11b197052864dd3395697a0df2eabd58314345e Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 00:22:18 +0200
Subject: [PATCH 01/34] fix compile encoding issue
---
build.gradle | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/build.gradle b/build.gradle
index 4503e12e..e532eaa9 100644
--- a/build.gradle
+++ b/build.gradle
@@ -46,10 +46,14 @@ compileJava {
options.compilerArgs = ['--release', '8']
}
+compileJava.options.encoding = 'UTF-8'
+compileTestJava.options.encoding = 'UTF-8'
+
task compileModuleInfoJava(type: JavaCompile) {
classpath = files()
source = 'src/main/java/module-info.java'
destinationDir = compileJava.destinationDir
+ options.encoding = compileJava.options.encoding
doFirst {
options.compilerArgs = [
From 6750d9fa04fd77e09e39eee6c74145f74df6cc51 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 22:51:46 +0200
Subject: [PATCH 02/34] fix javadoc compile issue
---
.../bettercloud/vault/api/database/DatabaseRoleOptions.java | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/api/database/DatabaseRoleOptions.java b/src/main/java/com/bettercloud/vault/api/database/DatabaseRoleOptions.java
index 9e2ce4ed..86320d0d 100644
--- a/src/main/java/com/bettercloud/vault/api/database/DatabaseRoleOptions.java
+++ b/src/main/java/com/bettercloud/vault/api/database/DatabaseRoleOptions.java
@@ -46,7 +46,7 @@ public List getRollbackStatements() {
}
/**
- * @param name (string: ) – Specifies the name of the role to create. This is specified as part of the URL.
+ * @param name {@code String} – Specifies the name of the role to create. This is specified as part of the URL.
* @return This object, with name populated, ready for other builder methods or immediate use.
*/
public DatabaseRoleOptions name(final String name) {
@@ -55,7 +55,7 @@ public DatabaseRoleOptions name(final String name) {
}
/**
- * @param dbName (string: ) - The name of the database connection to use for this role.
+ * @param dbName {@code String} - The name of the database connection to use for this role.
* @return This object, with dbName populated, ready for other builder methods or immediate use.
*/
public DatabaseRoleOptions dbName(final String dbName) {
@@ -82,7 +82,7 @@ public DatabaseRoleOptions maxTtl(final String maxTtl) {
}
/**
- * @param creationStatements (list: ) – Specifies the database statements executed to create and configure a user. See the plugin's API page for more information on support and formatting for this parameter.
+ * @param creationStatements {@code List} – Specifies the database statements executed to create and configure a user. See the plugin's API page for more information on support and formatting for this parameter.
* @return This object, with creationStatements populated, ready for other builder methods or immediate use.
*/
public DatabaseRoleOptions creationStatements(final List creationStatements) {
From 753cb977fa19939f686e8ac7872eeb7ea381aed2 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 22:59:08 +0200
Subject: [PATCH 03/34] fix testcontainer deprecation and use extend generic
container pattern
---
build.gradle | 2 +-
.../vault/api/AuthBackendDatabaseTests.java | 6 +-
.../vault/api/VaultAgentTests.java | 7 +-
.../bettercloud/vault/util/DbContainer.java | 32 +++------
.../vault/util/VaultAgentContainer.java | 26 ++++---
.../vault/util/VaultContainer.java | 71 +++++++------------
6 files changed, 55 insertions(+), 89 deletions(-)
diff --git a/build.gradle b/build.gradle
index e532eaa9..6c6517d9 100644
--- a/build.gradle
+++ b/build.gradle
@@ -18,7 +18,7 @@ repositories {
dependencies {
testCompile('junit:junit:4.12')
testCompile('org.mockito:mockito-core:2.28.2')
- testCompile('org.testcontainers:testcontainers:1.11.3')
+ testCompile('org.testcontainers:testcontainers:1.12.0')
testCompile('org.eclipse.jetty:jetty-server:9.4.19.v20190610')
testCompile('org.slf4j:slf4j-api:1.7.26')
testCompile('org.bouncycastle:bcprov-jdk15on:1.62')
diff --git a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendDatabaseTests.java b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendDatabaseTests.java
index 5f773f62..eefffb10 100644
--- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendDatabaseTests.java
+++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendDatabaseTests.java
@@ -19,16 +19,16 @@
public class AuthBackendDatabaseTests {
@ClassRule
- public static final VaultContainer container = new VaultContainer();
+ public static final DbContainer dbContainer = new DbContainer();
@ClassRule
- public static final DbContainer dbContainer = new DbContainer();
+ public static final VaultContainer container = new VaultContainer().dependsOn(dbContainer);
@BeforeClass
public static void setupClass() throws IOException, InterruptedException {
container.initAndUnsealVault();
- container.setupBackendDatabase(dbContainer.getDbContainerIp());
+ container.setupBackendDatabase(DbContainer.hostname);
}
@Test
diff --git a/src/test-integration/java/com/bettercloud/vault/api/VaultAgentTests.java b/src/test-integration/java/com/bettercloud/vault/api/VaultAgentTests.java
index d63849be..59c75ccc 100644
--- a/src/test-integration/java/com/bettercloud/vault/api/VaultAgentTests.java
+++ b/src/test-integration/java/com/bettercloud/vault/api/VaultAgentTests.java
@@ -6,9 +6,7 @@
import com.bettercloud.vault.response.LogicalResponse;
import com.bettercloud.vault.util.VaultAgentContainer;
import com.bettercloud.vault.util.VaultContainer;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.*;
import org.junit.rules.TemporaryFolder;
import java.io.File;
@@ -25,6 +23,7 @@ public class VaultAgentTests {
public static final VaultContainer container = new VaultContainer();
@ClassRule
public static final TemporaryFolder temp = new TemporaryFolder();
+ @ClassRule
public static VaultAgentContainer vaultAgentContainer;
@BeforeClass
@@ -49,6 +48,7 @@ public static void setupClass() throws IOException, InterruptedException, VaultE
writeStringToFile(role_id, appRoleId);
writeStringToFile(secret_id, secretId);
vaultAgentContainer = new VaultAgentContainer(role_id.toPath(), secret_id.toPath());
+ vaultAgentContainer.start();
}
@Test
@@ -67,5 +67,4 @@ public void testWriteAndReadFromAgent() throws VaultException {
final String valueRead = vault.logical().read(pathToRead).getData().get("value");
assertEquals(value, valueRead);
}
-
}
diff --git a/src/test-integration/java/com/bettercloud/vault/util/DbContainer.java b/src/test-integration/java/com/bettercloud/vault/util/DbContainer.java
index 570a20e1..6e2954b2 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/DbContainer.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/DbContainer.java
@@ -1,35 +1,25 @@
package com.bettercloud.vault.util;
-import org.junit.rules.TestRule;
-import org.junit.runner.Description;
-import org.junit.runners.model.Statement;
-import org.testcontainers.containers.Container;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.testcontainers.containers.GenericContainer;
-import org.testcontainers.containers.wait.HostPortWaitStrategy;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy;
-import java.io.IOException;
+public class DbContainer extends GenericContainer implements TestConstants {
-public class DbContainer implements TestRule, TestConstants {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DbContainer.class);
- private final GenericContainer container;
+ public static final String hostname = "postgres";
public DbContainer() {
- container = new GenericContainer("postgres:11.3-alpine")
+ super("postgres:11.3-alpine");
+ this.withNetwork(CONTAINER_NETWORK)
+ .withNetworkAliases(hostname)
.withEnv("POSTGRES_PASSWORD", POSTGRES_PASSWORD)
.withEnv("POSTGRES_USER", POSTGRES_USER)
.withExposedPorts(5432)
+ .withLogConsumer(new Slf4jLogConsumer(LOGGER))
.waitingFor(new HostPortWaitStrategy());
}
-
- public String getDbContainerIp() throws IOException, InterruptedException {
- Container.ExecResult ip = container.execInContainer("hostname", "-i");
- return ip.getStdout().replace("\n", "");
-
- //return container.getContainerIpAddress();
- }
-
- @Override
- public Statement apply(Statement base, Description description) {
- return container.apply(base, description);
- }
}
diff --git a/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java b/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
index ad4b5aab..4d91692a 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
@@ -3,21 +3,23 @@
import com.bettercloud.vault.Vault;
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
-import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.model.Capability;
import java.nio.file.Path;
import java.util.function.Consumer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.GenericContainer;
-import org.testcontainers.containers.wait.Wait;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.containers.wait.strategy.Wait;
import static org.testcontainers.utility.MountableFile.forHostPath;
-public class VaultAgentContainer implements TestConstants {
+public class VaultAgentContainer extends GenericContainer implements TestConstants {
- private final GenericContainer container;
+ private static final Logger LOGGER = LoggerFactory.getLogger(VaultAgentContainer.class);
/**
* Establishes a running Docker container, hosting a Vault agent instance.
@@ -25,23 +27,19 @@ public class VaultAgentContainer implements TestConstants {
public VaultAgentContainer(
Path roleId,
Path secretId) {
- container = new GenericContainer("vault:1.2.1")
- .withNetwork(CONTAINER_NETWORK)
+ super("vault:1.2.1");
+ this.withNetwork(CONTAINER_NETWORK)
+ .withNetworkAliases("agent")
.withClasspathResourceMapping("/agent.hcl", AGENT_CONFIG_FILE, BindMode.READ_ONLY)
.withFileSystemBind(SSL_DIRECTORY, CONTAINER_SSL_DIRECTORY, BindMode.READ_ONLY)
- .withCreateContainerCmdModifier(new Consumer() {
- @Override
- public void accept(final CreateContainerCmd createContainerCmd) {
- createContainerCmd.withCapAdd(Capability.IPC_LOCK);
- }
- })
+ .withCreateContainerCmdModifier(command -> command.withCapAdd(Capability.IPC_LOCK))
.withCopyFileToContainer(forHostPath(roleId), "/home/vault/role_id")
.withCopyFileToContainer(forHostPath(secretId), "/home/vault/secret_id")
.withExposedPorts(8100)
.withEnv("VAULT_CACERT", CONTAINER_CERT_PEMFILE)
.withCommand(String.format("vault agent -config=%s", AGENT_CONFIG_FILE))
+ .withLogConsumer(new Slf4jLogConsumer(LOGGER))
.waitingFor(Wait.forLogMessage(".*renewed auth token.*", 1));
- container.start();
}
/**
@@ -70,6 +68,6 @@ public Vault getVault() throws VaultException {
* @return The URL of the Vault instance
*/
public String getAddress() {
- return String.format("http://%s:%d", container.getContainerIpAddress(), container.getMappedPort(8100));
+ return String.format("http://%s:%d", getContainerIpAddress(), getMappedPort(8100));
}
}
diff --git a/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java b/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
index 8b9c922e..ad937df5 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
@@ -4,18 +4,16 @@
import com.bettercloud.vault.Vault;
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
-import com.github.dockerjava.api.command.CreateContainerCmd;
+import com.bettercloud.vault.json.Json;
+import com.bettercloud.vault.json.JsonObject;
import com.github.dockerjava.api.model.Capability;
-import org.junit.rules.TestRule;
-import org.junit.runner.Description;
-import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.Container;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.output.Slf4jLogConsumer;
-import org.testcontainers.containers.wait.HttpWaitStrategy;
+import org.testcontainers.containers.wait.strategy.HttpWaitStrategy;
import java.io.File;
import java.io.IOException;
@@ -25,11 +23,11 @@
/**
* Sets up and exposes utilities for dealing with a Docker-hosted instance of Vault, for integration tests.
*/
-public class VaultContainer implements TestRule, TestConstants {
+public class VaultContainer extends GenericContainer implements TestConstants {
private static final Logger LOGGER = LoggerFactory.getLogger(VaultContainer.class);
- private final GenericContainer container;
+ public static final String DEFAULT_IMAGE_AND_TAG = "vault:1.1.3";
private String rootToken;
private String unsealKey;
@@ -37,24 +35,19 @@ public class VaultContainer implements TestRule, TestConstants {
/**
* Establishes a running Docker container, hosting a Vault server instance.
*/
- public VaultContainer() {
- container = new GenericContainer("vault:1.1.3")
- .withNetwork(CONTAINER_NETWORK)
+ public VaultContainer(String image) {
+ super(image);
+ this.withNetwork(CONTAINER_NETWORK)
.withNetworkAliases("vault")
.withClasspathResourceMapping("/startup.sh", CONTAINER_STARTUP_SCRIPT, BindMode.READ_ONLY)
.withClasspathResourceMapping("/config.json", CONTAINER_CONFIG_FILE, BindMode.READ_ONLY)
.withClasspathResourceMapping("/libressl.conf", CONTAINER_OPENSSL_CONFIG_FILE, BindMode.READ_ONLY)
.withClasspathResourceMapping("/approlePolicy.hcl", APPROLE_POLICY_FILE, BindMode.READ_ONLY)
.withFileSystemBind(SSL_DIRECTORY, CONTAINER_SSL_DIRECTORY, BindMode.READ_WRITE)
- .withCreateContainerCmdModifier(new Consumer() {
- // TODO: Why does the compiler freak out when this anonymous class is converted to a lambda?
- @Override
- public void accept(final CreateContainerCmd createContainerCmd) {
- createContainerCmd.withCapAdd(Capability.IPC_LOCK);
- }
- })
+ .withCreateContainerCmdModifier(command -> command.withCapAdd(Capability.IPC_LOCK))
.withExposedPorts(8200, 8280)
.withCommand("/bin/sh " + CONTAINER_STARTUP_SCRIPT)
+ .withLogConsumer(new Slf4jLogConsumer(LOGGER))
.waitingFor(
// All of the tests in this integration test suite use HTTPS connections. However, Vault
// is configured to run a plain HTTP listener on port 8280, purely for purposes of detecting
@@ -64,34 +57,21 @@ public void accept(final CreateContainerCmd createContainerCmd) {
// configuring SSL to trust the self-signed cert that's generated inside of the Docker
// container. A chicken-and-egg problem, as we need to wait for the container to be fully
// ready before we access that cert.
- new HttpWaitStrategy() {
- @Override
- protected Integer getLivenessCheckPort() {
- return container.getMappedPort(8280);
- }
- }
+ new HttpWaitStrategy()
+ .forPort(8280)
.forPath("/v1/sys/seal-status")
.forStatusCode(HttpURLConnection.HTTP_OK) // The expected response when "vault init" has not yet run
);
}
- /**
- * Called by JUnit automatically after the constructor method. Launches the Docker container that was configured
- * in the constructor.
- *
- * @param base
- * @param description
- * @return
- */
- @Override
- public Statement apply(final Statement base, final Description description) {
- return container.apply(base, description);
+ public VaultContainer() {
+ this(DEFAULT_IMAGE_AND_TAG);
}
/**
- * To be called by a test class method annotated with {@link org.junit.BeforeClass}. This logic doesn't work
- * when placed inside of the constructor or {@link this#apply(Statement, Description)} methods here, presumably
- * because the Docker container spawned by TestContainers is not ready to accept commonds until after those
+ * To be called by a test class method annotated with {@link org.junit.BeforeClass}.
+ * This logic doesn't work when placed inside of the constructor, presumably
+ * because the Docker container spawned by TestContainers is not ready to accept commands until after those
* methods complete.
*
*
This method initializes the Vault server, capturing the unseal key and root token that are displayed on the
@@ -102,16 +82,15 @@ public Statement apply(final Statement base, final Description description) {
* @throws InterruptedException
*/
public void initAndUnsealVault() throws IOException, InterruptedException {
- final Slf4jLogConsumer logConsumer = new Slf4jLogConsumer(LOGGER);
- container.followOutput(logConsumer);
+
// Initialize the Vault server
final Container.ExecResult initResult = runCommand("vault", "operator", "init", "-ca-cert=" +
- CONTAINER_CERT_PEMFILE, "-key-shares=1", "-key-threshold=1");
- final String stdout = initResult.getStdout().replaceAll(System.lineSeparator(), "").split("Vault initialized")[0];
- final String[] tokens = stdout.split("Initial Root Token: ");
- this.unsealKey = tokens[0].replace("Unseal Key 1: ", "");
- this.rootToken = tokens[1];
+ CONTAINER_CERT_PEMFILE, "-key-shares=1", "-key-threshold=1", "-format=json");
+ final String stdout = initResult.getStdout().replaceAll("\\r?\\n", "");
+ JsonObject initJson = Json.parse(stdout).asObject();
+ this.unsealKey = initJson.get("unseal_keys_b64").asArray().get(0).asString();
+ this.rootToken = initJson.get("root_token").asString();
System.out.println("Root token: " + rootToken);
@@ -345,7 +324,7 @@ public Vault getRootVault() throws VaultException {
* @return The URL of the Vault instance
*/
public String getAddress() {
- return String.format("https://%s:%d", container.getContainerIpAddress(), container.getMappedPort(8200));
+ return String.format("https://%s:%d", getContainerIpAddress(), getMappedPort(8200));
}
/**
@@ -371,7 +350,7 @@ public String getUnsealKey() {
*/
private Container.ExecResult runCommand(final String... command) throws IOException, InterruptedException {
LOGGER.info("Command: {}", String.join(" ", command));
- final Container.ExecResult result = this.container.execInContainer(command);
+ final Container.ExecResult result = execInContainer(command);
final String out = result.getStdout();
final String err = result.getStderr();
if (out != null && !out.isEmpty()) {
From b62b6f5815a56a093a02cf1704bb681fe62343d3 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 00:14:43 +0200
Subject: [PATCH 04/34] fix up logical tests after #176
---
.../bettercloud/vault/api/LogicalTests.java | 37 ++++++++-----------
1 file changed, 16 insertions(+), 21 deletions(-)
diff --git a/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java b/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java
index acd56158..71a68a90 100644
--- a/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java
+++ b/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java
@@ -8,6 +8,7 @@
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.response.AuthResponse;
+import com.bettercloud.vault.response.LogicalResponse;
import com.bettercloud.vault.util.VaultContainer;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -19,6 +20,7 @@
import com.bettercloud.vault.VaultException;
import org.junit.rules.ExpectedException;
+import static junit.framework.Assert.assertNotNull;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
@@ -253,12 +255,10 @@ public void testDestroy() throws VaultException {
* @throws VaultException
*/
@Test
- public void testReadExceptionMessageIncludesErrorsReturnedByVault() throws VaultException {
- expectedEx.expect(VaultException.class);
- expectedEx.expectMessage("permission denied");
-
+ public void testReadPermissionDeniedReturnedByVault() throws VaultException {
final Vault vault = container.getVault(NONROOT_TOKEN);
- vault.logical().read("secret/null");
+ LogicalResponse read = vault.logical().read("secret/null");
+ assertEquals(403, read.getRestResponse().getStatus());
}
/**
@@ -267,14 +267,12 @@ public void testReadExceptionMessageIncludesErrorsReturnedByVault() throws Vault
* @throws VaultException
*/
@Test
- public void testWriteExceptionMessageIncludesErrorsReturnedByVault() throws VaultException {
- expectedEx.expect(VaultException.class);
- expectedEx.expectMessage("permission denied");
-
+ public void testWritePermissionDeniedReturnedByVault() throws VaultException {
final Vault vault = container.getVault(NONROOT_TOKEN);
final Map testMap = new HashMap<>();
testMap.put("value", null);
- vault.logical().write("secret/null", testMap);
+ LogicalResponse write = vault.logical().write("secret/null", testMap);
+ assertEquals(403, write.getRestResponse().getStatus());
}
/**
@@ -288,7 +286,8 @@ public void testDeleteExceptionMessageIncludesErrorsReturnedByVault() throws Vau
expectedEx.expectMessage("permission denied");
final Vault vault = container.getVault(NONROOT_TOKEN);
- vault.logical().delete("secret/null");
+ LogicalResponse delete = vault.logical().delete("secret/null");
+ assertEquals(403, delete.getRestResponse().getStatus());
}
/**
@@ -297,12 +296,10 @@ public void testDeleteExceptionMessageIncludesErrorsReturnedByVault() throws Vau
* @throws VaultException
*/
@Test
- public void testListExceptionMessageIncludesErrorsReturnedByVault() throws VaultException {
- expectedEx.expect(VaultException.class);
- expectedEx.expectMessage("permission denied");
-
+ public void testListPermissionDeniedReturnedByVault() throws VaultException {
final Vault vault = container.getVault(NONROOT_TOKEN);
- vault.logical().list("secret/null");
+ List list = vault.logical().list("secret/null");
+ assertEquals(list.size(), 0);
}
/**
@@ -311,13 +308,11 @@ public void testListExceptionMessageIncludesErrorsReturnedByVault() throws Vault
* @throws VaultException
*/
@Test
- public void testReadExceptionMessageIncludesErrorsReturnedByVaultOn404() throws VaultException {
- expectedEx.expect(VaultException.class);
- expectedEx.expectMessage("{\"errors\":[]}");
-
+ public void testReadReturnedByVaultOn404() throws VaultException {
final Vault vault = container.getRootVault();
final String path = "secret/" + UUID.randomUUID().toString();
- vault.logical().read(path);
+ LogicalResponse read = vault.logical().read(path);
+ assertEquals(404, read.getRestResponse().getStatus());
}
/**
From ffc88395c7205766526954a0fd98093e43d79f92 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 21:40:15 +0200
Subject: [PATCH 05/34] Java 5: unnecessary boxing
---
src/main/java/com/bettercloud/vault/SslConfig.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/com/bettercloud/vault/SslConfig.java b/src/main/java/com/bettercloud/vault/SslConfig.java
index 0ad1ac2a..64de9975 100644
--- a/src/main/java/com/bettercloud/vault/SslConfig.java
+++ b/src/main/java/com/bettercloud/vault/SslConfig.java
@@ -444,7 +444,7 @@ public SslConfig build() throws VaultException {
this.environmentLoader = new EnvironmentLoader();
}
if (this.verifyObject == null && environmentLoader.loadVariable(VAULT_SSL_VERIFY) != null) {
- this.verify = Boolean.valueOf(environmentLoader.loadVariable(VAULT_SSL_VERIFY));
+ this.verify = Boolean.parseBoolean(environmentLoader.loadVariable(VAULT_SSL_VERIFY));
} else if (this.verifyObject != null) {
this.verify = verifyObject;
} else {
From 0f21b6e15c5444158410597acf8248556aab4c11 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 21:40:48 +0200
Subject: [PATCH 06/34] Java 5: unnecessary unboxing
---
src/main/java/com/bettercloud/vault/rest/Rest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/com/bettercloud/vault/rest/Rest.java b/src/main/java/com/bettercloud/vault/rest/Rest.java
index 5914f7e2..eb5e5c4b 100644
--- a/src/main/java/com/bettercloud/vault/rest/Rest.java
+++ b/src/main/java/com/bettercloud/vault/rest/Rest.java
@@ -441,7 +441,7 @@ private URLConnection initURLConnection(final String urlString, final String met
// SSL settings, if applicable
if (connection instanceof HttpsURLConnection) {
final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;
- if (sslVerification != null && !sslVerification.booleanValue()) {
+ if (sslVerification != null && !sslVerification) {
// SSL verification disabled
httpsURLConnection.setSSLSocketFactory(DISABLED_SSL_CONTEXT.getSocketFactory());
httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
From ae2f6e75df98db2d4b38f448fea5df0cdd89f7a9 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 21:41:58 +0200
Subject: [PATCH 07/34] Java 7: explicit type replaced with <>
---
src/main/java/com/bettercloud/vault/json/JsonArray.java | 4 ++--
src/main/java/com/bettercloud/vault/json/JsonObject.java | 8 ++++----
src/main/java/com/bettercloud/vault/rest/Rest.java | 2 +-
3 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/json/JsonArray.java b/src/main/java/com/bettercloud/vault/json/JsonArray.java
index 421b5f90..1f89bcaf 100644
--- a/src/main/java/com/bettercloud/vault/json/JsonArray.java
+++ b/src/main/java/com/bettercloud/vault/json/JsonArray.java
@@ -68,7 +68,7 @@ public class JsonArray extends JsonValue implements Iterable {
* Creates a new empty JsonArray.
*/
public JsonArray() {
- values = new ArrayList();
+ values = new ArrayList<>();
}
/**
@@ -88,7 +88,7 @@ private JsonArray(JsonArray array, boolean unmodifiable) {
if (unmodifiable) {
values = Collections.unmodifiableList(array.values);
} else {
- values = new ArrayList(array.values);
+ values = new ArrayList<>(array.values);
}
}
diff --git a/src/main/java/com/bettercloud/vault/json/JsonObject.java b/src/main/java/com/bettercloud/vault/json/JsonObject.java
index df26011f..3937dfda 100644
--- a/src/main/java/com/bettercloud/vault/json/JsonObject.java
+++ b/src/main/java/com/bettercloud/vault/json/JsonObject.java
@@ -80,8 +80,8 @@ public class JsonObject extends JsonValue implements Iterable {
* Creates a new empty JsonObject.
*/
public JsonObject() {
- names = new ArrayList();
- values = new ArrayList();
+ names = new ArrayList<>();
+ values = new ArrayList<>();
table = new HashIndexTable();
}
@@ -103,8 +103,8 @@ private JsonObject(JsonObject object, boolean unmodifiable) {
names = Collections.unmodifiableList(object.names);
values = Collections.unmodifiableList(object.values);
} else {
- names = new ArrayList(object.names);
- values = new ArrayList(object.values);
+ names = new ArrayList<>(object.names);
+ values = new ArrayList<>(object.values);
}
table = new HashIndexTable();
updateHashIndex();
diff --git a/src/main/java/com/bettercloud/vault/rest/Rest.java b/src/main/java/com/bettercloud/vault/rest/Rest.java
index eb5e5c4b..366613a9 100644
--- a/src/main/java/com/bettercloud/vault/rest/Rest.java
+++ b/src/main/java/com/bettercloud/vault/rest/Rest.java
@@ -481,7 +481,7 @@ public boolean verify(final String s, final SSLSession sslSession) {
*/
private String parametersToQueryString() {
final StringBuilder queryString = new StringBuilder();
- final List> params = new ArrayList>(parameters.entrySet());
+ final List> params = new ArrayList<>(parameters.entrySet());
for (int index = 0; index < params.size(); index++) {
if (index > 0) {
queryString.append('&');
From 00894c256a245f9fc1cb5111d7bd6f8b98213014 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 21:43:57 +0200
Subject: [PATCH 08/34] Java 8: anonymous type replaced with method reference
---
.../java/com/bettercloud/vault/response/MountResponse.java | 7 +------
1 file changed, 1 insertion(+), 6 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/response/MountResponse.java b/src/main/java/com/bettercloud/vault/response/MountResponse.java
index 5e426d0e..a67e8af6 100644
--- a/src/main/java/com/bettercloud/vault/response/MountResponse.java
+++ b/src/main/java/com/bettercloud/vault/response/MountResponse.java
@@ -106,12 +106,7 @@ private Map buildMountsMap() {
}
return StreamSupport.stream(data.spliterator(), false)
- .collect(Collectors.toMap(new Function() {
- @Override
- public String apply(Member member) {
- return member.getName();
- }
- }, new Function() {
+ .collect(Collectors.toMap(Member::getName, new Function() {
@Override
public Mount apply(Member member) {
return buildMount(member.getValue().asObject());
From e301c78208428cd43b834bc62e9f606d3bb20547 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 21:49:15 +0200
Subject: [PATCH 09/34] Java 8: anonymous type replaced with lambda
---
.../vault/api/mounts/MountType.java | 7 +-
.../vault/response/MountResponse.java | 8 +--
.../java/com/bettercloud/vault/rest/Rest.java | 9 +--
.../vault/util/VaultAgentContainer.java | 1 -
.../vault/util/VaultContainer.java | 1 -
.../vault/json/JsonNumber_Test.java | 6 +-
.../com/bettercloud/vault/json/Json_Test.java | 72 ++++---------------
7 files changed, 16 insertions(+), 88 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountType.java b/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
index 3b7bc3d6..8a0ab2a5 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
@@ -1,7 +1,6 @@
package com.bettercloud.vault.api.mounts;
import java.util.Arrays;
-import java.util.function.Predicate;
/**
*
A representation of different available secret engine mount points
@@ -59,11 +58,7 @@ public static MountType of(final String value) {
return Arrays.asList(MountType.values())
.stream()
- .filter(new Predicate() {
- public boolean test(MountType type) {
- return type.value.equals(value);
- }
- })
+ .filter(type -> type.value.equals(value))
.findFirst()
.orElse(null);
}
diff --git a/src/main/java/com/bettercloud/vault/response/MountResponse.java b/src/main/java/com/bettercloud/vault/response/MountResponse.java
index a67e8af6..4c8d8c7d 100644
--- a/src/main/java/com/bettercloud/vault/response/MountResponse.java
+++ b/src/main/java/com/bettercloud/vault/response/MountResponse.java
@@ -2,7 +2,6 @@
import java.util.Collections;
import java.util.Map;
-import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@@ -106,11 +105,6 @@ private Map buildMountsMap() {
}
return StreamSupport.stream(data.spliterator(), false)
- .collect(Collectors.toMap(Member::getName, new Function() {
- @Override
- public Mount apply(Member member) {
- return buildMount(member.getValue().asObject());
- }
- }));
+ .collect(Collectors.toMap(Member::getName, member -> buildMount(member.getValue().asObject())));
}
}
diff --git a/src/main/java/com/bettercloud/vault/rest/Rest.java b/src/main/java/com/bettercloud/vault/rest/Rest.java
index 366613a9..f6be0668 100644
--- a/src/main/java/com/bettercloud/vault/rest/Rest.java
+++ b/src/main/java/com/bettercloud/vault/rest/Rest.java
@@ -1,9 +1,7 @@
package com.bettercloud.vault.rest;
-import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayOutputStream;
@@ -444,12 +442,7 @@ private URLConnection initURLConnection(final String urlString, final String met
if (sslVerification != null && !sslVerification) {
// SSL verification disabled
httpsURLConnection.setSSLSocketFactory(DISABLED_SSL_CONTEXT.getSocketFactory());
- httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
- @Override
- public boolean verify(final String s, final SSLSession sslSession) {
- return true;
- }
- });
+ httpsURLConnection.setHostnameVerifier((s, sslSession) -> true);
} else if (sslContext != null) {
// Cert file supplied
httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
diff --git a/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java b/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
index 4d91692a..43cb978d 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
@@ -6,7 +6,6 @@
import com.github.dockerjava.api.model.Capability;
import java.nio.file.Path;
-import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java b/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
index ad937df5..2c31723b 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
@@ -18,7 +18,6 @@
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
-import java.util.function.Consumer;
/**
* Sets up and exposes utilities for dealing with a Docker-hosted instance of Vault, for integration tests.
diff --git a/src/test/java/com/bettercloud/vault/json/JsonNumber_Test.java b/src/test/java/com/bettercloud/vault/json/JsonNumber_Test.java
index 04f578ba..9978fe90 100644
--- a/src/test/java/com/bettercloud/vault/json/JsonNumber_Test.java
+++ b/src/test/java/com/bettercloud/vault/json/JsonNumber_Test.java
@@ -45,11 +45,7 @@ public void setUp() {
@Test
public void constructor_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "string is null", new Runnable() {
- public void run() {
- new JsonNumber(null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "string is null", (Runnable) () -> new JsonNumber(null));
}
@Test
diff --git a/src/test/java/com/bettercloud/vault/json/Json_Test.java b/src/test/java/com/bettercloud/vault/json/Json_Test.java
index d8455f83..33fea3be 100644
--- a/src/test/java/com/bettercloud/vault/json/Json_Test.java
+++ b/src/test/java/com/bettercloud/vault/json/Json_Test.java
@@ -77,21 +77,13 @@ public void value_float_cutsOffPointZero() {
@Test
public void value_float_failsWithInfinity() {
String message = "Infinite and NaN values not permitted in JSON";
- assertException(IllegalArgumentException.class, message, new Runnable() {
- public void run() {
- Json.value(Float.POSITIVE_INFINITY);
- }
- });
+ assertException(IllegalArgumentException.class, message, (Runnable) () -> Json.value(Float.POSITIVE_INFINITY));
}
@Test
public void value_float_failsWithNaN() {
String message = "Infinite and NaN values not permitted in JSON";
- assertException(IllegalArgumentException.class, message, new Runnable() {
- public void run() {
- Json.value(Float.NaN);
- }
- });
+ assertException(IllegalArgumentException.class, message, (Runnable) () -> Json.value(Float.NaN));
}
@Test
@@ -112,21 +104,13 @@ public void value_double_cutsOffPointZero() {
@Test
public void value_double_failsWithInfinity() {
String message = "Infinite and NaN values not permitted in JSON";
- assertException(IllegalArgumentException.class, message, new Runnable() {
- public void run() {
- Json.value(Double.POSITIVE_INFINITY);
- }
- });
+ assertException(IllegalArgumentException.class, message, (Runnable) () -> Json.value(Double.POSITIVE_INFINITY));
}
@Test
public void value_double_failsWithNaN() {
String message = "Infinite and NaN values not permitted in JSON";
- assertException(IllegalArgumentException.class, message, new Runnable() {
- public void run() {
- Json.value(Double.NaN);
- }
- });
+ assertException(IllegalArgumentException.class, message, (Runnable) () -> Json.value(Double.NaN));
}
@Test
@@ -160,11 +144,7 @@ public void array_int() {
@Test
public void array_int_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "values is null", new Runnable() {
- public void run() {
- Json.array((int[]) null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "values is null", (Runnable) () -> Json.array((int[]) null));
}
@Test
@@ -175,11 +155,7 @@ public void array_long() {
@Test
public void array_long_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "values is null", new Runnable() {
- public void run() {
- Json.array((long[]) null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "values is null", (Runnable) () -> Json.array((long[]) null));
}
@Test
@@ -190,11 +166,7 @@ public void array_float() {
@Test
public void array_float_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "values is null", new Runnable() {
- public void run() {
- Json.array((float[]) null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "values is null", (Runnable) () -> Json.array((float[]) null));
}
@Test
@@ -205,11 +177,7 @@ public void array_double() {
@Test
public void array_double_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "values is null", new Runnable() {
- public void run() {
- Json.array((double[]) null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "values is null", (Runnable) () -> Json.array((double[]) null));
}
@Test
@@ -220,11 +188,7 @@ public void array_boolean() {
@Test
public void array_boolean_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "values is null", new Runnable() {
- public void run() {
- Json.array((boolean[]) null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "values is null", (Runnable) () -> Json.array((boolean[]) null));
}
@Test
@@ -235,11 +199,7 @@ public void array_string() {
@Test
public void array_string_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "values is null", new Runnable() {
- public void run() {
- Json.array((String[]) null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "values is null", (Runnable) () -> Json.array((String[]) null));
}
@Test
@@ -254,11 +214,7 @@ public void parse_string() {
@Test
public void parse_string_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "string is null", new Runnable() {
- public void run() {
- Json.parse((String) null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "string is null", (Runnable) () -> Json.parse((String) null));
}
@Test
@@ -270,11 +226,7 @@ public void parse_reader() throws IOException {
@Test
public void parse_reader_failsWithNull() {
- TestUtil.assertException(NullPointerException.class, "reader is null", new RunnableEx() {
- public void run() throws IOException {
- Json.parse((Reader) null);
- }
- });
+ TestUtil.assertException(NullPointerException.class, "reader is null", (RunnableEx) () -> Json.parse((Reader) null));
}
}
From 891047bf7acbf1b5c4c5f0174c70b8006f5146d1 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 21:51:33 +0200
Subject: [PATCH 10/34] convert field to local
---
.../mock/AuthRequestValidatingMockVault.java | 41 +++++++++----------
1 file changed, 20 insertions(+), 21 deletions(-)
diff --git a/src/test/java/com/bettercloud/vault/vault/mock/AuthRequestValidatingMockVault.java b/src/test/java/com/bettercloud/vault/vault/mock/AuthRequestValidatingMockVault.java
index 687d9333..0e47f78b 100644
--- a/src/test/java/com/bettercloud/vault/vault/mock/AuthRequestValidatingMockVault.java
+++ b/src/test/java/com/bettercloud/vault/vault/mock/AuthRequestValidatingMockVault.java
@@ -10,27 +10,6 @@
public class AuthRequestValidatingMockVault extends MockVault {
private Predicate validator;
- private final String validResponse = "{\n" +
- " \"renewable\": true,\n" +
- " \"auth\": {\n" +
- " \"lease_duration\": 1800000,\n" +
- " \"metadata\": {\n" +
- " \"role_tag_max_ttl\": \"0\",\n" +
- " \"instance_id\": \"i-de0f1344\",\n" +
- " \"ami_id\": \"ami-fce36983\",\n" +
- " \"role\": \"dev-role\",\n" +
- " \"auth_type\": \"ec2\",\n" +
- " \"nonce\": \"5defbf9e-a8f9-3063-bdfc-54b7a42a1f95\"\n" +
- " },\n" +
- " \"policies\": [\n" +
- " \"default\",\n" +
- " \"dev\"\n" +
- " ],\n" +
- " \"accessor\": \"20b89871-e6f2-1160-fb29-31c2f6d4645e\",\n" +
- " \"client_token\": \"c9368254-3f21-aded-8a6f-7c818e81b17a\"\n" +
- " }\n" +
- "}";
-
public AuthRequestValidatingMockVault(Predicate validator) {
this.validator = validator;
@@ -45,6 +24,26 @@ public void handle(String target,
baseRequest.setHandled(true);
if (validator.test(request)) {
response.setStatus(200);
+ String validResponse = "{\n" +
+ " \"renewable\": true,\n" +
+ " \"auth\": {\n" +
+ " \"lease_duration\": 1800000,\n" +
+ " \"metadata\": {\n" +
+ " \"role_tag_max_ttl\": \"0\",\n" +
+ " \"instance_id\": \"i-de0f1344\",\n" +
+ " \"ami_id\": \"ami-fce36983\",\n" +
+ " \"role\": \"dev-role\",\n" +
+ " \"auth_type\": \"ec2\",\n" +
+ " \"nonce\": \"5defbf9e-a8f9-3063-bdfc-54b7a42a1f95\"\n" +
+ " },\n" +
+ " \"policies\": [\n" +
+ " \"default\",\n" +
+ " \"dev\"\n" +
+ " ],\n" +
+ " \"accessor\": \"20b89871-e6f2-1160-fb29-31c2f6d4645e\",\n" +
+ " \"client_token\": \"c9368254-3f21-aded-8a6f-7c818e81b17a\"\n" +
+ " }\n" +
+ "}";
response.getWriter().println(validResponse);
} else {
response.setStatus(400);
From 7f40bec854e138b445ecaa5ad0c9ccf43be33991 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 21:54:01 +0200
Subject: [PATCH 11/34] suppress deprecation in AppIdTests
---
.../java/com/bettercloud/vault/api/AuthBackendAppIdTests.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppIdTests.java b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppIdTests.java
index 49324717..7c4439ff 100644
--- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppIdTests.java
+++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppIdTests.java
@@ -33,6 +33,7 @@ public static void setupClass() throws IOException, InterruptedException {
public void testLoginByAuthId() throws VaultException {
final Vault vault = container.getVault();
final String path = "app-id/login";
+ @SuppressWarnings("deprecation") // used for testing
final String token = vault.auth().loginByAppID(path, VaultContainer.APP_ID, VaultContainer.USER_ID)
.getAuthClientToken();
From 7c14dbac2c6069559384863023ca3c7b6c5199b7 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sat, 24 Aug 2019 22:52:21 +0200
Subject: [PATCH 12/34] fix `SslContextFactory` deprecation by using
`SslContextFactory.Server`
---
src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java b/src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java
index 5a1ae8e8..eb189bc1 100644
--- a/src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java
+++ b/src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java
@@ -39,7 +39,7 @@ public static Server initHttpMockVault(final MockVault mock) {
public static Server initHttpsMockVault(final MockVault mock) {
final Server server = new Server();
- final SslContextFactory sslContextFactory = new SslContextFactory();
+ final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath(VaultTestUtils.class.getResource("/keystore.jks").toExternalForm());
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.setKeyManagerPassword("password");
From b9133ee77ea09251397cfe874877f7429ed8a888 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 01:17:19 +0200
Subject: [PATCH 13/34] add checkstyle
---
build.gradle | 2 +-
config/checkstyle/checkstyle.xml | 12 ++++++++++++
2 files changed, 13 insertions(+), 1 deletion(-)
create mode 100644 config/checkstyle/checkstyle.xml
diff --git a/build.gradle b/build.gradle
index 6c6517d9..f2031734 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,6 +1,7 @@
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'signing'
+apply plugin: 'checkstyle'
group 'com.bettercloud'
archivesBaseName = 'vault-java-driver'
@@ -211,4 +212,3 @@ uploadArchives {
}
}
}
-
diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml
new file mode 100644
index 00000000..1a18d739
--- /dev/null
+++ b/config/checkstyle/checkstyle.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
From de96c0aaefee5169053ae2cae9b4f668b7ce1775 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 00:47:43 +0200
Subject: [PATCH 14/34] fix trailing whitespace
---
.../com/bettercloud/vault/VaultConfig.java | 4 +-
.../bettercloud/vault/api/mounts/Mount.java | 4 +-
.../vault/api/mounts/MountConfig.java | 4 +-
.../vault/api/mounts/MountPayload.java | 2 +-
.../vault/api/mounts/MountType.java | 4 +-
.../bettercloud/vault/api/mounts/Mounts.java | 42 +++++++++----------
.../vault/api/mounts/TimeToLive.java | 6 +--
.../bettercloud/vault/json/JsonObject.java | 12 +++---
8 files changed, 39 insertions(+), 39 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/VaultConfig.java b/src/main/java/com/bettercloud/vault/VaultConfig.java
index 9ba58ef2..85ed7034 100644
--- a/src/main/java/com/bettercloud/vault/VaultConfig.java
+++ b/src/main/java/com/bettercloud/vault/VaultConfig.java
@@ -146,14 +146,14 @@ public VaultConfig secretsEnginePathMap(final Map secretEngineVe
this.secretsEnginePathMap = new ConcurrentHashMap<>(secretEngineVersions);
return this;
}
-
+
/**
*
Sets the secrets Engine version be used by Vault for the provided path.
*
* @param path the path to use for accessing Vault secrets.
* Example "/secret/foo"
* @param version The key-value engine version used for this path.
- * @return This object, with a new entry in the secrets paths map, ready for additional builder-pattern method calls or else finalization with
+ * @return This object, with a new entry in the secrets paths map, ready for additional builder-pattern method calls or else finalization with
* the build() method
*/
public VaultConfig putSecretsEngineVersionForPath(String path, String version) {
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/Mount.java b/src/main/java/com/bettercloud/vault/api/mounts/Mount.java
index 5b277a05..2c6c7c1e 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/Mount.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/Mount.java
@@ -5,7 +5,7 @@
/**
*
A container for options returned by mounts endpoints on the Secret Engine backend. This class is
* meant for use with a builder pattern style. Example usage:
- *
+ *
*
*
{@code
* final Mount options = new Mount()
@@ -15,7 +15,7 @@
*
*/
public class Mount implements Serializable {
-
+
private static final long serialVersionUID = 45748211702309181L;
private MountType type;
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountConfig.java b/src/main/java/com/bettercloud/vault/api/mounts/MountConfig.java
index 7a2627f5..545b96f1 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountConfig.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountConfig.java
@@ -7,10 +7,10 @@
/**
*
A container for options returned by mounts endpoints on the Secret Engine backend. This class is
* meant for use with a builder pattern style. Example usage:
- *
+ *
*
Most of the time this will be wrapped inside Mount object rather than directly sent to Vault backend
* or back to the user.
- *
+ *
*
*
{@code
* final MountConfig config = new MountConfig()
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java b/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
index df002b58..6ef41aa3 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
@@ -11,7 +11,7 @@
/**
*
A container for options sent to mounts endpoints on the Secret Engine backend as REST payload. This class is
* meant for use with a builder pattern style. Example usage:
- *
+ *
*
*
{@code
* final MountPayload payload = new MountPayload()
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountType.java b/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
index 8a0ab2a5..3352db63 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
@@ -46,9 +46,9 @@ public String value() {
/**
*
Get the MountType instance from the provided value string.
- *
+ *
* @param value The mount type value to use to lookup.
- *
+ *
* @return an instance of MountType or null
*/
public static MountType of(final String value) {
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java b/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java
index 441de871..73b724ea 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java
@@ -35,9 +35,9 @@ public Mounts(final VaultConfig config) {
* final Map mounts = response.getMounts();
* }
*
- *
+ *
* @return A container for the information returned by Vault
- *
+ *
* @throws VaultException If any error occurs or unexpected response is received from Vault
*/
public MountResponse list() throws VaultException {
@@ -87,7 +87,7 @@ public MountResponse list() throws VaultException {
*
*
This method accepts a MountConfig parameter, containing optional settings for the mount
* creation operation. Example usage:
- *
+ *
*
A successful operation will return a 204 HTTP status. A VaultException will be thrown if
* mount point already exists, or if any other problem occurs. Example usage:
{@code
* final VaultConfig config = new VaultConfig.address(...).token(...).build();
* final Vault vault = new Vault(config);
- *
+ *
* final MountPayload payload = new MountPayload()
* .defaultLeaseTtl(TimeToLive.of(86400, TimeUnit.SECONDS))
* .maxLeaseTtl(TimeToLive.of(86400, TimeUnit.SECONDS))
* .description("description for pki engine");
- *
+ *
* final MountResponse response = vault.mounts().enable("pki/mount/point/path", MountType.PKI, payload);
- *
+ *
* assertEquals(204, response.getRestResponse().getStatus();
* }
*
@@ -110,9 +110,9 @@ public MountResponse list() throws VaultException {
* @param path The path to enable secret engine on.
* @param type The type of secret engine to enable.
* @param payload The MountPayload instance to use to create secret engine.
- *
+ *
* @return A container for the information returned by Vault
- *
+ *
* @throws VaultException If any error occurs or unexpected response is received from Vault
*/
public MountResponse enable(final String path, final MountType type, final MountPayload payload) throws VaultException {
@@ -179,17 +179,17 @@ public MountResponse enable(final String path, final MountType type, final Mount
*
{@code
* final VaultConfig config = new VaultConfig.address(...).token(...).build();
* final Vault vault = new Vault(config);
- *
+ *
* final MountResponse response = vault.mounts().disable("pki/mount/point/path");
- *
+ *
* assertEquals(204, response.getRestResponse().getStatus();
* }
*
*
* @param path The path to disable secret engine on.
- *
+ *
* @return A container for the information returned by Vault
- *
+ *
* @throws VaultException If any error occurs or unexpected response is received from Vault
*/
public MountResponse disable(final String path) throws VaultException {
@@ -245,7 +245,7 @@ public MountResponse disable(final String path) throws VaultException {
*
{@code
* final VaultConfig config = new VaultConfig.address(...).token(...).build();
* final Vault vault = new Vault(config);
- *
+ *
* final MountResponse response = vault.mounts().read("pki/mount/point/path");
* final Mount mount = response.getMount();
* final MountConfig mountConfig = mount.getConfig();
@@ -253,9 +253,9 @@ public MountResponse disable(final String path) throws VaultException {
*
*
* @param path The path to read secret engine's configuration from.
- *
+ *
* @return A container for the information returned by Vault
- *
+ *
* @throws VaultException If any error occurs or unexpected response is received from Vault
*/
public MountResponse read(final String path) throws VaultException {
@@ -306,7 +306,7 @@ public MountResponse read(final String path) throws VaultException {
*
*
This the method accepts a MountConfig parameter, containing optional settings for the mount
* tune operation. Example usage:
- *
+ *
*
A successful operation will return a 204 HTTP status. A VaultException will be thrown if
* the mount point not exist, or if any other problem occurs. Example usage:
{@code
* final VaultConfig config = new VaultConfig.address(...).token(...).build();
* final Vault vault = new Vault(config);
- *
+ *
* final MountPayload payload = new MountPayload()
* .defaultLeaseTtl(TimeToLive.of(12, TimeUnit.HOURS))
* .maxLeaseTtl(TimeToLive.of(12, TimeUnit.HOURS))
* .description("description of pki");
- *
+ *
* final MountResponse response = vault.mounts().tune("pki/mount/point/path", configs);
- *
+ *
* assertEquals(204, response.getRestResponse().getStatus();
* }
*
*
* @param path The path to tune secret engine's configuration on.
* @param payload The MountPayload instance to use to tune secret engine.
- *
+ *
* @return A container for the information returned by Vault
- *
+ *
* @throws VaultException If any error occurs or unexpected response is received from Vault
*/
public MountResponse tune(final String path, final MountPayload payload) throws VaultException {
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/TimeToLive.java b/src/main/java/com/bettercloud/vault/api/mounts/TimeToLive.java
index 0901b780..83f94914 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/TimeToLive.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/TimeToLive.java
@@ -6,15 +6,15 @@
*
A container for Time To Live information sent to mounts endpoints on the Secret Engine backend as REST payload.
* This class is meant for use with a static TimeToLive.of(int, TimeUnit) method pattern style. Example
* usage:
- *
+ *
*
*
{@code
* TimeToLive.of(1, TimeUnit.HOURS);
* }
*
- *
+ *
*
Note that the only accepted TimeUnit which Vault backend understands are:
- *
+ *
*
*
TimeUnit.SECONDS
*
TimeUnit.MINUTES
diff --git a/src/main/java/com/bettercloud/vault/json/JsonObject.java b/src/main/java/com/bettercloud/vault/json/JsonObject.java
index 3937dfda..58ee44b7 100644
--- a/src/main/java/com/bettercloud/vault/json/JsonObject.java
+++ b/src/main/java/com/bettercloud/vault/json/JsonObject.java
@@ -600,7 +600,7 @@ public Integer getInt(String name) {
JsonValue value = get(name);
return value != null ? value.asInt() : null;
}
-
+
/**
* Returns the int value of the member with the specified name in this object. If
* this object does not contain a member with this name, the given default value is returned. If
@@ -636,7 +636,7 @@ public Long getLong(String name) {
JsonValue value = get(name);
return value != null ? value.asLong() : null;
}
-
+
/**
* Returns the long value of the member with the specified name in this object. If
* this object does not contain a member with this name, the given default value is returned. If
@@ -672,7 +672,7 @@ public Float getFloat(String name) {
JsonValue value = get(name);
return value != null ? value.asFloat() : null;
}
-
+
/**
* Returns the float value of the member with the specified name in this object. If
* this object does not contain a member with this name, the given default value is returned. If
@@ -708,7 +708,7 @@ public Double getDouble(String name) {
JsonValue value = get(name);
return value != null ? value.asDouble() : null;
}
-
+
/**
* Returns the double value of the member with the specified name in this object. If
* this object does not contain a member with this name, the given default value is returned. If
@@ -744,7 +744,7 @@ public Boolean getBoolean(String name) {
JsonValue value = get(name);
return value != null ? value.asBoolean() : null;
}
-
+
/**
* Returns the boolean value of the member with the specified name in this object. If
* this object does not contain a member with this name, the given default value is returned. If
@@ -779,7 +779,7 @@ public String getString(String name) {
JsonValue value = get(name);
return value != null ? value.asString() : null;
}
-
+
/**
* Returns the String value of the member with the specified name in this object. If
* this object does not contain a member with this name, the given default value is returned. If
From 1a464c9b17a94f012e5663b4863e2646c664b97c Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 00:51:44 +0200
Subject: [PATCH 15/34] fix final newline
---
.gitattributes | 1 +
src/main/java/module-info.java | 2 +-
src/test/java/com/bettercloud/vault/VaultTests.java | 2 +-
3 files changed, 3 insertions(+), 2 deletions(-)
create mode 100644 .gitattributes
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..6313b56c
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+* text=auto eol=lf
diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java
index f38506b0..5c93ea9e 100644
--- a/src/main/java/module-info.java
+++ b/src/main/java/module-info.java
@@ -5,4 +5,4 @@
exports com.bettercloud.vault.json;
exports com.bettercloud.vault.response;
exports com.bettercloud.vault.rest;
-}
\ No newline at end of file
+}
diff --git a/src/test/java/com/bettercloud/vault/VaultTests.java b/src/test/java/com/bettercloud/vault/VaultTests.java
index 502fe86b..5b4c4354 100644
--- a/src/test/java/com/bettercloud/vault/VaultTests.java
+++ b/src/test/java/com/bettercloud/vault/VaultTests.java
@@ -112,4 +112,4 @@ public void testConfigBuiler_WithInvalidRequestAsNonError() throws Exception {
Assert.assertEquals(403, response.getRestResponse().getStatus());
Assert.assertEquals(0, response.getRetries());
}
-}
\ No newline at end of file
+}
From 8676208c9360d9c57c11b431e970c7fd2627b287 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 04:35:40 +0200
Subject: [PATCH 16/34] add GitHub Action CI
---
.github/workflows/gradle.yml | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
create mode 100644 .github/workflows/gradle.yml
diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml
new file mode 100644
index 00000000..a3db770d
--- /dev/null
+++ b/.github/workflows/gradle.yml
@@ -0,0 +1,25 @@
+name: CI
+
+on: [push, pull_request]
+
+jobs:
+ build:
+ name: Build on JDK ${{ matrix.java }} and ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ java: [9, 11, 12]
+ os: [ubuntu-latest, windows-latest]
+ include:
+ # TODO(casz) remove once https://github.com/testcontainers/testcontainers-java/pull/1780 is available
+ - os: 'ubuntu-latest'
+ tasks: 'integrationTest'
+
+ steps:
+ - uses: actions/checkout@v1
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v1
+ with:
+ java-version: ${{ matrix.java }}
+ - name: Build with Gradle
+ run: ./gradlew build ${{ matrix.tasks }}
From 67dddfc8e4fcbd3e655d7aaacc968b834968a4fe Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:25:06 +0200
Subject: [PATCH 17/34] add Travis CI
can be removed once GitHub Action CI is generally available
---
.travis.yml | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
create mode 100644 .travis.yml
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 00000000..ffa2eb62
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,27 @@
+language: java
+
+dist: xenial
+
+services:
+ - docker
+
+before_cache:
+ - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
+ - rm -fr $HOME/.gradle/caches/*/plugin-resolution/
+
+cache:
+ directories:
+ - $HOME/.gradle/caches/
+ - $HOME/.gradle/wrapper/
+
+matrix:
+ include:
+ - jdk: openjdk12
+ - jdk: openjdk11
+ - jdk: openjdk9
+
+script:
+ - ./gradlew build integrationTest -s
+
+notifications:
+ email: false
From 3e0eeda62b20633c1d1ba806166740d457860d09 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 04:40:46 +0200
Subject: [PATCH 18/34] Skip testcontainers if Docker is not available
---
.../java/com/bettercloud/vault/util/DbContainer.java | 11 ++++++++++-
.../com/bettercloud/vault/util/TestConstants.java | 2 ++
.../bettercloud/vault/util/VaultAgentContainer.java | 10 +++++++++-
.../com/bettercloud/vault/util/VaultContainer.java | 12 +++++++++++-
4 files changed, 32 insertions(+), 3 deletions(-)
diff --git a/src/test-integration/java/com/bettercloud/vault/util/DbContainer.java b/src/test-integration/java/com/bettercloud/vault/util/DbContainer.java
index 6e2954b2..365c6293 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/DbContainer.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/DbContainer.java
@@ -5,8 +5,12 @@
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.output.Slf4jLogConsumer;
import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy;
+import org.testcontainers.lifecycle.TestDescription;
+import org.testcontainers.lifecycle.TestLifecycleAware;
-public class DbContainer extends GenericContainer implements TestConstants {
+import static org.junit.Assume.assumeTrue;
+
+public class DbContainer extends GenericContainer implements TestConstants, TestLifecycleAware {
private static final Logger LOGGER = LoggerFactory.getLogger(DbContainer.class);
@@ -22,4 +26,9 @@ public DbContainer() {
.withLogConsumer(new Slf4jLogConsumer(LOGGER))
.waitingFor(new HostPortWaitStrategy());
}
+
+ @Override
+ public void beforeTest(TestDescription description) {
+ assumeTrue(DOCKER_AVAILABLE);
+ }
}
diff --git a/src/test-integration/java/com/bettercloud/vault/util/TestConstants.java b/src/test-integration/java/com/bettercloud/vault/util/TestConstants.java
index 9f40112f..1c34a29c 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/TestConstants.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/TestConstants.java
@@ -1,6 +1,7 @@
package com.bettercloud.vault.util;
import org.testcontainers.containers.Network;
+import org.testcontainers.utility.TestEnvironment;
import java.io.File;
@@ -40,4 +41,5 @@ interface TestConstants {
String APPROLE_POLICY_FILE = "/home/vault/approlePolicy.hcl";
Network CONTAINER_NETWORK = Network.newNetwork();
+ boolean DOCKER_AVAILABLE = TestEnvironment.dockerApiAtLeast("1.10");
}
diff --git a/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java b/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
index 43cb978d..be0ba9f7 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java
@@ -13,10 +13,13 @@
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.output.Slf4jLogConsumer;
import org.testcontainers.containers.wait.strategy.Wait;
+import org.testcontainers.lifecycle.TestDescription;
+import org.testcontainers.lifecycle.TestLifecycleAware;
+import static org.junit.Assume.assumeTrue;
import static org.testcontainers.utility.MountableFile.forHostPath;
-public class VaultAgentContainer extends GenericContainer implements TestConstants {
+public class VaultAgentContainer extends GenericContainer implements TestConstants, TestLifecycleAware {
private static final Logger LOGGER = LoggerFactory.getLogger(VaultAgentContainer.class);
@@ -69,4 +72,9 @@ public Vault getVault() throws VaultException {
public String getAddress() {
return String.format("http://%s:%d", getContainerIpAddress(), getMappedPort(8100));
}
+
+ @Override
+ public void beforeTest(TestDescription description) {
+ assumeTrue(DOCKER_AVAILABLE);
+ }
}
diff --git a/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java b/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
index 2c31723b..15595e68 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java
@@ -14,15 +14,20 @@
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.output.Slf4jLogConsumer;
import org.testcontainers.containers.wait.strategy.HttpWaitStrategy;
+import org.testcontainers.lifecycle.TestDescription;
+import org.testcontainers.lifecycle.TestLifecycleAware;
+import org.testcontainers.utility.TestEnvironment;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
+import static org.junit.Assume.assumeTrue;
+
/**
* Sets up and exposes utilities for dealing with a Docker-hosted instance of Vault, for integration tests.
*/
-public class VaultContainer extends GenericContainer implements TestConstants {
+public class VaultContainer extends GenericContainer implements TestConstants, TestLifecycleAware {
private static final Logger LOGGER = LoggerFactory.getLogger(VaultContainer.class);
@@ -360,4 +365,9 @@ private Container.ExecResult runCommand(final String... command) throws IOExcept
}
return result;
}
+
+ @Override
+ public void beforeTest(TestDescription description) {
+ assumeTrue(DOCKER_AVAILABLE);
+ }
}
From ad34a136ba0353641645f02c07614d9ac28e5d99 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 04:18:14 +0200
Subject: [PATCH 19/34] Use UTF-8 Charset constant
---
src/main/java/com/bettercloud/vault/api/mounts/Mounts.java | 6 ++++--
src/main/java/com/bettercloud/vault/rest/Rest.java | 4 +++-
src/test/java/com/bettercloud/vault/VaultConfigTests.java | 1 +
3 files changed, 8 insertions(+), 3 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java b/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java
index 73b724ea..63798c49 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java
@@ -6,6 +6,8 @@
import com.bettercloud.vault.rest.Rest;
import com.bettercloud.vault.rest.RestResponse;
+import java.nio.charset.StandardCharsets;
+
/**
*
The implementing class for operations on Vault's /v1/sys/mounts/* REST endpoints.
*
@@ -133,7 +135,7 @@ public MountResponse enable(final String path, final MountType type, final Mount
final RestResponse restResponse = new Rest()//NOPMD
.url(String.format("%s/v1/sys/mounts/%s", config.getAddress(), path))
.optionalHeader("X-Vault-Token", config.getToken())
- .body(requestJson.getBytes("UTF-8"))
+ .body(requestJson.getBytes(StandardCharsets.UTF_8))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
@@ -347,7 +349,7 @@ public MountResponse tune(final String path, final MountPayload payload) throws
final RestResponse restResponse = new Rest()//NOPMD
.url(String.format("%s/v1/sys/mounts/%s/tune", config.getAddress(), path))
.optionalHeader("X-Vault-Token", config.getToken())
- .body(requestJson.getBytes("UTF-8"))
+ .body(requestJson.getBytes(StandardCharsets.UTF_8))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
diff --git a/src/main/java/com/bettercloud/vault/rest/Rest.java b/src/main/java/com/bettercloud/vault/rest/Rest.java
index f6be0668..d1aee47c 100644
--- a/src/main/java/com/bettercloud/vault/rest/Rest.java
+++ b/src/main/java/com/bettercloud/vault/rest/Rest.java
@@ -13,6 +13,7 @@
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
@@ -145,6 +146,7 @@ public Rest body(final byte[] body) {
* @return This object, with a parameter added, ready for other builder-pattern config methods or an HTTP verb method
* @throws RestException If any error occurs, or unexpected response received from Vault
*/
+ @SuppressWarnings("CharsetObjectCanBeUsed") // Using Charset constant requires Java and above
public Rest parameter(final String name, final String value) throws RestException {
try {
this.parameters.put(URLEncoder.encode(name, "UTF-8"), URLEncoder.encode(value, "UTF-8"));
@@ -397,7 +399,7 @@ private RestResponse postOrPutImpl(final boolean doPost) throws RestException {
} else if (!parameters.isEmpty()) {
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
final OutputStream outputStream = connection.getOutputStream();
- outputStream.write(parametersToQueryString().getBytes("UTF-8"));
+ outputStream.write(parametersToQueryString().getBytes(StandardCharsets.UTF_8));
outputStream.close();
}
diff --git a/src/test/java/com/bettercloud/vault/VaultConfigTests.java b/src/test/java/com/bettercloud/vault/VaultConfigTests.java
index 230445e2..423276e1 100644
--- a/src/test/java/com/bettercloud/vault/VaultConfigTests.java
+++ b/src/test/java/com/bettercloud/vault/VaultConfigTests.java
@@ -217,6 +217,7 @@ public void testConfigBuilder_FailToLoad() throws VaultException {
new VaultConfig().build();
}
+ @SuppressWarnings("CharsetObjectCanBeUsed") // Requires Java 10 and above
@Test
public void testConfigBuilder_LoadTokenFromHomedir() throws IOException, VaultException {
final String mockHomeDirectory = System.getProperty("java.io.tmpdir") + File.separatorChar + UUID.randomUUID().toString();
From 735815b85d3b4fc66c4dd1b1e239ff1ed9b2f7f4 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:36:08 +0200
Subject: [PATCH 20/34] remove redundant private modifier on enum
---
src/main/java/com/bettercloud/vault/api/mounts/MountType.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountType.java b/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
index 3352db63..a5e570e9 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
@@ -36,7 +36,7 @@ public enum MountType {
private final String value;
- private MountType(final String value) {
+ MountType(final String value) {
this.value = value;
}
From 66182c2b52225bf6692cbd76290d6756746f352a Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:38:23 +0200
Subject: [PATCH 21/34] pointless comparison of boolean
---
src/main/java/com/bettercloud/vault/SslConfig.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/SslConfig.java b/src/main/java/com/bettercloud/vault/SslConfig.java
index 64de9975..278d1fa6 100644
--- a/src/main/java/com/bettercloud/vault/SslConfig.java
+++ b/src/main/java/com/bettercloud/vault/SslConfig.java
@@ -450,7 +450,7 @@ public SslConfig build() throws VaultException {
} else {
this.verify = true;
}
- if (this.verify == true && this.pemUTF8 == null && environmentLoader.loadVariable(VAULT_SSL_CERT) != null) {
+ if (this.verify && this.pemUTF8 == null && environmentLoader.loadVariable(VAULT_SSL_CERT) != null) {
final File pemFile = new File(environmentLoader.loadVariable(VAULT_SSL_CERT));
try (final InputStream input = new FileInputStream(pemFile)) {
this.pemUTF8 = inputStreamToUTF8(input);
@@ -487,7 +487,7 @@ protected String getPemUTF8() {
* @throws VaultException
*/
private void buildSsl() throws VaultException {
- if (verify == true) {
+ if (verify) {
if (keyStore != null || trustStore != null) {
this.sslContext = buildSslContextFromJks();
} else if (pemUTF8 != null || clientPemUTF8 != null || clientKeyPemUTF8 != null) {
From eafd359d633e4e9a8c0b624b9c86d19a2c409483 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:39:07 +0200
Subject: [PATCH 22/34] unnecessary null check before equals call
---
src/main/java/com/bettercloud/vault/api/Auth.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/api/Auth.java b/src/main/java/com/bettercloud/vault/api/Auth.java
index c5e955f5..1d8b756c 100644
--- a/src/main/java/com/bettercloud/vault/api/Auth.java
+++ b/src/main/java/com/bettercloud/vault/api/Auth.java
@@ -1228,7 +1228,7 @@ public LookupResponse lookupSelf(final String tokenAuthMount) throws VaultExcept
throw new VaultException("Vault responded with HTTP status code: " + restResponse.getStatus(), restResponse.getStatus());
}
final String mimeType = restResponse.getMimeType();
- if (mimeType == null || !"application/json".equals(mimeType)) {
+ if (!"application/json".equals(mimeType)) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new LookupResponse(restResponse, retryCount);
@@ -1291,7 +1291,7 @@ public LogicalResponse lookupWrap() throws VaultException {
restResponse.getStatus());
}
final String mimeType = restResponse.getMimeType();
- if (mimeType == null || !"application/json".equals(mimeType)) {
+ if (!"application/json".equals(mimeType)) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new LogicalResponse(restResponse, retryCount, Logical.logicalOperations.authentication);
From aaa52b2905a321be2195a2ae022fc815213da923 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:40:17 +0200
Subject: [PATCH 23/34] Simplify stream chains
---
.../java/com/bettercloud/vault/api/mounts/MountPayload.java | 4 ++--
src/main/java/com/bettercloud/vault/api/mounts/MountType.java | 3 +--
2 files changed, 3 insertions(+), 4 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java b/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
index 6ef41aa3..5cad3738 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
@@ -132,11 +132,11 @@ public JsonObject toTuneJson() {
jsonObject.addIfNotNull("description", this.description);
if (this.auditNonHmacRequestKeys != null && this.auditNonHmacRequestKeys.size() > 0) {
- jsonObject.addIfNotNull("audit_non_hmac_request_keys", this.auditNonHmacRequestKeys.stream().collect(Collectors.joining(",")));
+ jsonObject.addIfNotNull("audit_non_hmac_request_keys", String.join(",", this.auditNonHmacRequestKeys));
}
if (this.auditNonHmacResponseKeys != null && this.auditNonHmacResponseKeys.size() > 0) {
- jsonObject.addIfNotNull("audit_non_hmac_response_keys", this.auditNonHmacResponseKeys.stream().collect(Collectors.joining(",")));
+ jsonObject.addIfNotNull("audit_non_hmac_response_keys", String.join(",", this.auditNonHmacResponseKeys));
}
return jsonObject;
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountType.java b/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
index a5e570e9..6e434bb3 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountType.java
@@ -56,8 +56,7 @@ public static MountType of(final String value) {
return null;
}
- return Arrays.asList(MountType.values())
- .stream()
+ return Arrays.stream(MountType.values())
.filter(type -> type.value.equals(value))
.findFirst()
.orElse(null);
From a738b4ba1a2efaccd85a2562c6b5977eab4c7522 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:45:29 +0200
Subject: [PATCH 24/34] string concatenation used in a string builder :sweat:
---
src/main/java/com/bettercloud/vault/api/Auth.java | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/src/main/java/com/bettercloud/vault/api/Auth.java b/src/main/java/com/bettercloud/vault/api/Auth.java
index 1d8b756c..2f7a6417 100644
--- a/src/main/java/com/bettercloud/vault/api/Auth.java
+++ b/src/main/java/com/bettercloud/vault/api/Auth.java
@@ -252,7 +252,10 @@ public AuthResponse createToken(final TokenRequest tokenRequest, final String to
if (tokenRequest.numUses != null) jsonObject.add("num_uses", tokenRequest.numUses);
final String requestJson = jsonObject.toString();
- final StringBuilder urlBuilder = new StringBuilder(config.getAddress()).append("/v1/auth/" + mount + "/create");//NOPMD
+ final StringBuilder urlBuilder = new StringBuilder(config.getAddress())//NOPMD
+ .append("/v1/auth/")
+ .append(mount)
+ .append("/create");
if (tokenRequest.role != null) {
urlBuilder.append("/").append(tokenRequest.role);
}
From f0f49531819e522fdb9f8191f4865de52b0ff18a Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:46:26 +0200
Subject: [PATCH 25/34] string concatenation in a loop :sweat:
---
src/test/java/com/bettercloud/vault/SSLTests.java | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/test/java/com/bettercloud/vault/SSLTests.java b/src/test/java/com/bettercloud/vault/SSLTests.java
index 1ea4977e..553bc2fd 100644
--- a/src/test/java/com/bettercloud/vault/SSLTests.java
+++ b/src/test/java/com/bettercloud/vault/SSLTests.java
@@ -173,13 +173,13 @@ public void testSslPem_UTF8() throws Exception {
final BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/cert.pem")));
final StringBuilder builder = new StringBuilder();
- String utf8 = "";
+ StringBuilder utf8 = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
- utf8 += str + System.lineSeparator();//NOPMD
+ utf8.append(str).append(System.lineSeparator());//NOPMD
}
in.close();
- final String pemUTF8 = utf8;
+ final String pemUTF8 = utf8.toString();
final VaultConfig vaultConfig = new VaultConfig()
.address("https://127.0.0.1:9998")
From 87b6cbbbde2c626d38edbfa803f87296dc346832 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:55:52 +0200
Subject: [PATCH 26/34] condition is covered by instanceOf
---
src/main/java/com/bettercloud/vault/rest/Rest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/com/bettercloud/vault/rest/Rest.java b/src/main/java/com/bettercloud/vault/rest/Rest.java
index d1aee47c..e2aa1930 100644
--- a/src/main/java/com/bettercloud/vault/rest/Rest.java
+++ b/src/main/java/com/bettercloud/vault/rest/Rest.java
@@ -462,7 +462,7 @@ private URLConnection initURLConnection(final String urlString, final String met
} catch (Exception e) {
throw new RestException(e);
} finally {
- if (connection != null && connection instanceof HttpURLConnection) {
+ if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).disconnect();
}
}
From ff5f5b64a09a08982593e0b3102bcc19b6a4e7fc Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 03:56:54 +0200
Subject: [PATCH 27/34] unnecessary initialization of `StringBuilder`
---
src/main/java/com/bettercloud/vault/SslConfig.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/com/bettercloud/vault/SslConfig.java b/src/main/java/com/bettercloud/vault/SslConfig.java
index 278d1fa6..41d47cac 100644
--- a/src/main/java/com/bettercloud/vault/SslConfig.java
+++ b/src/main/java/com/bettercloud/vault/SslConfig.java
@@ -625,7 +625,7 @@ private KeyStore inputStreamToKeyStore(final InputStream inputStream, final Stri
*/
private static String inputStreamToUTF8(final InputStream input) throws IOException {
final BufferedReader in = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
- final StringBuilder utf8 = new StringBuilder("");
+ final StringBuilder utf8 = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
// String concatenation is less efficient, but for some reason the line-breaks (which are necessary
From 764219bed3187a6f69b0b0e260b1bd95c1c8417b Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 04:00:42 +0200
Subject: [PATCH 28/34] simplify clone of ArrayList
---
.../com/bettercloud/vault/api/mounts/MountConfig.java | 8 ++------
.../com/bettercloud/vault/api/mounts/MountPayload.java | 8 ++------
.../java/com/bettercloud/vault/api/pki/RoleOptions.java | 4 +---
3 files changed, 5 insertions(+), 15 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountConfig.java b/src/main/java/com/bettercloud/vault/api/mounts/MountConfig.java
index 545b96f1..4715dd95 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountConfig.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountConfig.java
@@ -76,9 +76,7 @@ public List getAuditNonHmacRequestKeys() {
if (auditNonHmacRequestKeys == null) {
return null;
} else {
- final List clone = new ArrayList<>();
- clone.addAll(auditNonHmacRequestKeys);
- return clone;
+ return new ArrayList<>(auditNonHmacRequestKeys);
}
}
@@ -86,9 +84,7 @@ public List getAuditNonHmacResponseKeys() {
if (auditNonHmacResponseKeys == null) {
return null;
} else {
- final List clone = new ArrayList<>();
- clone.addAll(auditNonHmacResponseKeys);
- return clone;
+ return new ArrayList<>(auditNonHmacResponseKeys);
}
}
diff --git a/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java b/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
index 5cad3738..f67dc1e6 100644
--- a/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
+++ b/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java
@@ -89,9 +89,7 @@ public List getAuditNonHmacRequestKeys() {
if (auditNonHmacRequestKeys == null) {
return null;
} else {
- final List clone = new ArrayList<>();
- clone.addAll(auditNonHmacRequestKeys);
- return clone;
+ return new ArrayList<>(auditNonHmacRequestKeys);
}
}
@@ -99,9 +97,7 @@ public List getAuditNonHmacResponseKeys() {
if (auditNonHmacResponseKeys == null) {
return null;
} else {
- final List clone = new ArrayList<>();
- clone.addAll(auditNonHmacResponseKeys);
- return clone;
+ return new ArrayList<>(auditNonHmacResponseKeys);
}
}
diff --git a/src/main/java/com/bettercloud/vault/api/pki/RoleOptions.java b/src/main/java/com/bettercloud/vault/api/pki/RoleOptions.java
index 10a83764..1a731d1f 100644
--- a/src/main/java/com/bettercloud/vault/api/pki/RoleOptions.java
+++ b/src/main/java/com/bettercloud/vault/api/pki/RoleOptions.java
@@ -221,9 +221,7 @@ public List getAllowedDomains() {
if (allowedDomains == null) {
return null;
} else {
- final List clone = new ArrayList<>();
- clone.addAll(allowedDomains);
- return clone;
+ return new ArrayList<>(allowedDomains);
}
}
From 7f3756fd3d1bd462fe274c597bc0b438c8d6fec3 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 04:03:38 +0200
Subject: [PATCH 29/34] simplify assertNull
---
.../java/com/bettercloud/vault/api/pki/RoleOptionsTests.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/test/java/com/bettercloud/vault/api/pki/RoleOptionsTests.java b/src/test/java/com/bettercloud/vault/api/pki/RoleOptionsTests.java
index 44560bfb..02ab478a 100644
--- a/src/test/java/com/bettercloud/vault/api/pki/RoleOptionsTests.java
+++ b/src/test/java/com/bettercloud/vault/api/pki/RoleOptionsTests.java
@@ -12,7 +12,7 @@ public void RoleOptionsTests() {
RoleOptions roleOptions = new RoleOptions();
Assert.assertNotNull(roleOptions);
- Assert.assertEquals(roleOptions.getAllowedDomains(), null);
+ Assert.assertNull(roleOptions.getAllowedDomains());
roleOptions.allowAnyName(true);
roleOptions.allowBareDomains(true);
From 50230cd9763d9042e977be656d3a61a3e606e47e Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 04:31:43 +0200
Subject: [PATCH 30/34] Use `Integer.valueOf` instead
---
.../java/com/bettercloud/vault/api/MountsTests.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/test-integration/java/com/bettercloud/vault/api/MountsTests.java b/src/test-integration/java/com/bettercloud/vault/api/MountsTests.java
index 29eccc2e..c036b458 100644
--- a/src/test-integration/java/com/bettercloud/vault/api/MountsTests.java
+++ b/src/test-integration/java/com/bettercloud/vault/api/MountsTests.java
@@ -144,8 +144,8 @@ public void testRead() throws VaultException {
assertEquals(200, response.getRestResponse().getStatus());
- assertEquals(new Integer(21600), config.getDefaultLeaseTtl());
- assertEquals(new Integer(21600), config.getMaxLeaseTtl());
+ assertEquals(Integer.valueOf(21600), config.getDefaultLeaseTtl());
+ assertEquals(Integer.valueOf(21600), config.getMaxLeaseTtl());
}
@Test
@@ -180,8 +180,8 @@ public void testTune() throws VaultException {
final Mount mount = response.getMount();
final MountConfig config = mount.getConfig();
- assertEquals(new Integer(43200), config.getDefaultLeaseTtl());
- assertEquals(new Integer(43200), config.getMaxLeaseTtl());
+ assertEquals(Integer.valueOf(43200), config.getDefaultLeaseTtl());
+ assertEquals(Integer.valueOf(43200), config.getMaxLeaseTtl());
}
@Test
From e7cae4a3c9cd47c4b3421c062f309921fa67e9b1 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 05:07:44 +0200
Subject: [PATCH 31/34] info log level for CI
---
.github/workflows/gradle.yml | 2 +-
.travis.yml | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml
index a3db770d..5f78b4f8 100644
--- a/.github/workflows/gradle.yml
+++ b/.github/workflows/gradle.yml
@@ -22,4 +22,4 @@ jobs:
with:
java-version: ${{ matrix.java }}
- name: Build with Gradle
- run: ./gradlew build ${{ matrix.tasks }}
+ run: ./gradlew build ${{ matrix.tasks }} -s --info
diff --git a/.travis.yml b/.travis.yml
index ffa2eb62..1c5058e3 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -21,7 +21,7 @@ matrix:
- jdk: openjdk9
script:
- - ./gradlew build integrationTest -s
+ - ./gradlew build integrationTest -s --info
notifications:
email: false
From 31289129d620166b6457987aac181ba511071ea9 Mon Sep 17 00:00:00 2001
From: Joseph Petersen
Date: Sun, 25 Aug 2019 14:18:37 +0200
Subject: [PATCH 32/34] use in-memory keystore to avoid file locks
---
.../vault/api/AuthBackendCertTests.java | 29 ++-
.../com/bettercloud/vault/util/SSLUtils.java | 219 +++++++++++-------
.../bettercloud/vault/util/TestConstants.java | 5 +-
.../vault/util/VaultContainer.java | 5 +-
4 files changed, 154 insertions(+), 104 deletions(-)
diff --git a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendCertTests.java b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendCertTests.java
index 671e503d..8eb37c86 100644
--- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendCertTests.java
+++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendCertTests.java
@@ -6,20 +6,16 @@
import com.bettercloud.vault.VaultException;
import com.bettercloud.vault.util.SSLUtils;
import com.bettercloud.vault.util.VaultContainer;
-import org.bouncycastle.operator.OperatorCreationException;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
-import java.security.InvalidKeyException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.SignatureException;
-import java.security.cert.CertificateException;
+import java.security.KeyStore;
+import java.util.HashMap;
+import static com.bettercloud.vault.util.TestConstants.PASSWORD;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
@@ -34,14 +30,15 @@ public class AuthBackendCertTests {
@ClassRule
public static final VaultContainer container = new VaultContainer();
+ private static HashMap clientCertAndKey;
+ private static String cert;
@BeforeClass
- public static void setupClass() throws IOException, InterruptedException, CertificateException, SignatureException,
- NoSuchAlgorithmException, KeyStoreException, OperatorCreationException, NoSuchProviderException,
- InvalidKeyException {
+ public static void setupClass() throws IOException, InterruptedException {
+ clientCertAndKey = SSLUtils.createClientCertAndKey();
+ cert = (String) clientCertAndKey.get("cert");
container.initAndUnsealVault();
- SSLUtils.createClientCertAndKey();
- container.setupBackendCert();
+ container.setupBackendCert(cert);
}
@Test
@@ -53,8 +50,8 @@ public void testLoginByCert_usingJksConfig() throws VaultException {
.readTimeout(30)
.sslConfig(
new SslConfig()
- .keyStoreFile(new File(VaultContainer.CLIENT_KEYSTORE), "password")
- .trustStoreFile(new File(VaultContainer.CLIENT_TRUSTSTORE))
+ .keyStore((KeyStore) clientCertAndKey.get("clientKeystore"), PASSWORD)
+ .trustStore((KeyStore) clientCertAndKey.get("clientTrustStore"))
.build()
)
.build();
@@ -76,8 +73,8 @@ public void testLoginByCert_usingPemConfig() throws VaultException {
.sslConfig(
new SslConfig()
.pemFile(new File(VaultContainer.CERT_PEMFILE))
- .clientPemFile(new File(VaultContainer.CLIENT_CERT_PEMFILE))
- .clientKeyPemFile(new File(VaultContainer.CLIENT_PRIVATE_KEY_PEMFILE))
+ .clientPemUTF8(cert)
+ .clientKeyPemUTF8((String) clientCertAndKey.get("privateKey"))
.build()
)
.build();
diff --git a/src/test-integration/java/com/bettercloud/vault/util/SSLUtils.java b/src/test-integration/java/com/bettercloud/vault/util/SSLUtils.java
index a60bf786..58b5e669 100644
--- a/src/test-integration/java/com/bettercloud/vault/util/SSLUtils.java
+++ b/src/test-integration/java/com/bettercloud/vault/util/SSLUtils.java
@@ -6,6 +6,7 @@
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
+import org.bouncycastle.cert.CertIOException;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
@@ -27,8 +28,6 @@
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayOutputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
@@ -51,6 +50,7 @@
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Date;
+import java.util.HashMap;
/**
* Static utility methods for generating client-side SSL certs and keys, for tests that use Vault's TLS Certificate
@@ -67,105 +67,153 @@ private SSLUtils() {
*
*
Also constructs a JKS keystore, with a client certificate to use for authentication with Vault's TLS
* Certificate auth backend. Stores this cert as a PEM file as well, so that can be registered with Vault
- * as a recognized certificate in {@link VaultContainer#setupBackendCert()}.
+ * as a recognized certificate in {@link VaultContainer#setupBackendCert(String)}.
*
*
This method must be called AFTER {@link VaultContainer#initAndUnsealVault()}, and BEFORE
- * {@link VaultContainer#setupBackendCert()}.
This class is used for inspecting the request inputs to ensure they were properly
diff --git a/src/test/java/com/bettercloud/vault/vault/mock/MockVault.java b/src/test/java/com/bettercloud/vault/vault/mock/MockVault.java
index 7df77a40..ea395137 100644
--- a/src/test/java/com/bettercloud/vault/vault/mock/MockVault.java
+++ b/src/test/java/com/bettercloud/vault/vault/mock/MockVault.java
@@ -1,19 +1,17 @@
package com.bettercloud.vault.vault.mock;
-import static com.bettercloud.vault.vault.VaultTestUtils.readRequestBody;
-import static com.bettercloud.vault.vault.VaultTestUtils.readRequestHeaders;
-
+import com.bettercloud.vault.json.JsonObject;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
-import com.bettercloud.vault.json.JsonObject;
+import static com.bettercloud.vault.vault.VaultTestUtils.readRequestBody;
+import static com.bettercloud.vault.vault.VaultTestUtils.readRequestHeaders;
/**
*
This class is used to mock out a Vault server in unit tests involving retry logic. As it extends Jetty's
diff --git a/src/test/java/com/bettercloud/vault/vault/mock/OpenTimeoutsMockVault.java b/src/test/java/com/bettercloud/vault/vault/mock/OpenTimeoutsMockVault.java
index 9e0a1a55..8b9e0f19 100644
--- a/src/test/java/com/bettercloud/vault/vault/mock/OpenTimeoutsMockVault.java
+++ b/src/test/java/com/bettercloud/vault/vault/mock/OpenTimeoutsMockVault.java
@@ -1,11 +1,10 @@
package com.bettercloud.vault.vault.mock;
-import org.eclipse.jetty.server.Request;
-
+import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
+import org.eclipse.jetty.server.Request;
/**
*
This class is used to mock out a Vault server in unit tests involving open timeouts (i.e. delays before an
diff --git a/src/test/java/com/bettercloud/vault/vault/mock/ReadTimeoutsMockVault.java b/src/test/java/com/bettercloud/vault/vault/mock/ReadTimeoutsMockVault.java
index f408cdb0..2da9f3d0 100644
--- a/src/test/java/com/bettercloud/vault/vault/mock/ReadTimeoutsMockVault.java
+++ b/src/test/java/com/bettercloud/vault/vault/mock/ReadTimeoutsMockVault.java
@@ -1,11 +1,10 @@
package com.bettercloud.vault.vault.mock;
-import org.eclipse.jetty.server.Request;
-
+import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
+import org.eclipse.jetty.server.Request;
/**
*
This class is used to mock out a Vault server in unit tests involving read timeouts (i.e. delays between an
diff --git a/src/test/java/com/bettercloud/vault/vault/mock/RetriesMockVault.java b/src/test/java/com/bettercloud/vault/vault/mock/RetriesMockVault.java
index 54bc3d13..356116ec 100644
--- a/src/test/java/com/bettercloud/vault/vault/mock/RetriesMockVault.java
+++ b/src/test/java/com/bettercloud/vault/vault/mock/RetriesMockVault.java
@@ -1,11 +1,9 @@
package com.bettercloud.vault.vault.mock;
-import org.eclipse.jetty.server.Request;
-
-import javax.servlet.ServletException;
+import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
+import org.eclipse.jetty.server.Request;
/**
*
This class is used to mock out a Vault server in unit tests involving retry logic. As it extends Jetty's
From 3231da3f3739cbbb3cfabecd3a04eeecca4bcfe3 Mon Sep 17 00:00:00 2001
From: Barry Klawans
Date: Mon, 26 Aug 2019 07:50:04 +0200
Subject: [PATCH 34/34] Changed the list() methods to return a LogicalResult so
the status code can be checked. Added new method getListData() to
LogicalResult
---
.../com/bettercloud/vault/api/Logical.java | 19 +++-------------
.../vault/response/LogicalResponse.java | 22 +++++++++++++++++++
.../bettercloud/vault/api/LogicalTests.java | 16 +++++++-------
3 files changed, 33 insertions(+), 24 deletions(-)
diff --git a/src/main/java/com/bettercloud/vault/api/Logical.java b/src/main/java/com/bettercloud/vault/api/Logical.java
index c0566a01..cc36b8c3 100644
--- a/src/main/java/com/bettercloud/vault/api/Logical.java
+++ b/src/main/java/com/bettercloud/vault/api/Logical.java
@@ -305,13 +305,13 @@ private LogicalResponse write(final String path, final Map nameV
* @return A list of keys corresponding to key/value pairs at a given Vault path, or an empty list if there are none
* @throws VaultException If any errors occur, or unexpected response received from Vault
*/
- public List list(final String path) throws VaultException {
+ public LogicalResponse list(final String path) throws VaultException {
if (engineVersionForSecretPath(path).equals(2)) {
return list(path, logicalOperations.listV2);
} else return list(path, logicalOperations.listV1);
}
- private List list(final String path, final logicalOperations operation) throws VaultException {
+ private LogicalResponse list(final String path, final logicalOperations operation) throws VaultException {
LogicalResponse response = null;
try {
response = read(adjustPathForList(path, operation), true, operation);
@@ -321,20 +321,7 @@ private List list(final String path, final logicalOperations operation)
}
}
- final List returnValues = new ArrayList<>();
- if (
- response != null
- && response.getRestResponse().getStatus() != 404
- && response.getData() != null
- && response.getData().get("keys") != null
- ) {
-
- final JsonArray keys = Json.parse(response.getData().get("keys")).asArray();
- for (int index = 0; index < keys.size(); index++) {
- returnValues.add(keys.get(index).asString());
- }
- }
- return returnValues;
+ return response;
}
/**
diff --git a/src/main/java/com/bettercloud/vault/response/LogicalResponse.java b/src/main/java/com/bettercloud/vault/response/LogicalResponse.java
index 53e75874..93f3fb8d 100644
--- a/src/main/java/com/bettercloud/vault/response/LogicalResponse.java
+++ b/src/main/java/com/bettercloud/vault/response/LogicalResponse.java
@@ -2,11 +2,14 @@
import com.bettercloud.vault.api.Logical;
import com.bettercloud.vault.json.Json;
+import com.bettercloud.vault.json.JsonArray;
import com.bettercloud.vault.json.JsonObject;
import com.bettercloud.vault.json.JsonValue;
import com.bettercloud.vault.rest.RestResponse;
import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
/**
@@ -16,6 +19,7 @@
public class LogicalResponse extends VaultResponse {
private Map data = new HashMap<>();
+ private List listData = new ArrayList<>();
private JsonObject dataObject = null;
private String leaseId;
private Boolean renewable;
@@ -36,6 +40,10 @@ public Map getData() {
return data;
}
+ public List getListData() {
+ return listData;
+ }
+
public JsonObject getDataObject() {
return dataObject;
}
@@ -83,6 +91,20 @@ private void parseResponseData(final Logical.logicalOperations operation) {
data.put(member.getName(), jsonValue.toString());
}
}
+ // For list operations convert the array of keys to a list of values
+ if (operation.equals(Logical.logicalOperations.listV1) || operation.equals(Logical.logicalOperations.listV2)) {
+ if (
+ getRestResponse().getStatus() != 404
+ && data.get("keys") != null
+ ) {
+
+ final JsonArray keys = Json.parse(data.get("keys")).asArray();
+ for (int index = 0; index < keys.size(); index++) {
+ listData.add(keys.get(index).asString());
+ }
+ }
+
+ }
} catch (Exception ignored) {
}
}
diff --git a/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java b/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java
index 03d49f31..63f8b6ac 100644
--- a/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java
+++ b/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java
@@ -164,7 +164,7 @@ public void testList() throws VaultException {
testMap.put("value", "world");
vault.logical().write("secret/hello", testMap);
- final List keys = vault.logical().list("secret");
+ final List keys = vault.logical().list("secret").getListData();
assertTrue(keys.contains("hello"));
}
@@ -180,7 +180,7 @@ public void testListKVEngineV1() throws VaultException {
testMap.put("value", "world");
vault.logical().write("kv-v1/hello", testMap);
- final List keys = vault.logical().list("kv-v1");
+ final List keys = vault.logical().list("kv-v1").getListData();
assertTrue(keys.contains("hello"));
}
@@ -196,9 +196,9 @@ public void testDelete() throws VaultException {
testMap.put("value", "world");
vault.logical().write("secret/hello", testMap);
- assertTrue(vault.logical().list("secret").contains("hello"));
+ assertTrue(vault.logical().list("secret").getListData().contains("hello"));
vault.logical().delete("secret/hello");
- assertFalse(vault.logical().list("secret").contains("hello"));
+ assertFalse(vault.logical().list("secret").getListData().contains("hello"));
}
/**
@@ -213,9 +213,9 @@ public void testDeleteKVEngineV1() throws VaultException {
testMap.put("value", "world");
vault.logical().write("kv-v1/hello", testMap);
- assertTrue(vault.logical().list("kv-v1").contains("hello"));
+ assertTrue(vault.logical().list("kv-v1").getListData().contains("hello"));
vault.logical().delete("kv-v1/hello");
- assertFalse(vault.logical().list("kv-v1").contains("hello"));
+ assertFalse(vault.logical().list("kv-v1").getListData().contains("hello"));
}
/**
@@ -295,8 +295,8 @@ public void testDeleteExceptionMessageIncludesErrorsReturnedByVault() throws Vau
@Test
public void testListPermissionDeniedReturnedByVault() throws VaultException {
final Vault vault = container.getVault(NONROOT_TOKEN);
- List list = vault.logical().list("secret/null");
- assertEquals(list.size(), 0);
+ LogicalResponse response = vault.logical().list("secret/null");
+ assertEquals(404, response.getRestResponse().getStatus());
}
/**