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:

* @@ -95,14 +95,14 @@ public MountResponse list() throws VaultException { *
{@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:

* @@ -314,23 +314,23 @@ public MountResponse read(final String path) throws VaultException { *
{@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()}.

    + * {@link VaultContainer#setupBackendCert(String)}.

    * - * @throws KeyStoreException - * @throws IOException - * @throws CertificateException - * @throws NoSuchAlgorithmException + * @throws IOException When certificate was not created + * @return */ - public static void createClientCertAndKey() throws KeyStoreException, IOException, CertificateException, - NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, - OperatorCreationException { + public static HashMap createClientCertAndKey() throws IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - final FileReader fileReader = new FileReader(CERT_PEMFILE); - final PEMParser pemParser = new PEMParser(fileReader); - final X509CertificateHolder certificateHolder = (X509CertificateHolder) pemParser.readObject(); - final X509Certificate vaultCertificate = new JcaX509CertificateConverter() - .setProvider(BouncyCastleProvider.PROVIDER_NAME) - .getCertificate(certificateHolder); + final X509CertificateHolder certificateHolder = getX509CertificateHolder(); + final X509Certificate vaultCertificate = getCertificate(certificateHolder); + + KeyStore clientTrustStore = getClientTrustStore(vaultCertificate); // Store the Vault's server certificate as a trusted cert in the truststore - final KeyStore trustStore = KeyStore.getInstance("jks"); - trustStore.load(null); - trustStore.setCertificateEntry("cert", vaultCertificate); - try (final FileOutputStream keystoreOutputStream = new FileOutputStream(CLIENT_TRUSTSTORE)) { - trustStore.store(keystoreOutputStream, "password".toCharArray()); - } // Generate a client certificate, and store it in a Java keystore final KeyPair keyPair = generateKeyPair(); - final X509Certificate clientCertificate = - generateCert(keyPair, "C=AU, O=The Legion of the Bouncy Castle, OU=Client Certificate, CN=localhost"); - final KeyStore keyStore = KeyStore.getInstance("jks"); - keyStore.load(null); - keyStore.setKeyEntry("privatekey", keyPair.getPrivate(), "password".toCharArray(), new Certificate[]{clientCertificate}); - keyStore.setCertificateEntry("cert", clientCertificate); - try (final FileOutputStream keystoreOutputStream = new FileOutputStream(CLIENT_KEYSTORE)) { - keyStore.store(keystoreOutputStream, "password".toCharArray()); + final X509Certificate clientCertificate = generateCert(keyPair); + if (clientCertificate == null) { + throw new IOException("Failed to generate certificate"); } + final KeyStore clientKeystore = getClientKeystore(keyPair, clientCertificate); // Also write the client certificate to a PEM file, so it can be registered with Vault - writeCertToPem(clientCertificate, CLIENT_CERT_PEMFILE); - writePrivateKeyToPem(keyPair.getPrivate(), CLIENT_PRIVATE_KEY_PEMFILE); + String certToPem = certToPem(clientCertificate); + String privateKeyToPem = privateKeyToPem(keyPair.getPrivate()); + return new HashMap() { + { + put("clientKeystore", clientKeystore); + put("clientTrustStore", clientTrustStore); + put("cert", certToPem); + put("privateKey", privateKeyToPem); + } + }; + } + + private static KeyStore getClientTrustStore(X509Certificate vaultCertificate) throws IOException { + final KeyStore trustStore = emptyStore(); + try { + trustStore.setCertificateEntry("cert", vaultCertificate); + } catch (KeyStoreException e) { + throw new IOException("Cannot create trust keystore.", e); + } + return trustStore; + } + + private static KeyStore getClientKeystore(KeyPair keyPair, X509Certificate clientCertificate) { + try { + final KeyStore keyStore = emptyStore(); + keyStore.setKeyEntry("privatekey", keyPair.getPrivate(), PASSWORD.toCharArray(), new Certificate[]{clientCertificate}); + keyStore.setCertificateEntry("cert", clientCertificate); + return keyStore; + } catch (KeyStoreException | IOException e) { + return null; + } + } + + private static X509CertificateHolder getX509CertificateHolder() { + final PEMParser pemParser; + try (FileReader fileReader = new FileReader(CERT_PEMFILE)) { + pemParser = new PEMParser(fileReader); + return (X509CertificateHolder) pemParser.readObject(); + } catch (IOException e) { + return null; + } + } + + private static X509Certificate getCertificate(X509CertificateHolder certificateHolder) { + try { + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate(certificateHolder); + } catch (CertificateException e) { + return null; + } } /** * See https://www.cryptoworkshop.com/guide/, chapter 3 * * @return A 4096-bit RSA key pair - * @throws NoSuchAlgorithmException */ - private static KeyPair generateKeyPair() throws NoSuchAlgorithmException { - final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); - keyPairGenerator.initialize(4096); - return keyPairGenerator.genKeyPair(); + private static KeyPair generateKeyPair() throws IOException { + try { + final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); + keyPairGenerator.initialize(4096); + KeyPair keyPair = keyPairGenerator.genKeyPair(); + if (keyPair == null) { + throw new IOException("Failed to generate keypair"); + } + return keyPair; + } catch (NoSuchAlgorithmException e) { + throw new IOException("Failed to generate keypair", e); + } } /** * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder * * @param keyPair The RSA keypair with which to generate the certificate - * @param issuer The issuer (and subject) to use for the certificate * @return An X509 certificate - * @throws IOException - * @throws CertificateException - * @throws NoSuchProviderException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws SignatureException */ - private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, - CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, - SignatureException, OperatorCreationException { - final String subject = issuer; + private static X509Certificate generateCert(final KeyPair keyPair) { + String issuer = "C=AU, O=The Legion of the Bouncy Castle, OU=Client Certificate, CN=localhost"; final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( new X500Name(issuer), BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), - new X500Name(subject), + new X500Name(issuer), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) ); final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); - certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + try { + certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } catch (CertIOException e) { + e.printStackTrace(); + return null; + } final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption"); final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); - final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); - final ContentSigner signer = signerBuilder.build(keyp); - final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer); - - final X509Certificate certificate = new JcaX509CertificateConverter() - .getCertificate(x509CertificateHolder); - certificate.checkValidity(new Date()); - certificate.verify(keyPair.getPublic()); + final X509CertificateHolder x509CertificateHolder; + try { + final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); + final ContentSigner signer = signerBuilder.build(keyp); + x509CertificateHolder = certificateBuilder.build(signer); + } catch (IOException | OperatorCreationException e) { + e.printStackTrace(); + return null; + } + + final X509Certificate certificate; + try { + certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder); + certificate.checkValidity(new Date()); + certificate.verify(keyPair.getPublic()); + } catch (CertificateException | SignatureException | InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException e) { + e.printStackTrace(); + return null; + } + return certificate; } @@ -173,42 +221,37 @@ private static X509Certificate generateCert(final KeyPair keyPair, final String * See https://stackoverflow.com/questions/3313020/write-x509-certificate-into-pem-formatted-string-in-java * * @param certificate An X509 certificate - * @param filename The name (including path) of a file to which the certificate will be written in PEM format - * @throws CertificateEncodingException - * @throws FileNotFoundException + * @return String certificate in pem format */ - private static void writeCertToPem(final X509Certificate certificate, final String filename) - throws CertificateEncodingException, FileNotFoundException { + private static String certToPem(final X509Certificate certificate) throws IOException { final Base64.Encoder encoder = Base64.getMimeEncoder(); final String certHeader = "-----BEGIN CERTIFICATE-----\n"; final String certFooter = "\n-----END CERTIFICATE-----"; - final byte[] certBytes = certificate.getEncoded(); - final String certContents = new String(encoder.encode(certBytes)); - final String certPem = certHeader + certContents + certFooter; - try (final PrintWriter out = new PrintWriter(filename)) { - out.println(certPem); + final byte[] certBytes; + try { + certBytes = certificate.getEncoded(); + } catch (CertificateEncodingException e) { + throw new IOException("Failed to encode certificate", e); } + final String certContents = new String(encoder.encode(certBytes)); + return certHeader + certContents + certFooter; } /** * See https://stackoverflow.com/questions/3313020/write-x509-certificate-into-pem-formatted-string-in-java * * @param key An RSA private key - * @param filename The name (including path) of a file to which the private key will be written in PEM format - * @throws FileNotFoundException + * @return String private key in pem format */ - private static void writePrivateKeyToPem(final PrivateKey key, final String filename) throws FileNotFoundException { + private static String privateKeyToPem(final PrivateKey key) { final Base64.Encoder encoder = Base64.getMimeEncoder(); final String keyHeader = "-----BEGIN PRIVATE KEY-----\n"; final String keyFooter = "\n-----END PRIVATE KEY-----"; final byte[] keyBytes = key.getEncoded(); final String keyContents = new String(encoder.encode(keyBytes)); - final String keyPem = keyHeader + keyContents + keyFooter; - try (final PrintWriter out = new PrintWriter(filename)) { - out.println(keyPem); - } + return keyHeader + keyContents + keyFooter; } /** @@ -228,13 +271,25 @@ public static String generatePKCS10(KeyPair kp, String CN, String OU, String O, ContentSigner signGen = new JcaContentSignerBuilder("SHA256withRSA").build(kp.getPrivate()); PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic()); PKCS10CertificationRequest csr = builder.build(signGen); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - Writer osWriter = new OutputStreamWriter(output); - JcaPEMWriter pem = new JcaPEMWriter(osWriter); - pem.writeObject(csr); - pem.close(); - return new String(output.toByteArray()); + try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { + try (Writer osWriter = new OutputStreamWriter(output)) { + try (JcaPEMWriter pem = new JcaPEMWriter(osWriter)) { + pem.writeObject(csr); + } + } + return new String(output.toByteArray()); + } } + public static KeyStore emptyStore() throws IOException { + try { + KeyStore ks = KeyStore.getInstance("JKS"); + // Loading creates the store, can't do anything with it until it's loaded + ks.load(null, PASSWORD.toCharArray()); + return ks; + } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { + throw new IOException("Cannot create empty keystore.", e); + } + } } 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 1c34a29c..354449d0 100644 --- a/src/test-integration/java/com/bettercloud/vault/util/TestConstants.java +++ b/src/test-integration/java/com/bettercloud/vault/util/TestConstants.java @@ -10,7 +10,7 @@ * and {@link SSLUtils}. Mostly username/password credentials and other Vault configuration values, and * path locations for SSL artifacts. */ -interface TestConstants { +public interface TestConstants { String POSTGRES_PASSWORD = "superpassword1"; String POSTGRES_USER = "superuser1"; @@ -26,9 +26,6 @@ interface TestConstants { String CERT_PEMFILE = SSL_DIRECTORY + File.separator + "root-cert.pem"; String CLIENT_CERT_PEMFILE = SSL_DIRECTORY + File.separator + "client-cert.pem"; - String CLIENT_PRIVATE_KEY_PEMFILE = SSL_DIRECTORY + File.separator + "client-privatekey.pem"; - String CLIENT_KEYSTORE = SSL_DIRECTORY + File.separator + "keystore.jks"; - String CLIENT_TRUSTSTORE = SSL_DIRECTORY + File.separator + "truststore.jks"; String CONTAINER_STARTUP_SCRIPT = "/vault/config/startup.sh"; String CONTAINER_CONFIG_FILE = "/vault/config/config.json"; 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 15595e68..163aa707 100644 --- a/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java +++ b/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java @@ -176,10 +176,11 @@ public void setupBackendPki() throws IOException, InterruptedException { * * @throws IOException * @throws InterruptedException + * @param cert */ - public void setupBackendCert() throws IOException, InterruptedException { + public void setupBackendCert(String cert) throws IOException, InterruptedException { runCommand("vault", "login", "-ca-cert=" + CONTAINER_CERT_PEMFILE, rootToken); - + runCommand("sh", "-c", "cat <> " + CONTAINER_CLIENT_CERT_PEMFILE + "\n" + cert + "\nEOL"); runCommand("vault", "auth", "enable", "-ca-cert=" + CONTAINER_CERT_PEMFILE, "cert"); runCommand("vault", "write", "-ca-cert=" + CONTAINER_CERT_PEMFILE, "auth/cert/certs/web", "display_name=web", "policies=web,prod", "certificate=@" + CONTAINER_CLIENT_CERT_PEMFILE, "ttl=3600"); From a684096fd01a99f19dd563c1870cfabd661f985b Mon Sep 17 00:00:00 2001 From: Joseph Petersen Date: Sun, 25 Aug 2019 15:45:27 +0200 Subject: [PATCH 33/34] code style and import order --- .gitignore | 3 +- .idea/codeStyles/Project.xml | 125 ++++++++++++++++++ .idea/codeStyles/codeStyleConfig.xml | 5 + config/checkstyle/checkstyle.xml | 28 ++-- .../java/com/bettercloud/vault/SslConfig.java | 11 +- .../java/com/bettercloud/vault/Vault.java | 1 - .../java/com/bettercloud/vault/api/Auth.java | 1 - .../java/com/bettercloud/vault/api/Debug.java | 1 - .../com/bettercloud/vault/api/Leases.java | 1 - .../com/bettercloud/vault/api/Logical.java | 19 ++- .../vault/api/LogicalUtilities.java | 1 - .../java/com/bettercloud/vault/api/Seal.java | 1 - .../vault/api/database/Database.java | 1 - .../vault/api/mounts/MountPayload.java | 6 +- .../bettercloud/vault/api/mounts/Mounts.java | 1 - .../com/bettercloud/vault/api/pki/Pki.java | 1 - .../com/bettercloud/vault/json/JsonArray.java | 1 - .../bettercloud/vault/json/JsonObject.java | 4 +- .../com/bettercloud/vault/json/JsonValue.java | 1 - .../vault/response/AuthResponse.java | 1 - .../vault/response/DatabaseResponse.java | 1 - .../vault/response/HealthResponse.java | 1 - .../vault/response/LogicalResponse.java | 1 - .../vault/response/LookupResponse.java | 7 +- .../vault/response/MountResponse.java | 9 +- .../vault/response/PkiResponse.java | 1 - .../vault/response/SealResponse.java | 1 - .../vault/response/VaultResponse.java | 1 - .../java/com/bettercloud/vault/rest/Rest.java | 8 +- .../vault/api/AuthBackendAppIdTests.java | 3 +- .../vault/api/AuthBackendAppRoleTests.java | 3 +- .../vault/api/AuthBackendCertTests.java | 7 +- .../vault/api/AuthBackendDatabaseTests.java | 7 +- .../vault/api/AuthBackendPkiTests.java | 16 ++- .../vault/api/AuthBackendTokenTests.java | 5 +- .../vault/api/AuthBackendUserPassTests.java | 3 +- .../com/bettercloud/vault/api/DebugTests.java | 9 +- .../bettercloud/vault/api/LeasesTests.java | 10 +- .../bettercloud/vault/api/LogicalTests.java | 15 +-- .../bettercloud/vault/api/MountsTests.java | 24 ++-- .../com/bettercloud/vault/api/SealTests.java | 3 +- .../vault/api/VaultAgentTests.java | 7 +- .../com/bettercloud/vault/util/SSLUtils.java | 50 ++++--- .../bettercloud/vault/util/TestConstants.java | 3 +- .../vault/util/VaultAgentContainer.java | 2 - .../vault/util/VaultContainer.java | 8 +- .../vault/LogicalUtilitiesTests.java | 3 +- .../com/bettercloud/vault/RetryTests.java | 4 +- .../java/com/bettercloud/vault/SSLTests.java | 5 +- .../bettercloud/vault/VaultConfigTests.java | 5 +- .../com/bettercloud/vault/VaultTests.java | 7 +- .../vault/api/pki/CredentialTests.java | 1 - .../vault/api/pki/RoleOptionsTests.java | 3 +- .../vault/json/JsonArray_Test.java | 15 ++- .../vault/json/JsonLiteral_Test.java | 19 ++- .../vault/json/JsonNumber_Test.java | 7 +- .../vault/json/JsonObject_Test.java | 17 ++- .../vault/json/JsonParser_Test.java | 9 +- .../vault/json/JsonString_Test.java | 7 +- .../vault/json/JsonValue_Test.java | 10 +- .../vault/json/JsonWriter_Test.java | 5 +- .../com/bettercloud/vault/json/Json_Test.java | 10 +- .../vault/json/ParseException_Test.java | 4 +- .../vault/json/PrettyPrint_Test.java | 16 ++- .../com/bettercloud/vault/json/TestUtil.java | 6 +- .../vault/json/WritingBuffer_Test.java | 5 +- .../vault/json/test/mocking/Mocking_Test.java | 9 +- .../bettercloud/vault/rest/DeleteTests.java | 3 +- .../com/bettercloud/vault/rest/GetTests.java | 7 +- .../com/bettercloud/vault/rest/PostTests.java | 6 +- .../com/bettercloud/vault/rest/PutTests.java | 3 +- .../vault/vault/VaultTestUtils.java | 11 +- .../vault/vault/api/AuthBackendAwsTests.java | 5 +- .../vault/vault/api/AuthLookupTest.java | 3 +- .../vault/vault/api/AuthLookupWrapTest.java | 3 +- .../mock/AuthRequestValidatingMockVault.java | 7 +- .../vault/vault/mock/EchoInputMockVault.java | 7 +- .../vault/vault/mock/MockVault.java | 8 +- .../vault/mock/OpenTimeoutsMockVault.java | 5 +- .../vault/mock/ReadTimeoutsMockVault.java | 5 +- .../vault/vault/mock/RetriesMockVault.java | 6 +- 81 files changed, 386 insertions(+), 278 deletions(-) create mode 100644 .idea/codeStyles/Project.xml create mode 100644 .idea/codeStyles/codeStyleConfig.xml diff --git a/.gitignore b/.gitignore index f1180579..7d0667d7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .gradle -.idea +.idea/* +!.idea/codeStyles/ .testcontainers-tmp* vault-java-driver.iml diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 00000000..8c7b0846 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,125 @@ + + + + + + + diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 00000000..0f7bc519 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 1a18d739..7e739db3 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -1,12 +1,24 @@ - + - - - - - - - + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/bettercloud/vault/SslConfig.java b/src/main/java/com/bettercloud/vault/SslConfig.java index 41d47cac..21179b14 100644 --- a/src/main/java/com/bettercloud/vault/SslConfig.java +++ b/src/main/java/com/bettercloud/vault/SslConfig.java @@ -1,12 +1,6 @@ package com.bettercloud.vault; import com.bettercloud.vault.api.Auth; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; @@ -31,6 +25,11 @@ import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Base64; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; /** *

    A container for SSL-related configuration options, meant to be stored within a {@link VaultConfig} instance.

    diff --git a/src/main/java/com/bettercloud/vault/Vault.java b/src/main/java/com/bettercloud/vault/Vault.java index 0a7fce08..5f44a4a4 100644 --- a/src/main/java/com/bettercloud/vault/Vault.java +++ b/src/main/java/com/bettercloud/vault/Vault.java @@ -14,7 +14,6 @@ import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestException; import com.bettercloud.vault.rest.RestResponse; - import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/com/bettercloud/vault/api/Auth.java b/src/main/java/com/bettercloud/vault/api/Auth.java index 2f7a6417..949ae858 100644 --- a/src/main/java/com/bettercloud/vault/api/Auth.java +++ b/src/main/java/com/bettercloud/vault/api/Auth.java @@ -10,7 +10,6 @@ import com.bettercloud.vault.response.LookupResponse; import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestResponse; - import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.List; diff --git a/src/main/java/com/bettercloud/vault/api/Debug.java b/src/main/java/com/bettercloud/vault/api/Debug.java index 370d73c7..0acf4ccb 100644 --- a/src/main/java/com/bettercloud/vault/api/Debug.java +++ b/src/main/java/com/bettercloud/vault/api/Debug.java @@ -6,7 +6,6 @@ import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestException; import com.bettercloud.vault.rest.RestResponse; - import java.util.HashSet; import java.util.Set; diff --git a/src/main/java/com/bettercloud/vault/api/Leases.java b/src/main/java/com/bettercloud/vault/api/Leases.java index 1c36a984..c378be20 100644 --- a/src/main/java/com/bettercloud/vault/api/Leases.java +++ b/src/main/java/com/bettercloud/vault/api/Leases.java @@ -6,7 +6,6 @@ import com.bettercloud.vault.response.VaultResponse; import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestResponse; - import java.nio.charset.StandardCharsets; diff --git a/src/main/java/com/bettercloud/vault/api/Logical.java b/src/main/java/com/bettercloud/vault/api/Logical.java index 0c207534..c0566a01 100644 --- a/src/main/java/com/bettercloud/vault/api/Logical.java +++ b/src/main/java/com/bettercloud/vault/api/Logical.java @@ -1,11 +1,5 @@ package com.bettercloud.vault.api; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - import com.bettercloud.vault.VaultConfig; import com.bettercloud.vault.VaultException; import com.bettercloud.vault.json.Json; @@ -15,8 +9,19 @@ import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestException; import com.bettercloud.vault.rest.RestResponse; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; -import static com.bettercloud.vault.api.LogicalUtilities.*; +import static com.bettercloud.vault.api.LogicalUtilities.adjustPathForDelete; +import static com.bettercloud.vault.api.LogicalUtilities.adjustPathForList; +import static com.bettercloud.vault.api.LogicalUtilities.adjustPathForReadOrWrite; +import static com.bettercloud.vault.api.LogicalUtilities.adjustPathForVersionDelete; +import static com.bettercloud.vault.api.LogicalUtilities.adjustPathForVersionDestroy; +import static com.bettercloud.vault.api.LogicalUtilities.adjustPathForVersionUnDelete; +import static com.bettercloud.vault.api.LogicalUtilities.jsonObjectToWriteFromEngineVersion; /** diff --git a/src/main/java/com/bettercloud/vault/api/LogicalUtilities.java b/src/main/java/com/bettercloud/vault/api/LogicalUtilities.java index 305bf364..a1746fbc 100644 --- a/src/main/java/com/bettercloud/vault/api/LogicalUtilities.java +++ b/src/main/java/com/bettercloud/vault/api/LogicalUtilities.java @@ -1,7 +1,6 @@ package com.bettercloud.vault.api; import com.bettercloud.vault.json.JsonObject; - import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; diff --git a/src/main/java/com/bettercloud/vault/api/Seal.java b/src/main/java/com/bettercloud/vault/api/Seal.java index 857772f6..667cf124 100644 --- a/src/main/java/com/bettercloud/vault/api/Seal.java +++ b/src/main/java/com/bettercloud/vault/api/Seal.java @@ -6,7 +6,6 @@ import com.bettercloud.vault.response.SealResponse; import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestResponse; - import java.nio.charset.StandardCharsets; /** diff --git a/src/main/java/com/bettercloud/vault/api/database/Database.java b/src/main/java/com/bettercloud/vault/api/database/Database.java index 0fd12260..2e89bded 100644 --- a/src/main/java/com/bettercloud/vault/api/database/Database.java +++ b/src/main/java/com/bettercloud/vault/api/database/Database.java @@ -7,7 +7,6 @@ import com.bettercloud.vault.response.DatabaseResponse; import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestResponse; - import java.nio.charset.StandardCharsets; import java.util.List; 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 f67dc1e6..96782fd0 100644 --- a/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java +++ b/src/main/java/com/bettercloud/vault/api/mounts/MountPayload.java @@ -1,12 +1,10 @@ package com.bettercloud.vault.api.mounts; +import com.bettercloud.vault.json.Json; +import com.bettercloud.vault.json.JsonObject; import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; - -import com.bettercloud.vault.json.Json; -import com.bettercloud.vault.json.JsonObject; /** *

    A container for options sent to mounts endpoints on the Secret Engine backend as REST payload. This class is 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 63798c49..d2779c4a 100644 --- a/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java +++ b/src/main/java/com/bettercloud/vault/api/mounts/Mounts.java @@ -5,7 +5,6 @@ import com.bettercloud.vault.response.MountResponse; import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestResponse; - import java.nio.charset.StandardCharsets; /** diff --git a/src/main/java/com/bettercloud/vault/api/pki/Pki.java b/src/main/java/com/bettercloud/vault/api/pki/Pki.java index 9a7c3d91..852a892f 100644 --- a/src/main/java/com/bettercloud/vault/api/pki/Pki.java +++ b/src/main/java/com/bettercloud/vault/api/pki/Pki.java @@ -7,7 +7,6 @@ import com.bettercloud.vault.response.PkiResponse; import com.bettercloud.vault.rest.Rest; import com.bettercloud.vault.rest.RestResponse; - import java.nio.charset.StandardCharsets; import java.util.List; diff --git a/src/main/java/com/bettercloud/vault/json/JsonArray.java b/src/main/java/com/bettercloud/vault/json/JsonArray.java index 1f89bcaf..d018b7da 100644 --- a/src/main/java/com/bettercloud/vault/json/JsonArray.java +++ b/src/main/java/com/bettercloud/vault/json/JsonArray.java @@ -22,7 +22,6 @@ package com.bettercloud.vault.json; import java.io.IOException; -import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; diff --git a/src/main/java/com/bettercloud/vault/json/JsonObject.java b/src/main/java/com/bettercloud/vault/json/JsonObject.java index 58ee44b7..b38af9b8 100644 --- a/src/main/java/com/bettercloud/vault/json/JsonObject.java +++ b/src/main/java/com/bettercloud/vault/json/JsonObject.java @@ -21,16 +21,14 @@ ******************************************************************************/ package com.bettercloud.vault.json; +import com.bettercloud.vault.json.JsonObject.Member; import java.io.IOException; import java.io.ObjectInputStream; -import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; -import com.bettercloud.vault.json.JsonObject.Member; - /** * Represents a JSON object, a set of name/value pairs, where the names are strings and the values diff --git a/src/main/java/com/bettercloud/vault/json/JsonValue.java b/src/main/java/com/bettercloud/vault/json/JsonValue.java index 7746bb9e..0d8855fc 100644 --- a/src/main/java/com/bettercloud/vault/json/JsonValue.java +++ b/src/main/java/com/bettercloud/vault/json/JsonValue.java @@ -22,7 +22,6 @@ package com.bettercloud.vault.json; import java.io.IOException; -import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; diff --git a/src/main/java/com/bettercloud/vault/response/AuthResponse.java b/src/main/java/com/bettercloud/vault/response/AuthResponse.java index 761b9e82..2c1167f8 100644 --- a/src/main/java/com/bettercloud/vault/response/AuthResponse.java +++ b/src/main/java/com/bettercloud/vault/response/AuthResponse.java @@ -6,7 +6,6 @@ import com.bettercloud.vault.json.JsonValue; import com.bettercloud.vault.json.ParseException; import com.bettercloud.vault.rest.RestResponse; - import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/bettercloud/vault/response/DatabaseResponse.java b/src/main/java/com/bettercloud/vault/response/DatabaseResponse.java index b8e9a42d..d099ceb7 100644 --- a/src/main/java/com/bettercloud/vault/response/DatabaseResponse.java +++ b/src/main/java/com/bettercloud/vault/response/DatabaseResponse.java @@ -6,7 +6,6 @@ import com.bettercloud.vault.json.JsonArray; import com.bettercloud.vault.json.JsonObject; import com.bettercloud.vault.rest.RestResponse; - import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/bettercloud/vault/response/HealthResponse.java b/src/main/java/com/bettercloud/vault/response/HealthResponse.java index 87fe0ab4..6e96514a 100644 --- a/src/main/java/com/bettercloud/vault/response/HealthResponse.java +++ b/src/main/java/com/bettercloud/vault/response/HealthResponse.java @@ -4,7 +4,6 @@ import com.bettercloud.vault.json.Json; import com.bettercloud.vault.json.JsonObject; import com.bettercloud.vault.rest.RestResponse; - import java.io.Serializable; import java.nio.charset.StandardCharsets; diff --git a/src/main/java/com/bettercloud/vault/response/LogicalResponse.java b/src/main/java/com/bettercloud/vault/response/LogicalResponse.java index 21a47d7b..53e75874 100644 --- a/src/main/java/com/bettercloud/vault/response/LogicalResponse.java +++ b/src/main/java/com/bettercloud/vault/response/LogicalResponse.java @@ -5,7 +5,6 @@ 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.HashMap; import java.util.Map; diff --git a/src/main/java/com/bettercloud/vault/response/LookupResponse.java b/src/main/java/com/bettercloud/vault/response/LookupResponse.java index dfa6bd40..a8fc8eda 100644 --- a/src/main/java/com/bettercloud/vault/response/LookupResponse.java +++ b/src/main/java/com/bettercloud/vault/response/LookupResponse.java @@ -1,15 +1,14 @@ package com.bettercloud.vault.response; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - 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.json.ParseException; import com.bettercloud.vault.rest.RestResponse; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; /** * This class is a container for the information returned by Vault in lookup operations on auth backends. diff --git a/src/main/java/com/bettercloud/vault/response/MountResponse.java b/src/main/java/com/bettercloud/vault/response/MountResponse.java index 4c8d8c7d..f2ec0a1e 100644 --- a/src/main/java/com/bettercloud/vault/response/MountResponse.java +++ b/src/main/java/com/bettercloud/vault/response/MountResponse.java @@ -1,10 +1,5 @@ package com.bettercloud.vault.response; -import java.util.Collections; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; - import com.bettercloud.vault.api.Logical; import com.bettercloud.vault.api.mounts.Mount; import com.bettercloud.vault.api.mounts.MountConfig; @@ -13,6 +8,10 @@ import com.bettercloud.vault.json.JsonObject.Member; import com.bettercloud.vault.json.JsonValue; import com.bettercloud.vault.rest.RestResponse; +import java.util.Collections; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; /** * This class is a container for the information returned by Vault in /sys/mounts/ API diff --git a/src/main/java/com/bettercloud/vault/response/PkiResponse.java b/src/main/java/com/bettercloud/vault/response/PkiResponse.java index d0666d53..6e692249 100644 --- a/src/main/java/com/bettercloud/vault/response/PkiResponse.java +++ b/src/main/java/com/bettercloud/vault/response/PkiResponse.java @@ -4,7 +4,6 @@ import com.bettercloud.vault.api.pki.Credential; import com.bettercloud.vault.api.pki.RoleOptions; import com.bettercloud.vault.rest.RestResponse; - import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/bettercloud/vault/response/SealResponse.java b/src/main/java/com/bettercloud/vault/response/SealResponse.java index 38a53a40..3322b073 100644 --- a/src/main/java/com/bettercloud/vault/response/SealResponse.java +++ b/src/main/java/com/bettercloud/vault/response/SealResponse.java @@ -4,7 +4,6 @@ import com.bettercloud.vault.json.JsonObject; import com.bettercloud.vault.json.ParseException; import com.bettercloud.vault.rest.RestResponse; - import java.nio.charset.StandardCharsets; /** diff --git a/src/main/java/com/bettercloud/vault/response/VaultResponse.java b/src/main/java/com/bettercloud/vault/response/VaultResponse.java index b6efdc13..6082d113 100644 --- a/src/main/java/com/bettercloud/vault/response/VaultResponse.java +++ b/src/main/java/com/bettercloud/vault/response/VaultResponse.java @@ -1,7 +1,6 @@ package com.bettercloud.vault.response; import com.bettercloud.vault.rest.RestResponse; - import java.io.Serializable; /** diff --git a/src/main/java/com/bettercloud/vault/rest/Rest.java b/src/main/java/com/bettercloud/vault/rest/Rest.java index e2aa1930..7ac9290f 100644 --- a/src/main/java/com/bettercloud/vault/rest/Rest.java +++ b/src/main/java/com/bettercloud/vault/rest/Rest.java @@ -1,9 +1,5 @@ package com.bettercloud.vault.rest; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -23,6 +19,10 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; /** *

    A simple client for issuing HTTP requests. Supports the HTTP verbs:

    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 7c4439ff..24ec60b0 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppIdTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppIdTests.java @@ -3,12 +3,11 @@ import com.bettercloud.vault.Vault; import com.bettercloud.vault.VaultException; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import java.io.IOException; - import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; diff --git a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppRoleTests.java b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppRoleTests.java index de71aa7b..e1ade502 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppRoleTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendAppRoleTests.java @@ -5,12 +5,11 @@ import com.bettercloud.vault.VaultException; import com.bettercloud.vault.response.LogicalResponse; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import java.io.IOException; - import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; 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 8eb37c86..1eb1a9c9 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendCertTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendCertTests.java @@ -6,14 +6,13 @@ import com.bettercloud.vault.VaultException; import com.bettercloud.vault.util.SSLUtils; import com.bettercloud.vault.util.VaultContainer; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; - import java.io.File; import java.io.IOException; import java.security.KeyStore; import java.util.HashMap; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; import static com.bettercloud.vault.util.TestConstants.PASSWORD; import static org.junit.Assert.assertNotNull; 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 eefffb10..d9d41c60 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendDatabaseTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendDatabaseTests.java @@ -6,13 +6,12 @@ import com.bettercloud.vault.response.DatabaseResponse; import com.bettercloud.vault.util.DbContainer; import com.bettercloud.vault.util.VaultContainer; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; - import java.io.IOException; import java.util.ArrayList; import java.util.List; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; diff --git a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendPkiTests.java b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendPkiTests.java index e8aacdf0..43bdecb2 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendPkiTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendPkiTests.java @@ -7,17 +7,23 @@ import com.bettercloud.vault.response.PkiResponse; import com.bettercloud.vault.rest.RestResponse; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.ArrayList; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import java.io.IOException; -import java.security.*; -import java.util.ArrayList; - import static com.bettercloud.vault.util.SSLUtils.generatePKCS10; -import static junit.framework.TestCase.*; +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertNull; +import static junit.framework.TestCase.assertTrue; /** * Integration tests for for operations on Vault's /v1/pki/* REST endpoints. diff --git a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendTokenTests.java b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendTokenTests.java index c3197e81..3d76d359 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendTokenTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendTokenTests.java @@ -6,13 +6,12 @@ import com.bettercloud.vault.response.AuthResponse; import com.bettercloud.vault.response.LookupResponse; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; diff --git a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendUserPassTests.java b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendUserPassTests.java index dd869bdb..2ac3086f 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/AuthBackendUserPassTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/AuthBackendUserPassTests.java @@ -4,12 +4,11 @@ import com.bettercloud.vault.VaultException; import com.bettercloud.vault.response.AuthResponse; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import java.io.IOException; - import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; diff --git a/src/test-integration/java/com/bettercloud/vault/api/DebugTests.java b/src/test-integration/java/com/bettercloud/vault/api/DebugTests.java index 3c01bca5..26223730 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/DebugTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/DebugTests.java @@ -4,14 +4,17 @@ import com.bettercloud.vault.VaultException; import com.bettercloud.vault.response.HealthResponse; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import java.io.IOException; - -import static junit.framework.TestCase.*; +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertNull; +import static junit.framework.TestCase.assertTrue; /** *

    Integration tests for the debug-related operations on the Vault HTTP API's.

    diff --git a/src/test-integration/java/com/bettercloud/vault/api/LeasesTests.java b/src/test-integration/java/com/bettercloud/vault/api/LeasesTests.java index 0bc119c4..f753f189 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/LeasesTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/LeasesTests.java @@ -1,18 +1,16 @@ package com.bettercloud.vault.api; -import static junit.framework.TestCase.assertEquals; - +import com.bettercloud.vault.Vault; +import com.bettercloud.vault.VaultException; import com.bettercloud.vault.response.VaultResponse; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import com.bettercloud.vault.Vault; -import com.bettercloud.vault.VaultException; - -import java.io.IOException; +import static junit.framework.TestCase.assertEquals; /** *

    Integration tests for the basic (i.e. "sys") Vault API operations.

    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 71a68a90..03d49f31 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/LogicalTests.java @@ -1,26 +1,23 @@ package com.bettercloud.vault.api; +import com.bettercloud.vault.Vault; +import com.bettercloud.vault.VaultConfig; +import com.bettercloud.vault.VaultException; +import com.bettercloud.vault.response.AuthResponse; +import com.bettercloud.vault.response.LogicalResponse; +import com.bettercloud.vault.util.VaultContainer; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; - -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; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; - -import com.bettercloud.vault.Vault; -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; 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 c036b458..e973e80d 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/MountsTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/MountsTests.java @@ -1,18 +1,5 @@ package com.bettercloud.vault.api; -import static junit.framework.TestCase.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import com.bettercloud.vault.Vault; import com.bettercloud.vault.VaultException; import com.bettercloud.vault.api.mounts.Mount; @@ -22,6 +9,17 @@ import com.bettercloud.vault.api.mounts.TimeToLive; import com.bettercloud.vault.response.MountResponse; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static junit.framework.TestCase.assertEquals; +import static org.junit.Assert.assertTrue; /** Integration tests for for operations on Vault's /v1/sys/mounts/* REST endpoints. */ public class MountsTests { diff --git a/src/test-integration/java/com/bettercloud/vault/api/SealTests.java b/src/test-integration/java/com/bettercloud/vault/api/SealTests.java index 473755a0..b1d45b3c 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/SealTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/SealTests.java @@ -3,12 +3,11 @@ import com.bettercloud.vault.VaultException; import com.bettercloud.vault.response.SealResponse; import com.bettercloud.vault.util.VaultContainer; +import java.io.IOException; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; -import java.io.IOException; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; 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 59c75ccc..34777e89 100644 --- a/src/test-integration/java/com/bettercloud/vault/api/VaultAgentTests.java +++ b/src/test-integration/java/com/bettercloud/vault/api/VaultAgentTests.java @@ -6,13 +6,14 @@ import com.bettercloud.vault.response.LogicalResponse; import com.bettercloud.vault.util.VaultAgentContainer; import com.bettercloud.vault.util.VaultContainer; -import org.junit.*; -import org.junit.rules.TemporaryFolder; - import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; import static junit.framework.TestCase.assertEquals; import static org.apache.commons.io.FileUtils.writeStringToFile; 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 58b5e669..332c92cd 100644 --- a/src/test-integration/java/com/bettercloud/vault/util/SSLUtils.java +++ b/src/test-integration/java/com/bettercloud/vault/util/SSLUtils.java @@ -1,5 +1,29 @@ package com.bettercloud.vault.util; +import java.io.ByteArrayOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.Security; +import java.security.SignatureException; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.Extension; @@ -26,32 +50,6 @@ import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; -import javax.security.auth.x500.X500Principal; -import java.io.ByteArrayOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Writer; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.Security; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -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 * auth backend. Right now, all such code is isolated to {@link com.bettercloud.vault.api.AuthBackendCertTests}. 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 354449d0..52e1cea4 100644 --- a/src/test-integration/java/com/bettercloud/vault/util/TestConstants.java +++ b/src/test-integration/java/com/bettercloud/vault/util/TestConstants.java @@ -1,10 +1,9 @@ package com.bettercloud.vault.util; +import java.io.File; import org.testcontainers.containers.Network; import org.testcontainers.utility.TestEnvironment; -import java.io.File; - /** * Various constants used throughout the integration test suite, but primarily by {@link VaultContainer} * and {@link SSLUtils}. Mostly username/password credentials and other Vault configuration values, and 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 be0ba9f7..35e9688b 100644 --- a/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java +++ b/src/test-integration/java/com/bettercloud/vault/util/VaultAgentContainer.java @@ -4,9 +4,7 @@ import com.bettercloud.vault.VaultConfig; import com.bettercloud.vault.VaultException; import com.github.dockerjava.api.model.Capability; - import java.nio.file.Path; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.BindMode; 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 163aa707..6602e881 100644 --- a/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java +++ b/src/test-integration/java/com/bettercloud/vault/util/VaultContainer.java @@ -7,6 +7,9 @@ import com.bettercloud.vault.json.Json; import com.bettercloud.vault.json.JsonObject; import com.github.dockerjava.api.model.Capability; +import java.io.File; +import java.io.IOException; +import java.net.HttpURLConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.BindMode; @@ -16,11 +19,6 @@ 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; diff --git a/src/test/java/com/bettercloud/vault/LogicalUtilitiesTests.java b/src/test/java/com/bettercloud/vault/LogicalUtilitiesTests.java index f56337cf..438f3048 100644 --- a/src/test/java/com/bettercloud/vault/LogicalUtilitiesTests.java +++ b/src/test/java/com/bettercloud/vault/LogicalUtilitiesTests.java @@ -3,11 +3,10 @@ import com.bettercloud.vault.api.Logical; import com.bettercloud.vault.api.LogicalUtilities; import com.bettercloud.vault.json.JsonObject; +import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; -import java.util.ArrayList; - public class LogicalUtilitiesTests { diff --git a/src/test/java/com/bettercloud/vault/RetryTests.java b/src/test/java/com/bettercloud/vault/RetryTests.java index 8779ed6f..a51237f2 100644 --- a/src/test/java/com/bettercloud/vault/RetryTests.java +++ b/src/test/java/com/bettercloud/vault/RetryTests.java @@ -3,13 +3,11 @@ import com.bettercloud.vault.response.LogicalResponse; import com.bettercloud.vault.vault.VaultTestUtils; import com.bettercloud.vault.vault.mock.RetriesMockVault; +import java.util.HashMap; import org.eclipse.jetty.server.Server; import org.junit.Test; -import java.util.HashMap; - import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** *

    Unit tests for the Vault driver, having no dependency on an actual Vault server instance being available. The diff --git a/src/test/java/com/bettercloud/vault/SSLTests.java b/src/test/java/com/bettercloud/vault/SSLTests.java index 553bc2fd..5f64073f 100644 --- a/src/test/java/com/bettercloud/vault/SSLTests.java +++ b/src/test/java/com/bettercloud/vault/SSLTests.java @@ -3,9 +3,6 @@ import com.bettercloud.vault.response.LogicalResponse; import com.bettercloud.vault.vault.VaultTestUtils; import com.bettercloud.vault.vault.mock.MockVault; -import org.eclipse.jetty.server.Server; -import org.junit.Test; - import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; @@ -13,6 +10,8 @@ import java.io.InputStreamReader; import java.security.KeyStore; import java.util.HashMap; +import org.eclipse.jetty.server.Server; +import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/src/test/java/com/bettercloud/vault/VaultConfigTests.java b/src/test/java/com/bettercloud/vault/VaultConfigTests.java index 423276e1..3a49a45b 100644 --- a/src/test/java/com/bettercloud/vault/VaultConfigTests.java +++ b/src/test/java/com/bettercloud/vault/VaultConfigTests.java @@ -1,8 +1,5 @@ package com.bettercloud.vault; -import org.junit.Assert; -import org.junit.Test; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -14,6 +11,8 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; +import org.junit.Assert; +import org.junit.Test; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; diff --git a/src/test/java/com/bettercloud/vault/VaultTests.java b/src/test/java/com/bettercloud/vault/VaultTests.java index 5b4c4354..ad52f4bf 100644 --- a/src/test/java/com/bettercloud/vault/VaultTests.java +++ b/src/test/java/com/bettercloud/vault/VaultTests.java @@ -3,15 +3,12 @@ import com.bettercloud.vault.response.LogicalResponse; import com.bettercloud.vault.vault.VaultTestUtils; import com.bettercloud.vault.vault.mock.MockVault; +import java.util.HashMap; +import java.util.Map; import org.eclipse.jetty.server.Server; import org.junit.Assert; import org.junit.Test; -import java.util.HashMap; -import java.util.Map; - -import static junit.framework.TestCase.assertEquals; - /** * Unit tests for the various Vault constructors. diff --git a/src/test/java/com/bettercloud/vault/api/pki/CredentialTests.java b/src/test/java/com/bettercloud/vault/api/pki/CredentialTests.java index 4cc2486a..4b947c36 100644 --- a/src/test/java/com/bettercloud/vault/api/pki/CredentialTests.java +++ b/src/test/java/com/bettercloud/vault/api/pki/CredentialTests.java @@ -1,6 +1,5 @@ package com.bettercloud.vault.api.pki; -import com.bettercloud.vault.api.pki.Credential; import org.junit.Assert; import org.junit.Test; 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 02ab478a..57361f3c 100644 --- a/src/test/java/com/bettercloud/vault/api/pki/RoleOptionsTests.java +++ b/src/test/java/com/bettercloud/vault/api/pki/RoleOptionsTests.java @@ -1,10 +1,9 @@ package com.bettercloud.vault.api.pki; +import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; -import java.util.ArrayList; - public class RoleOptionsTests { @Test diff --git a/src/test/java/com/bettercloud/vault/json/JsonArray_Test.java b/src/test/java/com/bettercloud/vault/json/JsonArray_Test.java index f1e51033..1a20e1a1 100644 --- a/src/test/java/com/bettercloud/vault/json/JsonArray_Test.java +++ b/src/test/java/com/bettercloud/vault/json/JsonArray_Test.java @@ -21,22 +21,23 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static com.bettercloud.vault.json.TestUtil.assertException; -import static org.junit.Assert.*; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; - import java.io.IOException; -import java.io.StringReader; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; + @SuppressWarnings("PMD") public class JsonArray_Test { diff --git a/src/test/java/com/bettercloud/vault/json/JsonLiteral_Test.java b/src/test/java/com/bettercloud/vault/json/JsonLiteral_Test.java index 371082ea..a2677722 100644 --- a/src/test/java/com/bettercloud/vault/json/JsonLiteral_Test.java +++ b/src/test/java/com/bettercloud/vault/json/JsonLiteral_Test.java @@ -21,14 +21,23 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static com.bettercloud.vault.json.Json.*; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - import java.io.IOException; - import org.junit.Test; +import static com.bettercloud.vault.json.Json.FALSE; +import static com.bettercloud.vault.json.Json.NULL; +import static com.bettercloud.vault.json.Json.TRUE; +import static com.bettercloud.vault.json.Json.value; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + @SuppressWarnings("PMD") public class JsonLiteral_Test { 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 9978fe90..21923cf4 100644 --- a/src/test/java/com/bettercloud/vault/json/JsonNumber_Test.java +++ b/src/test/java/com/bettercloud/vault/json/JsonNumber_Test.java @@ -21,15 +21,16 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static org.junit.Assert.*; - import java.io.IOException; import java.io.StringWriter; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + @SuppressWarnings("PMD") public class JsonNumber_Test { diff --git a/src/test/java/com/bettercloud/vault/json/JsonObject_Test.java b/src/test/java/com/bettercloud/vault/json/JsonObject_Test.java index 1ec3a78e..a0018f16 100644 --- a/src/test/java/com/bettercloud/vault/json/JsonObject_Test.java +++ b/src/test/java/com/bettercloud/vault/json/JsonObject_Test.java @@ -21,22 +21,25 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static org.junit.Assert.*; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; - +import com.bettercloud.vault.json.JsonObject.HashIndexTable; +import com.bettercloud.vault.json.JsonObject.Member; import java.io.IOException; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; - import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; -import com.bettercloud.vault.json.JsonObject.HashIndexTable; -import com.bettercloud.vault.json.JsonObject.Member; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; @SuppressWarnings("PMD") diff --git a/src/test/java/com/bettercloud/vault/json/JsonParser_Test.java b/src/test/java/com/bettercloud/vault/json/JsonParser_Test.java index 77e14e26..a9514bdc 100644 --- a/src/test/java/com/bettercloud/vault/json/JsonParser_Test.java +++ b/src/test/java/com/bettercloud/vault/json/JsonParser_Test.java @@ -21,15 +21,16 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static com.bettercloud.vault.json.TestUtil.assertException; -import static org.junit.Assert.*; - import java.io.IOException; import java.io.StringReader; - import org.hamcrest.core.StringStartsWith; import org.junit.Test; +import static com.bettercloud.vault.json.TestUtil.assertException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; + @SuppressWarnings("PMD") public class JsonParser_Test { diff --git a/src/test/java/com/bettercloud/vault/json/JsonString_Test.java b/src/test/java/com/bettercloud/vault/json/JsonString_Test.java index 72cec838..a6b49f4f 100644 --- a/src/test/java/com/bettercloud/vault/json/JsonString_Test.java +++ b/src/test/java/com/bettercloud/vault/json/JsonString_Test.java @@ -21,15 +21,16 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static org.junit.Assert.*; - import java.io.IOException; import java.io.StringWriter; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + @SuppressWarnings("PMD") public class JsonString_Test { diff --git a/src/test/java/com/bettercloud/vault/json/JsonValue_Test.java b/src/test/java/com/bettercloud/vault/json/JsonValue_Test.java index 25dd31e4..9fb8eb8a 100644 --- a/src/test/java/com/bettercloud/vault/json/JsonValue_Test.java +++ b/src/test/java/com/bettercloud/vault/json/JsonValue_Test.java @@ -21,15 +21,17 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - import java.io.IOException; import java.io.StringWriter; import java.io.Writer; - import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + @SuppressWarnings("PMD") public class JsonValue_Test { diff --git a/src/test/java/com/bettercloud/vault/json/JsonWriter_Test.java b/src/test/java/com/bettercloud/vault/json/JsonWriter_Test.java index acf53ea2..7c6bc43d 100644 --- a/src/test/java/com/bettercloud/vault/json/JsonWriter_Test.java +++ b/src/test/java/com/bettercloud/vault/json/JsonWriter_Test.java @@ -21,14 +21,13 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.io.StringWriter; - import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + @SuppressWarnings("PMD") public class JsonWriter_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 33fea3be..2390945f 100644 --- a/src/test/java/com/bettercloud/vault/json/Json_Test.java +++ b/src/test/java/com/bettercloud/vault/json/Json_Test.java @@ -21,16 +21,16 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static com.bettercloud.vault.json.TestUtil.assertException; -import static org.junit.Assert.*; - +import com.bettercloud.vault.json.TestUtil.RunnableEx; import java.io.IOException; import java.io.Reader; import java.io.StringReader; - import org.junit.Test; -import com.bettercloud.vault.json.TestUtil.RunnableEx; +import static com.bettercloud.vault.json.TestUtil.assertException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; @SuppressWarnings("PMD") diff --git a/src/test/java/com/bettercloud/vault/json/ParseException_Test.java b/src/test/java/com/bettercloud/vault/json/ParseException_Test.java index 0bd7ba6f..e4730a4b 100644 --- a/src/test/java/com/bettercloud/vault/json/ParseException_Test.java +++ b/src/test/java/com/bettercloud/vault/json/ParseException_Test.java @@ -21,10 +21,10 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static org.junit.Assert.assertEquals; - import org.junit.Test; +import static org.junit.Assert.assertEquals; + @SuppressWarnings("PMD") public class ParseException_Test { diff --git a/src/test/java/com/bettercloud/vault/json/PrettyPrint_Test.java b/src/test/java/com/bettercloud/vault/json/PrettyPrint_Test.java index a12017b3..310793d2 100644 --- a/src/test/java/com/bettercloud/vault/json/PrettyPrint_Test.java +++ b/src/test/java/com/bettercloud/vault/json/PrettyPrint_Test.java @@ -21,18 +21,22 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static com.bettercloud.vault.json.PrettyPrint.*; -import static java.util.Locale.US; -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; - import java.io.IOException; import java.io.StringWriter; import java.io.Writer; - import org.junit.Before; import org.junit.Test; +import static com.bettercloud.vault.json.PrettyPrint.indentWithSpaces; +import static com.bettercloud.vault.json.PrettyPrint.indentWithTabs; +import static com.bettercloud.vault.json.PrettyPrint.singleLine; +import static java.util.Locale.US; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; + @SuppressWarnings("PMD") public class PrettyPrint_Test { diff --git a/src/test/java/com/bettercloud/vault/json/TestUtil.java b/src/test/java/com/bettercloud/vault/json/TestUtil.java index 8ffd4af4..a13e9b5c 100644 --- a/src/test/java/com/bettercloud/vault/json/TestUtil.java +++ b/src/test/java/com/bettercloud/vault/json/TestUtil.java @@ -21,15 +21,15 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + @SuppressWarnings("PMD") class TestUtil { diff --git a/src/test/java/com/bettercloud/vault/json/WritingBuffer_Test.java b/src/test/java/com/bettercloud/vault/json/WritingBuffer_Test.java index 9c64cbcf..f9fd5403 100644 --- a/src/test/java/com/bettercloud/vault/json/WritingBuffer_Test.java +++ b/src/test/java/com/bettercloud/vault/json/WritingBuffer_Test.java @@ -21,15 +21,14 @@ ******************************************************************************/ package com.bettercloud.vault.json; -import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.io.StringWriter; import java.util.Arrays; - import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + @SuppressWarnings("PMD") public class WritingBuffer_Test { diff --git a/src/test/java/com/bettercloud/vault/json/test/mocking/Mocking_Test.java b/src/test/java/com/bettercloud/vault/json/test/mocking/Mocking_Test.java index 0aee974c..9a6862c6 100644 --- a/src/test/java/com/bettercloud/vault/json/test/mocking/Mocking_Test.java +++ b/src/test/java/com/bettercloud/vault/json/test/mocking/Mocking_Test.java @@ -21,15 +21,14 @@ ******************************************************************************/ package com.bettercloud.vault.json.test.mocking; -import static org.junit.Assert.assertNotNull; - import com.bettercloud.vault.json.JsonArray; -import org.junit.Test; -import org.mockito.Mockito; - import com.bettercloud.vault.json.JsonObject; import com.bettercloud.vault.json.JsonValue; import com.bettercloud.vault.json.ParseException; +import org.junit.Test; +import org.mockito.Mockito; + +import static org.junit.Assert.assertNotNull; /** diff --git a/src/test/java/com/bettercloud/vault/rest/DeleteTests.java b/src/test/java/com/bettercloud/vault/rest/DeleteTests.java index 7d105835..442dda71 100644 --- a/src/test/java/com/bettercloud/vault/rest/DeleteTests.java +++ b/src/test/java/com/bettercloud/vault/rest/DeleteTests.java @@ -4,11 +4,10 @@ import com.bettercloud.vault.json.JsonObject; import com.bettercloud.vault.vault.VaultTestUtils; import com.bettercloud.vault.vault.mock.EchoInputMockVault; +import java.io.UnsupportedEncodingException; import org.eclipse.jetty.server.Server; import org.junit.Test; -import java.io.UnsupportedEncodingException; - import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertNull; diff --git a/src/test/java/com/bettercloud/vault/rest/GetTests.java b/src/test/java/com/bettercloud/vault/rest/GetTests.java index 32d760d5..66a0c083 100644 --- a/src/test/java/com/bettercloud/vault/rest/GetTests.java +++ b/src/test/java/com/bettercloud/vault/rest/GetTests.java @@ -2,11 +2,12 @@ import com.bettercloud.vault.json.Json; import com.bettercloud.vault.json.JsonObject; -import org.junit.Test; - import java.nio.charset.StandardCharsets; +import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /** * Unit tests relating the REST client processing of GET requests. diff --git a/src/test/java/com/bettercloud/vault/rest/PostTests.java b/src/test/java/com/bettercloud/vault/rest/PostTests.java index 1ae185bc..acde3a54 100644 --- a/src/test/java/com/bettercloud/vault/rest/PostTests.java +++ b/src/test/java/com/bettercloud/vault/rest/PostTests.java @@ -2,11 +2,11 @@ import com.bettercloud.vault.json.Json; import com.bettercloud.vault.json.JsonObject; -import org.junit.Test; - import java.nio.charset.StandardCharsets; +import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /** * Unit tests relating the REST client processing of POST requests. diff --git a/src/test/java/com/bettercloud/vault/rest/PutTests.java b/src/test/java/com/bettercloud/vault/rest/PutTests.java index bab5a637..e983e7f1 100644 --- a/src/test/java/com/bettercloud/vault/rest/PutTests.java +++ b/src/test/java/com/bettercloud/vault/rest/PutTests.java @@ -2,9 +2,8 @@ import com.bettercloud.vault.json.Json; import com.bettercloud.vault.json.JsonObject; -import org.junit.Test; - import java.nio.charset.StandardCharsets; +import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; diff --git a/src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java b/src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java index eb189bc1..066b721b 100644 --- a/src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java +++ b/src/test/java/com/bettercloud/vault/vault/VaultTestUtils.java @@ -3,6 +3,11 @@ import com.bettercloud.vault.json.Json; import com.bettercloud.vault.json.JsonObject; import com.bettercloud.vault.vault.mock.MockVault; +import java.io.IOException; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; @@ -13,12 +18,6 @@ import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.Collections; -import java.util.Map; -import java.util.Optional; - import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; diff --git a/src/test/java/com/bettercloud/vault/vault/api/AuthBackendAwsTests.java b/src/test/java/com/bettercloud/vault/vault/api/AuthBackendAwsTests.java index d3d14d63..431f055b 100644 --- a/src/test/java/com/bettercloud/vault/vault/api/AuthBackendAwsTests.java +++ b/src/test/java/com/bettercloud/vault/vault/api/AuthBackendAwsTests.java @@ -7,12 +7,11 @@ import com.bettercloud.vault.response.AuthResponse; import com.bettercloud.vault.vault.VaultTestUtils; import com.bettercloud.vault.vault.mock.AuthRequestValidatingMockVault; +import java.util.function.Predicate; +import javax.servlet.http.HttpServletRequest; import org.eclipse.jetty.server.Server; import org.junit.Test; -import javax.servlet.http.HttpServletRequest; -import java.util.function.Predicate; - import static com.bettercloud.vault.vault.VaultTestUtils.readRequestBody; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; diff --git a/src/test/java/com/bettercloud/vault/vault/api/AuthLookupTest.java b/src/test/java/com/bettercloud/vault/vault/api/AuthLookupTest.java index b1aa2462..3a9385ce 100644 --- a/src/test/java/com/bettercloud/vault/vault/api/AuthLookupTest.java +++ b/src/test/java/com/bettercloud/vault/vault/api/AuthLookupTest.java @@ -7,13 +7,12 @@ import com.bettercloud.vault.response.LookupResponse; import com.bettercloud.vault.vault.VaultTestUtils; import com.bettercloud.vault.vault.mock.MockVault; +import java.util.Optional; import org.eclipse.jetty.server.Server; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.util.Optional; - import static org.junit.Assert.assertEquals; public class AuthLookupTest { diff --git a/src/test/java/com/bettercloud/vault/vault/api/AuthLookupWrapTest.java b/src/test/java/com/bettercloud/vault/vault/api/AuthLookupWrapTest.java index 6b49fc91..868c30f5 100644 --- a/src/test/java/com/bettercloud/vault/vault/api/AuthLookupWrapTest.java +++ b/src/test/java/com/bettercloud/vault/vault/api/AuthLookupWrapTest.java @@ -6,13 +6,12 @@ import com.bettercloud.vault.response.LogicalResponse; import com.bettercloud.vault.vault.VaultTestUtils; import com.bettercloud.vault.vault.mock.MockVault; +import java.util.Optional; import org.eclipse.jetty.server.Server; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.util.Optional; - import static org.junit.Assert.assertEquals; public class AuthLookupWrapTest { 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 0e47f78b..e1599a8f 100644 --- a/src/test/java/com/bettercloud/vault/vault/mock/AuthRequestValidatingMockVault.java +++ b/src/test/java/com/bettercloud/vault/vault/mock/AuthRequestValidatingMockVault.java @@ -1,11 +1,10 @@ package com.bettercloud.vault.vault.mock; -import org.eclipse.jetty.server.Request; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.function.Predicate; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.server.Request; public class AuthRequestValidatingMockVault extends MockVault { private Predicate validator; diff --git a/src/test/java/com/bettercloud/vault/vault/mock/EchoInputMockVault.java b/src/test/java/com/bettercloud/vault/vault/mock/EchoInputMockVault.java index 42f8573d..c8aef6af 100644 --- a/src/test/java/com/bettercloud/vault/vault/mock/EchoInputMockVault.java +++ b/src/test/java/com/bettercloud/vault/vault/mock/EchoInputMockVault.java @@ -2,12 +2,11 @@ import com.bettercloud.vault.json.Json; import com.bettercloud.vault.json.JsonObject; -import org.eclipse.jetty.server.Request; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Enumeration; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.server.Request; /** *

    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()); } /**