use SystemLambda instead of custom environment mocks

This commit is contained in:
Stefan Kalscheuer 2021-03-29 20:49:44 +02:00
parent 639d0e3c5b
commit c43ec190ca
4 changed files with 105 additions and 132 deletions

View File

@ -138,6 +138,12 @@
<version>3.8.0</version> <version>3.8.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-lambda</artifactId>
<version>1.2.0</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
@ -286,7 +292,7 @@
<plugin> <plugin>
<groupId>org.owasp</groupId> <groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId> <artifactId>dependency-check-maven</artifactId>
<version>6.0.5</version> <version>6.1.3</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>

View File

@ -16,17 +16,18 @@
package de.stklcode.jvault.connector.builder; package de.stklcode.jvault.connector.builder;
import com.github.stefanbirkner.systemlambda.SystemLambda;
import de.stklcode.jvault.connector.HTTPVaultConnector; import de.stklcode.jvault.connector.HTTPVaultConnector;
import de.stklcode.jvault.connector.exception.TlsException; import de.stklcode.jvault.connector.exception.TlsException;
import de.stklcode.jvault.connector.test.EnvironmentMock;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.nio.file.NoSuchFileException; import java.nio.file.NoSuchFileException;
import java.util.concurrent.Callable;
import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@ -50,59 +51,68 @@ class HTTPVaultConnectorBuilderTest {
* Test building from environment variables * Test building from environment variables
*/ */
@Test @Test
void testFromEnv() throws NoSuchFieldException, IllegalAccessException, IOException { void testFromEnv() throws Exception {
/* Provide address only should be enough */ /* Provide address only should be enough */
setenv(VAULT_ADDR, null, null, null); withVaultEnv(VAULT_ADDR, null, null, null).execute(() -> {
HTTPVaultConnectorBuilder factory = assertDoesNotThrow( HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> VaultConnectorBuilder.http().fromEnv(), () -> VaultConnectorBuilder.http().fromEnv(),
"Factory creation from minimal environment failed" "Factory creation from minimal environment failed"
); );
HTTPVaultConnector connector = factory.build(); HTTPVaultConnector connector = builder.build();
assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/"))); assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/")));
assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue()));
assertThat("Non-default number of retries, when none set", getRequestHelperPrivate(connector, "retries"), is(0)); assertThat("Non-default number of retries, when none set", getRequestHelperPrivate(connector, "retries"), is(0));
return null;
});
/* Provide address and number of retries */ /* Provide address and number of retries */
setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null); withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null).execute(() -> {
HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> VaultConnectorBuilder.http().fromEnv(),
"Factory creation from environment failed"
);
HTTPVaultConnector connector = builder.build();
factory = assertDoesNotThrow( assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/")));
() -> VaultConnectorBuilder.http().fromEnv(), assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue()));
"Factory creation from environment failed" assertThat("Number of retries not set correctly", getRequestHelperPrivate(connector, "retries"), is(VAULT_MAX_RETRIES));
);
connector = factory.build();
assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/"))); return null;
assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); });
assertThat("Number of retries not set correctly", getRequestHelperPrivate(connector, "retries"), is(VAULT_MAX_RETRIES));
/* Provide CA certificate */ /* Provide CA certificate */
String VAULT_CACERT = tempDir.toString() + "/doesnotexist"; String VAULT_CACERT = tempDir.toString() + "/doesnotexist";
setenv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null); withVaultEnv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null).execute(() -> {
TlsException e = assertThrows(
TlsException.class,
() -> VaultConnectorBuilder.http().fromEnv(),
"Creation with unknown cert path failed."
);
assertThat(e.getCause(), is(instanceOf(NoSuchFileException.class)));
assertThat(((NoSuchFileException) e.getCause()).getFile(), is(VAULT_CACERT));
TlsException e = assertThrows( return null;
TlsException.class, });
() -> VaultConnectorBuilder.http().fromEnv(),
"Creation with unknown cert path failed."
);
assertThat(e.getCause(), is(instanceOf(NoSuchFileException.class)));
assertThat(((NoSuchFileException) e.getCause()).getFile(), is(VAULT_CACERT));
/* Automatic authentication */ /* Automatic authentication */
setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN); withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> {
HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> VaultConnectorBuilder.http().fromEnv(),
"Factory creation from minimal environment failed"
);
assertThat("Token nor set correctly", getPrivate(builder, "token"), is(equalTo(VAULT_TOKEN)));
factory = assertDoesNotThrow( return null;
() -> VaultConnectorBuilder.http().fromEnv(), });
"Factory creation from minimal environment failed"
);
assertThat("Token nor set correctly", getPrivate(factory, "token"), is(equalTo(VAULT_TOKEN)));
} }
private void setenv(String vault_addr, String vault_cacert, String vault_max_retries, String vault_token) { private SystemLambda.WithEnvironmentVariables withVaultEnv(String vault_addr, String vault_cacert, String vault_max_retries, String vault_token) {
EnvironmentMock.setenv("VAULT_ADDR", vault_addr); return withEnvironmentVariable("VAULT_ADDR", vault_addr)
EnvironmentMock.setenv("VAULT_CACERT", vault_cacert); .and("VAULT_CACERT", vault_cacert)
EnvironmentMock.setenv("VAULT_MAX_RETRIES", vault_max_retries); .and("VAULT_MAX_RETRIES", vault_max_retries)
EnvironmentMock.setenv("VAULT_TOKEN", vault_token); .and("VAULT_TOKEN", vault_token);
} }
private Object getRequestHelperPrivate(HTTPVaultConnector connector, String fieldName) throws NoSuchFieldException, IllegalAccessException { private Object getRequestHelperPrivate(HTTPVaultConnector connector, String fieldName) throws NoSuchFieldException, IllegalAccessException {

View File

@ -16,17 +16,17 @@
package de.stklcode.jvault.connector.factory; package de.stklcode.jvault.connector.factory;
import com.github.stefanbirkner.systemlambda.SystemLambda;
import de.stklcode.jvault.connector.HTTPVaultConnector; import de.stklcode.jvault.connector.HTTPVaultConnector;
import de.stklcode.jvault.connector.exception.TlsException; import de.stklcode.jvault.connector.exception.TlsException;
import de.stklcode.jvault.connector.test.EnvironmentMock;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.nio.file.NoSuchFileException; import java.nio.file.NoSuchFileException;
import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@ -50,60 +50,68 @@ class HTTPVaultConnectorFactoryTest {
* Test building from environment variables * Test building from environment variables
*/ */
@Test @Test
void testFromEnv() throws NoSuchFieldException, IllegalAccessException, IOException { void testFromEnv() throws Exception {
/* Provide address only should be enough */ /* Provide address only should be enough */
setenv(VAULT_ADDR, null, null, null); withVaultEnv(VAULT_ADDR, null, null, null).execute(() -> {
HTTPVaultConnectorFactory factory = assertDoesNotThrow(
() -> VaultConnectorFactory.httpFactory().fromEnv(),
"Factory creation from minimal environment failed"
);
HTTPVaultConnector connector = factory.build();
HTTPVaultConnectorFactory factory = assertDoesNotThrow( assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/")));
() -> VaultConnectorFactory.httpFactory().fromEnv(), assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue()));
"Factory creation from minimal environment failed" assertThat("Non-default number of retries, when none set", getRequestHelperPrivate(connector, "retries"), is(0));
);
HTTPVaultConnector connector = factory.build();
assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/"))); return null;
assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); });
assertThat("Non-default number of retries, when none set", getRequestHelperPrivate(connector, "retries"), is(0));
/* Provide address and number of retries */ /* Provide address and number of retries */
setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null); withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null).execute(() -> {
HTTPVaultConnectorFactory factory = assertDoesNotThrow(
() -> VaultConnectorFactory.httpFactory().fromEnv(),
"Factory creation from environment failed"
);
HTTPVaultConnector connector = factory.build();
factory = assertDoesNotThrow( assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/")));
() -> VaultConnectorFactory.httpFactory().fromEnv(), assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue()));
"Factory creation from environment failed" assertThat("Number of retries not set correctly", getRequestHelperPrivate(connector, "retries"), is(VAULT_MAX_RETRIES));
);
connector = factory.build();
assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/"))); return null;
assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); });
assertThat("Number of retries not set correctly", getRequestHelperPrivate(connector, "retries"), is(VAULT_MAX_RETRIES));
/* Provide CA certificate */ /* Provide CA certificate */
String VAULT_CACERT = tempDir.toString() + "/doesnotexist"; String VAULT_CACERT = tempDir.toString() + "/doesnotexist";
setenv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null); withVaultEnv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null).execute(() -> {
TlsException e = assertThrows(
TlsException.class,
() -> VaultConnectorFactory.httpFactory().fromEnv(),
"Creation with unknown cert path failed."
);
assertThat(e.getCause(), is(instanceOf(NoSuchFileException.class)));
assertThat(((NoSuchFileException) e.getCause()).getFile(), is(VAULT_CACERT));
TlsException e = assertThrows( return null;
TlsException.class, });
() -> VaultConnectorFactory.httpFactory().fromEnv(),
"Creation with unknown cert path failed."
);
assertThat(e.getCause(), is(instanceOf(NoSuchFileException.class)));
assertThat(((NoSuchFileException) e.getCause()).getFile(), is(VAULT_CACERT));
/* Automatic authentication */ /* Automatic authentication */
setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN); withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> {
HTTPVaultConnectorFactory factory = assertDoesNotThrow(
() -> VaultConnectorFactory.httpFactory().fromEnv(),
"Factory creation from minimal environment failed"
);
assertThat("Token nor set correctly", getPrivate(getPrivate(factory, "delegate"), "token"), is(equalTo(VAULT_TOKEN)));
factory = assertDoesNotThrow( return null;
() -> VaultConnectorFactory.httpFactory().fromEnv(), });
"Factory creation from minimal environment failed"
);
assertThat("Token nor set correctly", getPrivate(getPrivate(factory, "delegate"), "token"), is(equalTo(VAULT_TOKEN)));
} }
private void setenv(String vault_addr, String vault_cacert, String vault_max_retries, String vault_token) { private SystemLambda.WithEnvironmentVariables withVaultEnv(String vault_addr, String vault_cacert, String vault_max_retries, String vault_token) {
EnvironmentMock.setenv("VAULT_ADDR", vault_addr); return withEnvironmentVariable("VAULT_ADDR", vault_addr)
EnvironmentMock.setenv("VAULT_CACERT", vault_cacert); .and("VAULT_CACERT", vault_cacert)
EnvironmentMock.setenv("VAULT_MAX_RETRIES", vault_max_retries); .and("VAULT_MAX_RETRIES", vault_max_retries)
EnvironmentMock.setenv("VAULT_TOKEN", vault_token); .and("VAULT_TOKEN", vault_token);
} }
private Object getRequestHelperPrivate(HTTPVaultConnector connector, String fieldName) throws NoSuchFieldException, IllegalAccessException { private Object getRequestHelperPrivate(HTTPVaultConnector connector, String fieldName) throws NoSuchFieldException, IllegalAccessException {

View File

@ -1,51 +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.test;
import java.lang.reflect.Field;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Test helper to modify system environment.
*
* @author Stefan Kalscheuer
*/
@SuppressWarnings("unchecked")
public class EnvironmentMock {
private static Map<String, String> environment;
static {
try {
Map<String, String> originalEnv = System.getenv();
Field mapField = originalEnv.getClass().getDeclaredField("m");
mapField.setAccessible(true);
environment = (Map<String, String>) mapField.get(originalEnv);
} catch (NoSuchFieldException | IllegalAccessException | ClassCastException e) {
fail("Failed to intercept unmodifiable system environment");
}
}
public static void setenv(String key, String value) {
if (value != null) {
environment.put(key, value);
} else {
environment.remove(key);
}
}
}