Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add health codes #153

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ The driver is available from Maven Central, for all modern Java build systems.
Gradle:
```
dependencies {
compile('com.bettercloud:vault-java-driver:4.0.0')
compile('com.bettercloud:vault-java-driver:4.1.0')
}
```

Expand Down Expand Up @@ -249,11 +249,15 @@ Note that changes to the major version (i.e. the first number) represent possibl
may require modifications in your code to migrate. Changes to the minor version (i.e. the second number)
should represent non-breaking changes. The third number represents any very minor bugfix patches.

* **4.1.0**: New health code support:
* Adds support for the new [Vault health codes](https://www.vaultproject.io/api/system/health.html#parameters)

* **4.0.0**: This is a breaking-change release, with two primary updates:
* Adds support for Version 2 of the Key/Value Secrets Engine. The driver now assumes that your Vault instance uses Version 2 of the
Key/Value Secrets Engine across the board. To configure this, see the [Key/Value Secret Engine Config](#key-value-secret-engine-config)
section above.
* Adds support for the namespaces feature of Vault Enterprise.

* **3.1.0**: Several updates.
* Adds support for seal-related operations (i.e. `/sys/seal`, `/sys/unseal`, `/sys/seal-status`).
* Adds support for the AWS auth backend.
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ apply plugin: 'signing'

group 'com.bettercloud'
archivesBaseName = 'vault-java-driver'
version '4.0.0'
version '4.1.0'
ext.isReleaseVersion = !version.endsWith('SNAPSHOT')

compileJava {
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/bettercloud/vault/SslConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,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);
Expand All @@ -477,7 +477,7 @@ public SslConfig build() throws VaultException {
* @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) {
Expand Down
52 changes: 44 additions & 8 deletions src/main/java/com/bettercloud/vault/api/Debug.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ public Debug withNameSpace(final String nameSpace) {
* health check and provides a simple way to monitor the health of a Vault instance.</p>
*
* @return The response information returned from Vault
* @throws VaultException If any errors occurs with the REST request (e.g. non-200 status code, invalid JSON payload, etc), and the maximum number of retries is exceeded.
* @throws VaultException If any errors occurs with the REST request (e.g. non-200 status code, invalid JSON payload, etc),
* and the maximum number of retries is exceeded.
* @see <a href="https://www.vaultproject.io/docs/http/sys-health.html">https://www.vaultproject.io/docs/http/sys-health.html</a>
*
* <blockquote>
Expand All @@ -58,7 +59,21 @@ public Debug withNameSpace(final String nameSpace) {
* </blockquote>
*/
public HealthResponse health() throws VaultException {
return health(null, null, null, null);
return health(null, null, null, null, null,
null, null, null);
}

/**
* <p>A deprecated, overloaded version of {@link Debug#health()} that allows for passing one or more of the previous four optional parameters.</p>
* Please consider using the new constructor that adds support for perfStandbyOk, drSecondaryCode, etc/
*/
@Deprecated
public HealthResponse health(
final Boolean standbyOk,
final Integer activeCode,
final Integer standbyCode,
final Integer sealedCode) throws VaultException {
return health(standbyOk, activeCode, standbyCode, sealedCode, null, null, null, null);
}

/**
Expand All @@ -71,18 +86,26 @@ public HealthResponse health() throws VaultException {
* will need to check <code>HealthReponse.getRestResponse().getStatus()</code> to determine the result of
* the operation.</p>
*
* @param standbyOk (optional) Indicates that being a standby should still return the active status code instead of the standby code
* @param activeCode (optional) Indicates the status code that should be returned for an active node instead of the default of 200
* @param standbyCode (optional) Indicates the status code that should be returned for a standby node instead of the default of 429
* @param sealedCode (optional) Indicates the status code that should be returned for a sealed node instead of the default of 500
* @param standbyOk (optional) Indicates that being a standby should still return the active status code instead of the standby code
* @param activeCode (optional) Indicates the status code that should be returned for an active node instead of the default of 200
* @param standbyCode (optional) Indicates the status code that should be returned for a standby node instead of the default of 429
* @param sealedCode (optional) Indicates the status code that should be returned for a sealed node instead of the default of 500
* @param perfStandbyOk (optional) Specifies if being a performance standby should still return the active status code instead of the performance standby status code
* @param drSecondaryCode (optional) Indicates the status code that should be returned for a DR secondary node instead of the default of 472
* @param performanceStandbyCode (optional) Indicates the status code that should be returned for a performance standby node instead of the default of 473
* @param unInitCode (optional) Indicates the status code that should be returned for an uninitialized node instead of the default of 501
* @return The response information returned from Vault
* @throws VaultException If an error occurs or unexpected response received from Vault
*/
public HealthResponse health(
final Boolean standbyOk,
final Integer activeCode,
final Integer standbyCode,
final Integer sealedCode
final Integer sealedCode,
final Boolean perfStandbyOk,
final Integer drSecondaryCode,
final Integer performanceStandbyCode,
final Integer unInitCode
) throws VaultException {
final String path = "sys/health";
int retryCount = 0;
Expand All @@ -105,19 +128,32 @@ public HealthResponse health(
if (activeCode != null) rest.parameter("activecode", activeCode.toString());
if (standbyCode != null) rest.parameter("standbycode", standbyCode.toString());
if (sealedCode != null) rest.parameter("sealedcode", sealedCode.toString());
if (perfStandbyOk != null) rest.parameter("perfstandbyok", perfStandbyOk.toString());
if (drSecondaryCode != null) rest.parameter("drsecondarycode", drSecondaryCode.toString());
if (performanceStandbyCode != null)
rest.parameter("performancestandbycode", performanceStandbyCode.toString());
if (unInitCode != null) rest.parameter("uninitcode", unInitCode.toString());
// Execute request
final RestResponse restResponse = rest.get();

// Validate response
final Set<Integer> validCodes = new HashSet<>();//NOPMD
validCodes.add(200);
validCodes.add(429);
validCodes.add(472);
validCodes.add(473);
validCodes.add(500);
validCodes.add(501);
validCodes.add(503);
if (activeCode != null) validCodes.add(activeCode);
if (standbyCode != null) validCodes.add(standbyCode);
if (sealedCode != null) validCodes.add(sealedCode);
if (drSecondaryCode != null) validCodes.add(drSecondaryCode);
if (performanceStandbyCode != null) validCodes.add(performanceStandbyCode);
if (unInitCode != null) validCodes.add(unInitCode);
if (!validCodes.contains(restResponse.getStatus())) {
throw new VaultException("Vault responded with HTTP status code: " + restResponse.getStatus(), restResponse.getStatus());
throw new VaultException("Vault responded with HTTP status code: " + restResponse.getStatus(),
restResponse.getStatus());
}
return new HealthResponse(restResponse, retryCount);
} catch (RuntimeException | VaultException | RestException e) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/bettercloud/vault/api/Leases.java
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public VaultResponse renew(final String leaseId, final long increment) throws Va
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
.put();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was my previous mistake.


// Validate response
if (restResponse.getStatus() != 200) {
Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/bettercloud/vault/json/JsonObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public AuthResponse(final RestResponse restResponse, final int retries) {
for (final JsonValue authPolicy : authPoliciesJsonArray) {
authPolicies.add(authPolicy.asString());
}
} catch (ParseException e) {
} catch (ParseException ignored) {
}
}

Expand Down
26 changes: 24 additions & 2 deletions src/main/java/com/bettercloud/vault/response/HealthResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.bettercloud.vault.VaultException;
import com.bettercloud.vault.json.Json;
import com.bettercloud.vault.json.JsonObject;
import com.bettercloud.vault.json.JsonValue;
import com.bettercloud.vault.rest.RestResponse;

import java.io.Serializable;
Expand All @@ -21,6 +22,9 @@ public class HealthResponse implements Serializable {
private Boolean sealed;
private Boolean standby;
private Long serverTimeUTC;
private Boolean performanceStandby;
private String replicationPerformanceMode;
private String replicationDrMode;

/**
* <p>Constructs a <code>HealthResponse</code> object from the data received in a health
Expand All @@ -34,7 +38,7 @@ public class HealthResponse implements Serializable {
* {@link com.bettercloud.vault.api.Debug#health(Boolean, Integer, Integer, Integer)}.</p>
*
* @param restResponse The raw HTTP response from Vault
* @param retries The number of retry attempts that occurred during the API call (can be zero)
* @param retries The number of retry attempts that occurred during the API call (can be zero)
* @throws VaultException If any error occurs or unexpected response is received from Vault
*/
public HealthResponse(final RestResponse restResponse, final int retries) throws VaultException {
Expand All @@ -59,7 +63,14 @@ public HealthResponse(final RestResponse restResponse, final int retries) throws
this.sealed = jsonObject.get("sealed") == null ? null : jsonObject.get("sealed").asBoolean();
this.standby = jsonObject.get("standby") == null ? null : jsonObject.get("standby").asBoolean();
this.serverTimeUTC = jsonObject.get("server_time_utc") == null ? null : jsonObject.get("server_time_utc").asLong();
} catch(final Exception e) {
this.performanceStandby = jsonObject.get("performance_standby") == null ? null :
jsonObject.get("performance_standby").asBoolean();
this.replicationPerformanceMode = jsonObject.get("replication_performance_mode") == null ? null :
jsonObject.get("replication_performance_mode").asString();
this.replicationDrMode = jsonObject.get("replication_dr_mode") == null ? null :
jsonObject.get("replication_dr_mode").asString();

} catch (final Exception e) {
throw new VaultException("Unable to parse JSON payload: " + e, restResponse.getStatus());
}
}
Expand Down Expand Up @@ -93,4 +104,15 @@ public Long getServerTimeUTC() {
return serverTimeUTC;
}

public Boolean getPerformanceStandby() {
return performanceStandby;
}

public String getReplicationPerformanceMode() {
return replicationPerformanceMode;
}

public String getReplicationDrMode() {
return replicationDrMode;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.bettercloud.vault.VaultException;
import com.bettercloud.vault.response.HealthResponse;
import com.bettercloud.vault.util.VaultContainer;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
Expand All @@ -12,6 +13,7 @@
import java.io.IOException;

import static junit.framework.TestCase.*;
import static org.junit.Assert.assertNotEquals;

/**
* <p>Integration tests for the debug-related operations on the Vault HTTP API's.</p>
Expand Down Expand Up @@ -44,12 +46,29 @@ public void testHealth_Plain() throws VaultException {
assertEquals(200, response.getRestResponse().getStatus());
}

@Test
public void testHealth_Sealed() throws VaultException {
vault.seal().seal();
final HealthResponse response = vault.debug().health();

assertTrue(response.getInitialized());
assertTrue(response.getSealed());
assertTrue(response.getStandby());
assertNotNull(response.getServerTimeUTC());
assertEquals(503, response.getRestResponse().getStatus());
assertFalse(response.getPerformanceStandby());
assertNotEquals("disabled", response.getReplicationPerformanceMode());
assertNotEquals("disabled", response.getReplicationDrMode());
container.getRootVault().seal().unseal(container.getUnsealKey());
}

@Test
public void testHealth_WithParams() throws VaultException {
final HealthResponse response = vault.debug().health(null, 212, null, null);
final HealthResponse response = vault.debug().health(null, 212, null, null, null, null, null, null);
assertTrue(response.getInitialized());
assertFalse(response.getSealed());
assertFalse(response.getStandby());
assertFalse(response.getPerformanceStandby());
assertNotNull(response.getServerTimeUTC());
assertEquals(212, response.getRestResponse().getStatus());
}
Expand All @@ -66,11 +85,30 @@ public void testHealth_WithParams() throws VaultException {
@Test
public void testHealth_WonkyActiveCode() throws VaultException {
final HealthResponse response = vault.debug().health(null, 204, null,
null);
null, null, null, null, null);
assertNull(response.getInitialized());
assertNull(response.getSealed());
assertNull(response.getStandby());
assertNull(response.getServerTimeUTC());
assertNull(response.getPerformanceStandby());
assertNull(response.getReplicationDrMode());
assertNull(response.getReplicationPerformanceMode());
assertEquals(204, response.getRestResponse().getStatus());
}

@Test
public void testHealth_WonkySealedCode() throws VaultException {
vault.seal().seal();
final HealthResponse response = vault.debug().health(null, null, null,
900, null, null, null, null);
assertTrue(response.getInitialized());
assertTrue(response.getSealed());
assertTrue(response.getStandby());
assertNotNull(response.getServerTimeUTC());
assertFalse(response.getPerformanceStandby());
assertNotNull(response.getReplicationDrMode());
assertNotNull(response.getReplicationPerformanceMode());
assertEquals(900, response.getRestResponse().getStatus());
container.getRootVault().seal().unseal(container.getUnsealKey());
}
}
1 change: 0 additions & 1 deletion src/test/java/com/bettercloud/vault/RetryTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.util.HashMap;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
* <p>Unit tests for the Vault driver, having no dependency on an actual Vault server instance being available. The
Expand Down
6 changes: 3 additions & 3 deletions src/test/java/com/bettercloud/vault/VaultConfigTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public String loadVariable(final String name) {
try {
final byte[] bytes = Files.readAllBytes(Paths.get(mockHomeDirectory).resolve(".vault-token"));
value = new String(bytes, StandardCharsets.UTF_8).trim();
} catch (IOException e) {
} catch (IOException ignored) {
}
}
} else {
Expand Down Expand Up @@ -154,8 +154,8 @@ public void testConfigBuilder_LoadFromEnv() throws VaultException {
assertEquals("http://127.0.0.1:8200", config.getAddress());
assertEquals("c24e2469-298a-6c64-6a71-5b47c9ba459a", config.getToken());
assertTrue(config.getSslConfig().isVerify());
assertTrue(30 == config.getOpenTimeout());
assertTrue(30 == config.getReadTimeout());
assertEquals(30, (int) config.getOpenTimeout());
assertEquals(30, (int) config.getReadTimeout());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 0 additions & 2 deletions src/test/java/com/bettercloud/vault/json/JsonArray_Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,11 @@
******************************************************************************/
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading