enforce use of builder to create a new HTTPVaultConnector (#54)
All checks were successful
continuous-integration/drone/push Build is passing

Remove constructors of HTTPVaultConnector and make the builder
constructor package-private to enforce use of .builder()....build()

For convenience we add direct builder constructors with a full URI
argument to allow a one-line initialization if necessary.
This commit is contained in:
Stefan Kalscheuer 2021-06-12 12:01:52 +02:00 committed by GitHub
parent 71564e87e8
commit 3c11fe912b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 109 additions and 259 deletions

View File

@ -12,7 +12,7 @@ Java Vault Connector is a connector library for [Vault](https://www.vaultproject
## Features: ## Features:
* HTTP(S) backend connector * HTTP(S) backend connector
* Ability to provide or enforce custom CA certificate * Ability to provide or enforce custom CA certificate
* Optional initialization from environment variables * Optional initialization from environment variables
* Authorization methods * Authorization methods
* Token * Token
@ -40,7 +40,7 @@ Java Vault Connector is a connector library for [Vault](https://www.vaultproject
<dependency> <dependency>
<groupId>de.stklcode.jvault</groupId> <groupId>de.stklcode.jvault</groupId>
<artifactId>jvault-connector</artifactId> <artifactId>jvault-connector</artifactId>
<version>0.9.4</version> <version>1.0.0-SNAPSHOTf</version>
</dependency> </dependency>
``` ```
@ -50,21 +50,19 @@ Java Vault Connector is a connector library for [Vault](https://www.vaultproject
```java ```java
// Instantiate using builder pattern style factory (TLS enabled by default) // Instantiate using builder pattern style factory (TLS enabled by default)
VaultConnector vault = VaultConnectorBuilder.http() VaultConnector vault = HTTPVaultConnector.builder()
.withHost("127.0.0.1") .withHost("127.0.0.1")
.withPort(8200) .withPort(8200)
.withTLS() .withTLS()
.build(); .build();
// Instantiate with custom SSL context // Instantiate with custom SSL context
VaultConnector vault = VaultConnectorBuilder.http() VaultConnector vault = HTTPVaultConnector.builder("https://example.com:8200/v1/")
.withHost("example.com")
.withPort(8200)
.withTrustedCA(Paths.get("/path/to/CA.pem")) .withTrustedCA(Paths.get("/path/to/CA.pem"))
.build(); .build();
// Initialization from environment variables // Initialization from environment variables
VaultConnector vault = VaultConnectorBuilder.http() VaultConnector vault = HTTPVaultConnector.builder()
.fromEnv() .fromEnv()
.build(); .build();
``` ```

View File

@ -24,7 +24,8 @@ import de.stklcode.jvault.connector.model.*;
import de.stklcode.jvault.connector.model.response.*; import de.stklcode.jvault.connector.model.response.*;
import de.stklcode.jvault.connector.model.response.embedded.AuthMethod; import de.stklcode.jvault.connector.model.response.embedded.AuthMethod;
import java.security.cert.X509Certificate; import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -40,7 +41,6 @@ import static java.util.Collections.singletonMap;
* @since 0.1 * @since 0.1
*/ */
public class HTTPVaultConnector implements VaultConnector { public class HTTPVaultConnector implements VaultConnector {
private static final String PATH_PREFIX = "/v1/";
private static final String PATH_SEAL_STATUS = "sys/seal-status"; private static final String PATH_SEAL_STATUS = "sys/seal-status";
private static final String PATH_SEAL = "sys/seal"; private static final String PATH_SEAL = "sys/seal";
private static final String PATH_UNSEAL = "sys/unseal"; private static final String PATH_UNSEAL = "sys/unseal";
@ -82,71 +82,26 @@ public class HTTPVaultConnector implements VaultConnector {
} }
/** /**
* Create connector using hostname and schema. * Get a new builder for a connector.
* *
* @param hostname The hostname * @param baseURL Base URL.
* @param useTLS If TRUE, use HTTPS, otherwise HTTP * @return Builder instance.
* @throws URISyntaxException Invalid URI syntax.
* @since 1.0
*/ */
public HTTPVaultConnector(final String hostname, final boolean useTLS) { public static HTTPVaultConnectorBuilder builder(String baseURL) throws URISyntaxException {
this(hostname, useTLS, null); return new HTTPVaultConnectorBuilder().withBaseURL(baseURL);
} }
/** /**
* Create connector using hostname, schema and port. * Get a new builder for a connector.
* *
* @param hostname The hostname * @param baseURL Base URL.
* @param useTLS If TRUE, use HTTPS, otherwise HTTP * @return Builder instance.
* @param port The port * @since 1.0
*/ */
public HTTPVaultConnector(final String hostname, final boolean useTLS, final Integer port) { public static HTTPVaultConnectorBuilder builder(URI baseURL) {
this(hostname, useTLS, port, PATH_PREFIX); return new HTTPVaultConnectorBuilder().withBaseURL(baseURL);
}
/**
* Create connector using hostname, schema, port and path.
*
* @param hostname The hostname
* @param useTLS If TRUE, use HTTPS, otherwise HTTP
* @param port The port
* @param prefix HTTP API prefix (default: /v1/)
*/
public HTTPVaultConnector(final String hostname, final boolean useTLS, final Integer port, final String prefix) {
this(((useTLS) ? "https" : "http")
+ "://" + hostname
+ ((port != null) ? ":" + port : "")
+ prefix);
}
/**
* Create connector using hostname, schema, port, path and trusted certificate.
*
* @param hostname The hostname
* @param useTLS If TRUE, use HTTPS, otherwise HTTP
* @param tlsVersion TLS version
* @param port The port
* @param prefix HTTP API prefix (default: /v1/)
* @param trustedCaCert Trusted CA certificate
* @param numberOfRetries Number of retries on 5xx errors
* @param timeout Timeout for HTTP requests (milliseconds)
*/
public HTTPVaultConnector(final String hostname,
final boolean useTLS,
final String tlsVersion,
final Integer port,
final String prefix,
final X509Certificate trustedCaCert,
final int numberOfRetries,
final Integer timeout) {
this(
((useTLS) ? "https" : "http")
+ "://" + hostname
+ ((port != null) ? ":" + port : "")
+ prefix,
trustedCaCert,
numberOfRetries,
timeout,
tlsVersion
);
} }
/** /**
@ -154,7 +109,7 @@ public class HTTPVaultConnector implements VaultConnector {
* *
* @param builder The builder. * @param builder The builder.
*/ */
public HTTPVaultConnector(final HTTPVaultConnectorBuilder builder) { HTTPVaultConnector(final HTTPVaultConnectorBuilder builder) {
this.request = new RequestHelper( this.request = new RequestHelper(
((builder.isWithTLS()) ? "https" : "http") + "://" + ((builder.isWithTLS()) ? "https" : "http") + "://" +
builder.getHost() + builder.getHost() +
@ -167,68 +122,6 @@ public class HTTPVaultConnector implements VaultConnector {
); );
} }
/**
* Create connector using full URL.
*
* @param baseURL The URL
*/
public HTTPVaultConnector(final String baseURL) {
this(baseURL, null);
}
/**
* Create connector using full URL and trusted certificate.
*
* @param baseURL The URL
* @param trustedCaCert Trusted CA certificate
*/
public HTTPVaultConnector(final String baseURL, final X509Certificate trustedCaCert) {
this(baseURL, trustedCaCert, 0, null);
}
/**
* Create connector using full URL and trusted certificate.
*
* @param baseURL The URL
* @param trustedCaCert Trusted CA certificate
* @param numberOfRetries Number of retries on 5xx errors
*/
public HTTPVaultConnector(final String baseURL, final X509Certificate trustedCaCert, final int numberOfRetries) {
this(baseURL, trustedCaCert, numberOfRetries, null);
}
/**
* Create connector using full URL and trusted certificate.
*
* @param baseURL The URL
* @param trustedCaCert Trusted CA certificate
* @param numberOfRetries Number of retries on 5xx errors
* @param timeout Timeout for HTTP requests (milliseconds)
*/
public HTTPVaultConnector(final String baseURL,
final X509Certificate trustedCaCert,
final int numberOfRetries,
final Integer timeout) {
this(baseURL, trustedCaCert, numberOfRetries, timeout, DEFAULT_TLS_VERSION);
}
/**
* Create connector using full URL and trusted certificate.
*
* @param baseURL The URL
* @param trustedCaCert Trusted CA certificate
* @param numberOfRetries Number of retries on 5xx errors
* @param timeout Timeout for HTTP requests (milliseconds)
* @param tlsVersion TLS Version.
*/
public HTTPVaultConnector(final String baseURL,
final X509Certificate trustedCaCert,
final int numberOfRetries,
final Integer timeout,
final String tlsVersion) {
this.request = new RequestHelper(baseURL, numberOfRetries, timeout, tlsVersion, trustedCaCert);
}
@Override @Override
public final void resetAuth() { public final void resetAuth() {
token = null; token = null;

View File

@ -16,13 +16,14 @@
package de.stklcode.jvault.connector; package de.stklcode.jvault.connector;
import de.stklcode.jvault.connector.builder.VaultConnectorBuilder;
import de.stklcode.jvault.connector.exception.ConnectionException; import de.stklcode.jvault.connector.exception.ConnectionException;
import de.stklcode.jvault.connector.exception.TlsException; import de.stklcode.jvault.connector.exception.TlsException;
import de.stklcode.jvault.connector.exception.VaultConnectorException; import de.stklcode.jvault.connector.exception.VaultConnectorException;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
@ -30,6 +31,7 @@ import java.nio.file.Paths;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory; import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.Objects;
/** /**
* Vault Connector Builder implementation for HTTP Vault connectors. * Vault Connector Builder implementation for HTTP Vault connectors.
@ -37,7 +39,7 @@ import java.security.cert.X509Certificate;
* @author Stefan Kalscheuer * @author Stefan Kalscheuer
* @since 0.8.0 * @since 0.8.0
*/ */
public final class HTTPVaultConnectorBuilder implements VaultConnectorBuilder { public final class HTTPVaultConnectorBuilder {
private static final String ENV_VAULT_ADDR = "VAULT_ADDR"; private static final String ENV_VAULT_ADDR = "VAULT_ADDR";
private static final String ENV_VAULT_CACERT = "VAULT_CACERT"; private static final String ENV_VAULT_CACERT = "VAULT_CACERT";
private static final String ENV_VAULT_TOKEN = "VAULT_TOKEN"; private static final String ENV_VAULT_TOKEN = "VAULT_TOKEN";
@ -73,6 +75,32 @@ public final class HTTPVaultConnectorBuilder implements VaultConnectorBuilder {
numberOfRetries = DEFAULT_NUMBER_OF_RETRIES; numberOfRetries = DEFAULT_NUMBER_OF_RETRIES;
} }
/**
* Set base URL, e.g. "protocol://host:port/prefix".
*
* @param baseURL Base URL
* @return self
* @throws URISyntaxException Invalid URI syntax.
* @since 1.0
*/
public HTTPVaultConnectorBuilder withBaseURL(final String baseURL) throws URISyntaxException {
return withBaseURL(new URI(baseURL));
}
/**
* Set base URL, e.g. "protocol://host:port/prefix".
*
* @param baseURL Base URL
* @return self
* @since 1.0
*/
public HTTPVaultConnectorBuilder withBaseURL(final URI baseURL) {
return withTLS(!("http".equalsIgnoreCase(Objects.requireNonNullElse(baseURL.getScheme(), ""))))
.withHost(baseURL.getHost())
.withPort(baseURL.getPort())
.withPrefix(baseURL.getPath());
}
/** /**
* Set hostname (default: 127.0.0.1). * Set hostname (default: 127.0.0.1).
* *
@ -95,12 +123,20 @@ public final class HTTPVaultConnectorBuilder implements VaultConnectorBuilder {
/** /**
* Set port (default: 8200). * Set port (default: 8200).
* A value of {@code null} or {@code -1} indicates that no port is specified, i.e. the protocol default is used.
* Otherwise a valid port number bwetween 1 and 65535 is expected.
* *
* @param port Vault TCP port * @param port Vault TCP port
* @return self * @return self
*/ */
public HTTPVaultConnectorBuilder withPort(final Integer port) { public HTTPVaultConnectorBuilder withPort(final Integer port) {
this.port = port; if (port < 0) {
this.port = null;
} else if(port < 1 || port > 65535) {
throw new IllegalArgumentException("Port number " + port + " out of range");
} else {
this.port = port;
}
return this; return this;
} }
@ -341,7 +377,6 @@ public final class HTTPVaultConnectorBuilder implements VaultConnectorBuilder {
* *
* @return Vault Connector instance. * @return Vault Connector instance.
*/ */
@Override
public HTTPVaultConnector build() { public HTTPVaultConnector build() {
return new HTTPVaultConnector(this); return new HTTPVaultConnector(this);
} }
@ -353,7 +388,6 @@ public final class HTTPVaultConnectorBuilder implements VaultConnectorBuilder {
* @throws VaultConnectorException if authentication failed * @throws VaultConnectorException if authentication failed
* @since 0.6.0 * @since 0.6.0
*/ */
@Override
public HTTPVaultConnector buildAndAuth() throws VaultConnectorException { public HTTPVaultConnector buildAndAuth() throws VaultConnectorException {
if (token == null) { if (token == null) {
throw new ConnectionException("No vault token provided, unable to authenticate."); throw new ConnectionException("No vault token provided, unable to authenticate.");

View File

@ -1,60 +0,0 @@
/*
* Copyright 2016-2021 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.stklcode.jvault.connector.builder;
import de.stklcode.jvault.connector.HTTPVaultConnector;
import de.stklcode.jvault.connector.HTTPVaultConnectorBuilder;
import de.stklcode.jvault.connector.VaultConnector;
import de.stklcode.jvault.connector.exception.VaultConnectorException;
/**
* Abstract Vault Connector Builder interface.
* Provides builder style for Vault connectors.
*
* @author Stefan Kalscheuer
* @since 0.8.0
* @deprecated Builder interface is no longer maintained. Use {@link HTTPVaultConnector#builder()} for instantiation.
*/
@Deprecated(forRemoval = true)
public interface VaultConnectorBuilder {
/**
* Get Factory implementation for HTTP Vault Connector.
*
* @return HTTP Connector Factory
* @deprecated use {@link HTTPVaultConnector#builder()} instead.
*/
@Deprecated(forRemoval = true)
static HTTPVaultConnectorBuilder http() {
return HTTPVaultConnector.builder();
}
/**
* Build command, produces connector after initialization.
*
* @return Vault Connector instance.
*/
VaultConnector build();
/**
* Build connector and authenticate with token set in factory or from environment.
*
* @return Authenticated Vault connector instance.
* @throws VaultConnectorException if authentication failed
* @since 0.6.0
*/
VaultConnector buildAndAuth() throws VaultConnectorException;
}

View File

@ -1,22 +0,0 @@
/*
* Copyright 2016-2021 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package contains the {@link de.stklcode.jvault.connector.builder.VaultConnectorBuilder} to initialize a
* connector instance.
*/
@Deprecated(forRemoval = true)
package de.stklcode.jvault.connector.builder;

View File

@ -57,7 +57,7 @@ public final class RequestHelper implements Serializable {
final Integer timeout, final Integer timeout,
final String tlsVersion, final String tlsVersion,
final X509Certificate trustedCaCert) { final X509Certificate trustedCaCert) {
this.baseURL = baseURL; this.baseURL = baseURL + (baseURL.endsWith("/") ? "" : "/");
this.retries = retries; this.retries = retries;
this.timeout = timeout; this.timeout = timeout;
this.tlsVersion = tlsVersion; this.tlsVersion = tlsVersion;

View File

@ -24,6 +24,7 @@ import org.junit.jupiter.api.io.TempDir;
import java.io.File; import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.nio.file.NoSuchFileException; import java.nio.file.NoSuchFileException;
import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable; import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable;
@ -70,6 +71,24 @@ class HTTPVaultConnectorBuilderTest {
assertEquals(9, getRequestHelperPrivate(connector, "retries"), "Unexpected number of retries"); assertEquals(9, getRequestHelperPrivate(connector, "retries"), "Unexpected number of retries");
assertEquals(5678, getRequestHelperPrivate(connector, "timeout"), "Number timeout value"); assertEquals(5678, getRequestHelperPrivate(connector, "timeout"), "Number timeout value");
assertThrows(ConnectionException.class, builder::buildAndAuth, "Immediate authentication should throw exception without token"); assertThrows(ConnectionException.class, builder::buildAndAuth, "Immediate authentication should throw exception without token");
/* Initialization from URL */
assertThrows(
URISyntaxException.class,
() -> HTTPVaultConnector.builder().withBaseURL("foo:/\\1nv4l1d_UrL"),
"Initialization from invalid URL should fail"
);
connector = assertDoesNotThrow(
() -> HTTPVaultConnector.builder().withBaseURL("https://vault3.example.com:5678/bar/").build(),
"Initialization from valid URL should not fail"
);
assertEquals("https://vault3.example.com:5678/bar/", getRequestHelperPrivate(connector, "baseURL"), "URL not set correctly");
/* Port numbers */
assertThrows(IllegalArgumentException.class, () -> HTTPVaultConnector.builder().withPort(65536), "Too large port number should throw an exception");
assertThrows(IllegalArgumentException.class, () -> HTTPVaultConnector.builder().withPort(0), "Port number 0 should throw an exception");
builder = assertDoesNotThrow(() -> HTTPVaultConnector.builder().withPort(-1), "Port number -1 should not throw an exception");
assertNull(builder.getPort(), "Port number -1 should be omitted");
} }
/** /**

View File

@ -19,7 +19,10 @@ package de.stklcode.jvault.connector;
import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import de.stklcode.jvault.connector.exception.*; import de.stklcode.jvault.connector.exception.ConnectionException;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.exception.PermissionDeniedException;
import de.stklcode.jvault.connector.exception.VaultConnectorException;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -29,6 +32,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.URISyntaxException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory; import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
@ -51,8 +55,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
* @since 0.7.0 * @since 0.7.0
*/ */
class HTTPVaultConnectorOfflineTest { class HTTPVaultConnectorOfflineTest {
private static final String INVALID_URL = "foo:/\\1nv4l1d_UrL";
private static WireMockServer wireMock; private static WireMockServer wireMock;
@BeforeAll @BeforeAll
@ -73,8 +75,8 @@ class HTTPVaultConnectorOfflineTest {
* Test exceptions thrown during request. * Test exceptions thrown during request.
*/ */
@Test @Test
void requestExceptionTest() throws IOException { void requestExceptionTest() throws IOException, URISyntaxException {
HTTPVaultConnector connector = new HTTPVaultConnector(wireMock.url("/"), null, 0, 250); HTTPVaultConnector connector = HTTPVaultConnector.builder(wireMock.url("/")).withTimeout(250).build();
// Test invalid response code. // Test invalid response code.
final int responseCode = 400; final int responseCode = 400;
@ -98,7 +100,7 @@ class HTTPVaultConnectorOfflineTest {
// Test exception thrown during request. // Test exception thrown during request.
try (ServerSocket s = new ServerSocket(0)) { try (ServerSocket s = new ServerSocket(0)) {
connector = new HTTPVaultConnector("http://localst:" + s.getLocalPort() + "/", null, 0, 250); connector = HTTPVaultConnector.builder("http://localst:" + s.getLocalPort() + "/").withTimeout(250).build();
} }
e = assertThrows( e = assertThrows(
ConnectionException.class, ConnectionException.class,
@ -109,7 +111,7 @@ class HTTPVaultConnectorOfflineTest {
assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class)); assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class));
// Now simulate a failing request that succeeds on second try. // Now simulate a failing request that succeeds on second try.
connector = new HTTPVaultConnector(wireMock.url("/"), null, 1, 250); connector = HTTPVaultConnector.builder(wireMock.url("/")).withNumberOfRetries(1).withTimeout(250).build();
WireMock.stubFor( WireMock.stubFor(
WireMock.any(anyUrl()) WireMock.any(anyUrl())
@ -125,13 +127,13 @@ class HTTPVaultConnectorOfflineTest {
* Test constructors of the {@link HTTPVaultConnector} class. * Test constructors of the {@link HTTPVaultConnector} class.
*/ */
@Test @Test
void constructorTest() throws IOException, CertificateException { void constructorTest() throws IOException, CertificateException, URISyntaxException {
final String url = "https://vault.example.net/test/"; final String url = "https://vault.example.net/test/";
final String hostname = "vault.example.com"; final String hostname = "vault.example.com";
final Integer port = 1337; final Integer port = 1337;
final String prefix = "/custom/prefix/"; final String prefix = "/custom/prefix/";
final int retries = 42; final int retries = 42;
final String expectedNoTls = "http://" + hostname + "/v1/"; final String expectedNoTls = "http://" + hostname + ":8200/v1/";
final String expectedCustomPort = "https://" + hostname + ":" + port + "/v1/"; final String expectedCustomPort = "https://" + hostname + ":" + port + "/v1/";
final String expectedCustomPrefix = "https://" + hostname + ":" + port + prefix; final String expectedCustomPrefix = "https://" + hostname + ":" + port + prefix;
X509Certificate trustedCaCert; X509Certificate trustedCaCert;
@ -141,30 +143,30 @@ class HTTPVaultConnectorOfflineTest {
} }
// Most basic constructor expects complete URL. // Most basic constructor expects complete URL.
HTTPVaultConnector connector = new HTTPVaultConnector(url); HTTPVaultConnector connector = HTTPVaultConnector.builder(url).build();
assertThat("Unexpected base URL", getRequestHelperPrivate(connector, "baseURL"), is(url)); assertThat("Unexpected base URL", getRequestHelperPrivate(connector, "baseURL"), is(url));
// Now override TLS usage. // Now override TLS usage.
connector = new HTTPVaultConnector(hostname, false); connector = HTTPVaultConnector.builder().withHost(hostname).withoutTLS().build();
assertThat("Unexpected base URL with TLS disabled", getRequestHelperPrivate(connector, "baseURL"), is(expectedNoTls)); assertThat("Unexpected base URL with TLS disabled", getRequestHelperPrivate(connector, "baseURL"), is(expectedNoTls));
// Specify custom port. // Specify custom port.
connector = new HTTPVaultConnector(hostname, true, port); connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).build();
assertThat("Unexpected base URL with custom port", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPort)); assertThat("Unexpected base URL with custom port", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPort));
// Specify custom prefix. // Specify custom prefix.
connector = new HTTPVaultConnector(hostname, true, port, prefix); connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).withPrefix(prefix).build();
assertThat("Unexpected base URL with custom prefix", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPrefix)); assertThat("Unexpected base URL with custom prefix", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPrefix));
assertThat("Trusted CA cert set, but not specified", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); assertThat("Trusted CA cert set, but not specified", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue()));
// Specify number of retries. // Specify number of retries.
connector = new HTTPVaultConnector(url, trustedCaCert, retries); connector = HTTPVaultConnector.builder(url).withTrustedCA(trustedCaCert).withNumberOfRetries(retries).build();
assertThat("Number of retries not set correctly", getRequestHelperPrivate(connector, "retries"), is(retries)); assertThat("Number of retries not set correctly", getRequestHelperPrivate(connector, "retries"), is(retries));
// Test TLS version (#22). // Test TLS version (#22).
assertThat("TLS version should be 1.2 if not specified", getRequestHelperPrivate(connector, "tlsVersion"), is("TLSv1.2")); assertThat("TLS version should be 1.2 if not specified", getRequestHelperPrivate(connector, "tlsVersion"), is("TLSv1.2"));
// Now override. // Now override.
connector = new HTTPVaultConnector(url, trustedCaCert, retries, null, "TLSv1.1"); connector = HTTPVaultConnector.builder(url).withTrustedCA(trustedCaCert).withNumberOfRetries(retries).withTLS("TLSv1.1").build();
assertThat("Overridden TLS version 1.1 not correct", getRequestHelperPrivate(connector, "tlsVersion"), is("TLSv1.1")); assertThat("Overridden TLS version 1.1 not correct", getRequestHelperPrivate(connector, "tlsVersion"), is("TLSv1.1"));
} }
@ -172,20 +174,13 @@ class HTTPVaultConnectorOfflineTest {
* This test is designed to test exceptions caught and thrown by seal-methods if Vault is not reachable. * This test is designed to test exceptions caught and thrown by seal-methods if Vault is not reachable.
*/ */
@Test @Test
void sealExceptionTest() throws IOException { void sealExceptionTest() throws IOException, URISyntaxException {
HTTPVaultConnector connector = new HTTPVaultConnector(INVALID_URL);
VaultConnectorException e = assertThrows(
InvalidRequestException.class,
connector::sealStatus,
"Querying seal status succeeded on invalid URL"
);
assertThat("Unexpected exception message", e.getMessage(), is("Invalid URI format"));
// Simulate no connection. // Simulate no connection.
VaultConnector connector;
try (ServerSocket s = new ServerSocket(0)) { try (ServerSocket s = new ServerSocket(0)) {
connector = new HTTPVaultConnector("http://localst:" + s.getLocalPort() + "/", null, 0, 250); connector = HTTPVaultConnector.builder("http://localst:" + s.getLocalPort()).withTimeout(250).build();
} }
e = assertThrows( ConnectionException e = assertThrows(
ConnectionException.class, ConnectionException.class,
connector::sealStatus, connector::sealStatus,
"Querying seal status succeeded on invalid instance" "Querying seal status succeeded on invalid instance"
@ -197,20 +192,13 @@ class HTTPVaultConnectorOfflineTest {
* This test is designed to test exceptions caught and thrown by seal-methods if Vault is not reachable. * This test is designed to test exceptions caught and thrown by seal-methods if Vault is not reachable.
*/ */
@Test @Test
void healthExceptionTest() throws IOException { void healthExceptionTest() throws IOException, URISyntaxException {
HTTPVaultConnector connector = new HTTPVaultConnector(INVALID_URL);
VaultConnectorException e = assertThrows(
InvalidRequestException.class,
connector::getHealth,
"Querying health status succeeded on invalid URL"
);
assertThat("Unexpected exception message", e.getMessage(), is("Invalid URI format"));
// Simulate no connection. // Simulate no connection.
HTTPVaultConnector connector;
try (ServerSocket s = new ServerSocket(0)) { try (ServerSocket s = new ServerSocket(0)) {
connector = new HTTPVaultConnector("http://localhost:" + s.getLocalPort() + "/", null, 0, 250); connector = HTTPVaultConnector.builder("http://localhost:" + s.getLocalPort() + "/").withTimeout(250).build();
} }
e = assertThrows( ConnectionException e = assertThrows(
ConnectionException.class, ConnectionException.class,
connector::getHealth, connector::getHealth,
"Querying health status succeeded on invalid instance" "Querying health status succeeded on invalid instance"
@ -222,8 +210,8 @@ class HTTPVaultConnectorOfflineTest {
* Test behavior on unparsable responses. * Test behavior on unparsable responses.
*/ */
@Test @Test
void parseExceptionTest() throws IOException { void parseExceptionTest() throws URISyntaxException {
HTTPVaultConnector connector = new HTTPVaultConnector(wireMock.url("/"), null, 0, 250); HTTPVaultConnector connector = HTTPVaultConnector.builder(wireMock.url("/")).withTimeout(250).build();
// Mock authorization. // Mock authorization.
setPrivate(connector, "authorized", true); setPrivate(connector, "authorized", true);
// Mock response. // Mock response.
@ -256,8 +244,8 @@ class HTTPVaultConnectorOfflineTest {
* Test requests that expect an empty response with code 204, but receive a 200 body. * Test requests that expect an empty response with code 204, but receive a 200 body.
*/ */
@Test @Test
void nonEmpty204ResponseTest() { void nonEmpty204ResponseTest() throws URISyntaxException {
HTTPVaultConnector connector = new HTTPVaultConnector(wireMock.url("/"), null, 0, 250); HTTPVaultConnector connector = HTTPVaultConnector.builder(wireMock.url("/")).withTimeout(250).build();
// Mock authorization. // Mock authorization.
setPrivate(connector, "authorized", true); setPrivate(connector, "authorized", true);
// Mock response. // Mock response.