Add Checkstyle integration.

Closes gh-276.
This commit is contained in:
Mark Paluch
2019-02-07 10:32:31 +01:00
parent 4ff0f8ab68
commit b35ebbeac3
111 changed files with 1252 additions and 837 deletions

16
.editorconfig Normal file
View File

@@ -0,0 +1,16 @@
root = true
[*.java]
indent_style = tab
indent_size = 4
continuation_indent_size = 8
[*.groovy]
indent_style = tab
indent_size = 4
continuation_indent_size = 8
[*.xml]
indent_style = tab
indent_size = 4
continuation_indent_size = 8

27
pom.xml
View File

@@ -127,6 +127,12 @@
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>8.12</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
@@ -185,6 +191,17 @@
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
@@ -229,6 +246,16 @@
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
<profiles>
<profile>
<id>sonar</id>

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.aws;
import javax.validation.constraints.NotEmpty;
@@ -60,4 +61,5 @@ public class VaultAwsProperties implements VaultSecretBackendDescriptor {
*/
@NotEmpty
private String secretKeyProperty = "cloud.aws.credentials.secretKey";
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.aws;
import java.util.HashMap;
@@ -68,7 +69,6 @@ public class VaultConfigAwsBootstrapConfiguration {
* property names to names provided with
* {@link VaultAwsProperties#getAccessKeyProperty()} and
* {@link VaultAwsProperties#getSecretKeyProperty()}.
*
* @param properties must not be {@literal null}.
* @return the {@link SecretBackendMetadata}
*/
@@ -113,5 +113,7 @@ public class VaultConfigAwsBootstrapConfiguration {
}
};
}
}
}

View File

@@ -2,4 +2,5 @@
* AWS integration with Vault.
* @author Mark Paluch
*/
package org.springframework.cloud.vault.config.aws;
package org.springframework.cloud.vault.config.aws;

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.aws;
import java.util.Collections;
@@ -30,9 +31,9 @@ import org.springframework.cloud.vault.util.Settings;
import org.springframework.util.StringUtils;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.cloud.vault.config.aws.VaultConfigAwsBootstrapConfiguration.AwsSecretBackendMetadataFactory.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.config.aws.VaultConfigAwsBootstrapConfiguration.AwsSecretBackendMetadataFactory.forAws;
/**
* Integration tests for {@link VaultConfigTemplate} using the aws secret backend. This
@@ -43,14 +44,18 @@ import static org.springframework.cloud.vault.config.aws.VaultConfigAwsBootstrap
*/
public class AwsSecretIntegrationTests extends IntegrationTestSupport {
private final static String AWS_REGION = "eu-west-1";
private final static String AWS_ACCESS_KEY = System.getProperty("aws.access.key");
private final static String AWS_SECRET_KEY = System.getProperty("aws.secret.key");
private static final String AWS_REGION = "eu-west-1";
private final static String ARN = "arn:aws:iam::aws:policy/ReadOnlyAccess";
private static final String AWS_ACCESS_KEY = System.getProperty("aws.access.key");
private static final String AWS_SECRET_KEY = System.getProperty("aws.secret.key");
private static final String ARN = "arn:aws:iam::aws:policy/ReadOnlyAccess";
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigOperations configOperations;
private VaultAwsProperties aws = new VaultAwsProperties();
/**
@@ -62,11 +67,11 @@ public class AwsSecretIntegrationTests extends IntegrationTestSupport {
assumeTrue(StringUtils.hasText(AWS_ACCESS_KEY)
&& StringUtils.hasText(AWS_SECRET_KEY));
aws.setEnabled(true);
aws.setRole("readonly");
this.aws.setEnabled(true);
this.aws.setRole("readonly");
if (!prepare().hasSecretBackend(aws.getBackend())) {
prepare().mountSecret(aws.getBackend());
if (!prepare().hasSecretBackend(this.aws.getBackend())) {
prepare().mountSecret(this.aws.getBackend());
}
VaultOperations vaultOperations = prepare().getVaultOperations();
@@ -76,23 +81,25 @@ public class AwsSecretIntegrationTests extends IntegrationTestSupport {
connection.put("access_key", AWS_ACCESS_KEY);
connection.put("secret_key", AWS_SECRET_KEY);
vaultOperations.write(String.format("%s/config/root", aws.getBackend()),
vaultOperations.write(String.format("%s/config/root", this.aws.getBackend()),
connection);
vaultOperations.write(
String.format("%s/roles/%s", aws.getBackend(), aws.getRole()),
String.format("%s/roles/%s", this.aws.getBackend(), this.aws.getRole()),
Collections.singletonMap("arn", ARN));
configOperations = new VaultConfigTemplate(vaultOperations, vaultProperties);
this.configOperations = new VaultConfigTemplate(vaultOperations,
this.vaultProperties);
}
@Test
public void shouldCreateCredentialsCorrectly() {
Map<String, Object> secretProperties = configOperations.read(forAws(aws))
.getData();
Map<String, Object> secretProperties = this.configOperations
.read(forAws(this.aws)).getData();
assertThat(secretProperties).containsKeys("cloud.aws.credentials.accessKey",
"cloud.aws.credentials.secretKey");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.aws;
import org.junit.Test;
@@ -52,10 +53,10 @@ public class VaultConfigAwsBootstrapConfigurationTests extends IntegrationTestSu
@Test
public void shouldApplyCustomConfiguration() {
SecretBackendMetadata metadata = factory.createMetadata(properties);
SecretBackendMetadata metadata = this.factory.createMetadata(this.properties);
assertThat(metadata).isInstanceOf(GenericSecretBackendMetadata.class);
assertThat(metadata.getPath()).isEqualTo(properties.getRole());
assertThat(metadata.getPath()).isEqualTo(this.properties.getRole());
}
@Configuration
@@ -74,5 +75,7 @@ public class VaultConfigAwsBootstrapConfigurationTests extends IntegrationTestSu
}
};
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.aws;
import java.util.Collections;
@@ -32,8 +33,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StringUtils;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the aws secret backend. In case this test should fail because
@@ -54,11 +55,13 @@ import static org.junit.Assume.*;
"cloud.aws.region.auto=false", "cloud.aws.region.static=eu-west-1" })
public class VaultConfigAwsTests {
private final static String AWS_REGION = "eu-west-1";
private final static String AWS_ACCESS_KEY = System.getProperty("aws.access.key");
private final static String AWS_SECRET_KEY = System.getProperty("aws.secret.key");
private static final String AWS_REGION = "eu-west-1";
private final static String ARN = "arn:aws:iam::aws:policy/ReadOnlyAccess";
private static final String AWS_ACCESS_KEY = System.getProperty("aws.access.key");
private static final String AWS_SECRET_KEY = System.getProperty("aws.secret.key");
private static final String ARN = "arn:aws:iam::aws:policy/ReadOnlyAccess";
/**
* Initialize the aws secret backend.
@@ -97,8 +100,8 @@ public class VaultConfigAwsTests {
@Test
public void shouldInitializeAwsProperties() {
assertThat(accessKey).isNotEmpty();
assertThat(secretKey).isNotEmpty();
assertThat(this.accessKey).isNotEmpty();
assertThat(this.secretKey).isNotEmpty();
}
@SpringBootApplication
@@ -107,5 +110,7 @@ public class VaultConfigAwsTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.consul;
import java.util.HashMap;
@@ -66,12 +67,10 @@ public class VaultConfigConsulBootstrapConfiguration {
* Creates a {@link SecretBackendMetadata} for a secret backend using
* {@link VaultConsulProperties}. This accessor transforms Vault's token property
* names to names provided with {@link VaultConsulProperties#getTokenProperty()}.
*
* @param properties must not be {@literal null}.
* @return the {@link SecretBackendMetadata}
*/
static SecretBackendMetadata forConsul(
final VaultConsulProperties properties) {
static SecretBackendMetadata forConsul(final VaultConsulProperties properties) {
Assert.notNull(properties, "VaultConsulProperties must not be null");
@@ -109,5 +108,7 @@ public class VaultConfigConsulBootstrapConfiguration {
}
};
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.consul;
import javax.validation.constraints.NotEmpty;
@@ -54,4 +55,5 @@ public class VaultConsulProperties implements VaultSecretBackendDescriptor {
*/
@NotEmpty
private String tokenProperty = "spring.cloud.consul.token";
}

View File

@@ -2,4 +2,5 @@
* Consul integration with Vault.
* @author Mark Paluch
*/
package org.springframework.cloud.vault.config.consul;
package org.springframework.cloud.vault.config.consul;

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.consul;
import java.net.InetSocketAddress;
@@ -38,9 +39,9 @@ import org.springframework.util.Base64Utils;
import org.springframework.vault.core.VaultOperations;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.cloud.vault.config.consul.VaultConfigConsulBootstrapConfiguration.ConsulSecretBackendMetadataFactory.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.config.consul.VaultConfigConsulBootstrapConfiguration.ConsulSecretBackendMetadataFactory.forConsul;
/**
* Integration tests for {@link VaultConfigTemplate} using the consul secret backend. This
@@ -50,21 +51,26 @@ import static org.springframework.cloud.vault.config.consul.VaultConfigConsulBoo
*/
public class ConsulSecretIntegrationTests extends IntegrationTestSupport {
private final static String CONSUL_HOST = "localhost";
private final static int CONSUL_PORT = 8500;
private static final String CONSUL_HOST = "localhost";
private final static String CONNECTION_URL = String.format("%s:%d", CONSUL_HOST,
private static final int CONSUL_PORT = 8500;
private static final String CONNECTION_URL = String.format("%s:%d", CONSUL_HOST,
CONSUL_PORT);
private final static String POLICY = "key \"\" { policy = \"read\" }";
private final static String CONSUL_ACL_MASTER_TOKEN = "consul-master-token";
private static final String POLICY = "key \"\" { policy = \"read\" }";
private final static ParameterizedTypeReference<Map<String, String>> STRING_MAP = new ParameterizedTypeReference<Map<String, String>>() {
private static final String CONSUL_ACL_MASTER_TOKEN = "consul-master-token";
private static final ParameterizedTypeReference<Map<String, String>> STRING_MAP = new ParameterizedTypeReference<Map<String, String>>() {
};
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigOperations configOperations;
private VaultConsulProperties consul = new VaultConsulProperties();
private RestTemplate restTemplate = new RestTemplate();
/**
@@ -75,20 +81,20 @@ public class ConsulSecretIntegrationTests extends IntegrationTestSupport {
assumeTrue(CanConnect.to(new InetSocketAddress(CONSUL_HOST, CONSUL_PORT)));
consul.setEnabled(true);
consul.setRole("readonly");
this.consul.setEnabled(true);
this.consul.setRole("readonly");
if (!prepare().hasSecretBackend(consul.getBackend())) {
prepare().mountSecret(consul.getBackend());
if (!prepare().hasSecretBackend(this.consul.getBackend())) {
prepare().mountSecret(this.consul.getBackend());
}
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
VaultOperations vaultOperations = this.vaultRule.prepare().getVaultOperations();
HttpHeaders headers = new HttpHeaders();
headers.add("X-Consul-Token", CONSUL_ACL_MASTER_TOKEN);
HttpEntity<String> requestEntity = new HttpEntity<>(
"{\"Name\": \"sample\", \"Type\": \"management\"}", headers);
ResponseEntity<Map<String, String>> tokenResponse = restTemplate.exchange(
ResponseEntity<Map<String, String>> tokenResponse = this.restTemplate.exchange(
"http://{host}:{port}/v1/acl/create", HttpMethod.PUT, requestEntity,
STRING_MAP, CONSUL_HOST, CONSUL_PORT);
@@ -96,23 +102,26 @@ public class ConsulSecretIntegrationTests extends IntegrationTestSupport {
consulAccess.put("address", CONNECTION_URL);
consulAccess.put("token", tokenResponse.getBody().get("ID"));
vaultOperations.write(String.format("%s/config/access", consul.getBackend()),
vaultOperations.write(String.format("%s/config/access", this.consul.getBackend()),
consulAccess);
vaultOperations.write(
String.format("%s/roles/%s", consul.getBackend(), consul.getRole()),
String.format("%s/roles/%s", this.consul.getBackend(),
this.consul.getRole()),
Collections.singletonMap("policy",
Base64Utils.encodeToString(POLICY.getBytes())));
configOperations = new VaultConfigTemplate(vaultOperations, vaultProperties);
this.configOperations = new VaultConfigTemplate(vaultOperations,
this.vaultProperties);
}
@Test
public void shouldCreateCredentialsCorrectly() {
Map<String, Object> secretProperties = configOperations.read(forConsul(consul))
.getData();
Map<String, Object> secretProperties = this.configOperations
.read(forConsul(this.consul)).getData();
assertThat(secretProperties).containsKeys("spring.cloud.consul.token");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.consul;
import java.net.InetSocketAddress;
@@ -49,8 +50,9 @@ import static org.junit.Assume.assumeTrue;
@Ignore("Consul discovery client is set up in the main context, no longer in the bootstrap context")
public class DiscoveryBootstrapConfigurationTests extends IntegrationTestSupport {
private final static String CONSUL_HOST = "localhost";
private final static int CONSUL_PORT = 8500;
private static final String CONSUL_HOST = "localhost";
private static final int CONSUL_PORT = 8500;
@Autowired
VaultOperations vaultOperations;
@@ -80,8 +82,9 @@ public class DiscoveryBootstrapConfigurationTests extends IntegrationTestSupport
@Test
public void shouldDiscoverThroughConsul() {
VaultHealth health = vaultOperations.opsForSys().health();
VaultHealth health = this.vaultOperations.opsForSys().health();
assertThat(health).isNotNull();
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.consul;
import org.junit.Test;
@@ -53,10 +54,10 @@ public class VaultConfigConsulBootstrapConfigurationTests extends IntegrationTes
@Test
public void shouldApplyCustomConfiguration() {
SecretBackendMetadata metadata = factory.createMetadata(properties);
SecretBackendMetadata metadata = this.factory.createMetadata(this.properties);
assertThat(metadata).isInstanceOf(GenericSecretBackendMetadata.class);
assertThat(metadata.getPath()).isEqualTo(properties.getRole());
assertThat(metadata.getPath()).isEqualTo(this.properties.getRole());
}
@Configuration
@@ -70,10 +71,12 @@ public class VaultConfigConsulBootstrapConfigurationTests extends IntegrationTes
@Override
public SecretBackendMetadata createMetadata(
VaultConsulProperties backendDescriptor) {
return GenericSecretBackendMetadata.create(backendDescriptor
.getRole());
return GenericSecretBackendMetadata
.create(backendDescriptor.getRole());
}
};
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.consul;
import java.net.InetSocketAddress;
@@ -40,8 +41,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Java6Assertions.*;
import static org.junit.Assume.*;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the consul secret backend. In case this test should fail
@@ -57,16 +58,18 @@ import static org.junit.Assume.*;
"spring.cloud.vault.consul.role=readonly" })
public class VaultConfigConsulTests {
private final static String CONSUL_HOST = "localhost";
private final static int CONSUL_PORT = 8500;
private static final String CONSUL_HOST = "localhost";
private final static String CONNECTION_URL = String.format("%s:%d", CONSUL_HOST,
private static final int CONSUL_PORT = 8500;
private static final String CONNECTION_URL = String.format("%s:%d", CONSUL_HOST,
CONSUL_PORT);
private final static String POLICY = "key \"\" { policy = \"read\" }";
private final static String CONSUL_ACL_MASTER_TOKEN = "consul-master-token";
private static final String POLICY = "key \"\" { policy = \"read\" }";
private final static ParameterizedTypeReference<Map<String, String>> STRING_MAP = new ParameterizedTypeReference<Map<String, String>>() {
private static final String CONSUL_ACL_MASTER_TOKEN = "consul-master-token";
private static final ParameterizedTypeReference<Map<String, String>> STRING_MAP = new ParameterizedTypeReference<Map<String, String>>() {
};
/**
@@ -110,7 +113,7 @@ public class VaultConfigConsulTests {
@Test
public void shouldHaveToken() {
assertThat(token).isNotEmpty();
assertThat(this.token).isNotEmpty();
}
@SpringBootApplication
@@ -119,5 +122,7 @@ public class VaultConfigConsulTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import org.springframework.cloud.vault.config.VaultSecretBackendDescriptor;
@@ -26,25 +27,23 @@ public interface DatabaseSecretProperties extends VaultSecretBackendDescriptor {
/**
* Role name.
*
* @return the role name
*/
String getRole();
/**
* Backend path.
*
* @return the backend path.
*/
String getBackend();
/**
* Name of the target property for the obtained username.
* @return name of the target property for the obtained username.
*/
String getUsernameProperty();
/**
* Name of the target property for the obtained password.
* @return name of the target property for the obtained password.
*/
String getPasswordProperty();

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import javax.validation.constraints.NotEmpty;
@@ -59,4 +60,5 @@ public class VaultCassandraProperties implements DatabaseSecretProperties {
*/
@NotEmpty
private String passwordProperty = "spring.data.cassandra.password";
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.util.HashMap;
@@ -52,8 +53,8 @@ public class VaultConfigDatabaseBootstrapConfiguration {
* {@link SecretBackendMetadataFactory} for Database integration using
* {@link DatabaseSecretProperties}.
*/
public static class DatabaseSecretBackendMetadataFactory implements
SecretBackendMetadataFactory<DatabaseSecretProperties> {
public static class DatabaseSecretBackendMetadataFactory
implements SecretBackendMetadataFactory<DatabaseSecretProperties> {
@Override
public SecretBackendMetadata createMetadata(
@@ -72,19 +73,19 @@ public class VaultConfigDatabaseBootstrapConfiguration {
* username/password property names to names provided with
* {@link DatabaseSecretProperties#getUsernameProperty()} and
* {@link DatabaseSecretProperties#getPasswordProperty()}.
*
* @param properties must not be {@literal null}.
* @return the {@link SecretBackendMetadata}
*/
static SecretBackendMetadata forDatabase(final DatabaseSecretProperties properties) {
static SecretBackendMetadata forDatabase(
final DatabaseSecretProperties properties) {
Assert.notNull(properties, "DatabaseSecretProperties must not be null");
final PropertyNameTransformer transformer = new PropertyNameTransformer();
transformer
.addKeyTransformation("username", properties.getUsernameProperty());
transformer
.addKeyTransformation("password", properties.getPasswordProperty());
transformer.addKeyTransformation("username",
properties.getUsernameProperty());
transformer.addKeyTransformation("password",
properties.getPasswordProperty());
return new SecretBackendMetadata() {
@@ -115,5 +116,7 @@ public class VaultConfigDatabaseBootstrapConfiguration {
}
};
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import javax.validation.constraints.NotEmpty;
@@ -60,4 +61,5 @@ public class VaultDatabaseProperties implements DatabaseSecretProperties {
*/
@NotEmpty
private String passwordProperty = "spring.datasource.password";
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import javax.validation.constraints.NotEmpty;
@@ -59,4 +60,5 @@ public class VaultMongoProperties implements DatabaseSecretProperties {
*/
@NotEmpty
private String passwordProperty = "spring.data.mongodb.password";
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import javax.validation.constraints.NotEmpty;
@@ -35,19 +36,21 @@ import org.springframework.validation.annotation.Validated;
@Data
@Validated
@Deprecated
public class VaultMySqlProperties implements DatabaseSecretProperties,
VaultSecretBackendDescriptor {
public class VaultMySqlProperties
implements DatabaseSecretProperties, VaultSecretBackendDescriptor {
/**
* Enable mysql backend usage.
*/
@Getter(onMethod_ = { @DeprecatedConfigurationProperty(reason = "Use spring.cloud.vault.database") })
@Getter(onMethod_ = {
@DeprecatedConfigurationProperty(reason = "Use spring.cloud.vault.database") })
private boolean enabled = false;
/**
* Role name for credentials.
*/
@Getter(onMethod_ = { @DeprecatedConfigurationProperty(reason = "Use spring.cloud.vault.database") })
@Getter(onMethod_ = {
@DeprecatedConfigurationProperty(reason = "Use spring.cloud.vault.database") })
private String role;
/**
@@ -67,4 +70,5 @@ public class VaultMySqlProperties implements DatabaseSecretProperties,
*/
@NotEmpty
private String passwordProperty = "spring.datasource.password";
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import javax.validation.constraints.NotEmpty;
@@ -40,13 +41,15 @@ public class VaultPostgreSqlProperties implements DatabaseSecretProperties {
* Enable postgresql backend usage.
*/
@Deprecated
@Getter(onMethod_ = { @DeprecatedConfigurationProperty(reason = "Use spring.cloud.vault.database") })
@Getter(onMethod_ = {
@DeprecatedConfigurationProperty(reason = "Use spring.cloud.vault.database") })
private boolean enabled = false;
/**
* Role name for credentials.
*/
@Getter(onMethod_ = { @DeprecatedConfigurationProperty(reason = "Use spring.cloud.vault.database") })
@Getter(onMethod_ = {
@DeprecatedConfigurationProperty(reason = "Use spring.cloud.vault.database") })
private String role;
/**
@@ -66,4 +69,5 @@ public class VaultPostgreSqlProperties implements DatabaseSecretProperties {
*/
@NotEmpty
private String passwordProperty = "spring.datasource.password";
}

View File

@@ -2,4 +2,5 @@
* Database integration with Vault.
* @author Mark Paluch
*/
package org.springframework.cloud.vault.config.databases;
package org.springframework.cloud.vault.config.databases;

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -30,9 +31,9 @@ import org.springframework.cloud.vault.util.IntegrationTestSupport;
import org.springframework.cloud.vault.util.Settings;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.forDatabase;
/**
* Integration tests for {@link VaultConfigTemplate} using the cassandra secret backend.
@@ -43,17 +44,21 @@ import static org.springframework.cloud.vault.config.databases.VaultConfigDataba
*/
public class CassandraSecretIntegrationTests extends IntegrationTestSupport {
private final static String CASSANDRA_HOST = "localhost";
private final static int CASSANDRA_PORT = 9042;
private static final String CASSANDRA_HOST = "localhost";
private final static String CASSANDRA_USERNAME = "springvault";
private final static String CASSANDRA_PASSWORD = "springvault";
private static final int CASSANDRA_PORT = 9042;
private final static String CREATE_USER_AND_GRANT_CQL = "CREATE USER '{{username}}' WITH PASSWORD '{{password}}' NOSUPERUSER;"
private static final String CASSANDRA_USERNAME = "springvault";
private static final String CASSANDRA_PASSWORD = "springvault";
private static final String CREATE_USER_AND_GRANT_CQL = "CREATE USER '{{username}}' WITH PASSWORD '{{password}}' NOSUPERUSER;"
+ "GRANT SELECT ON ALL KEYSPACES TO {{username}};";
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigOperations configOperations;
private VaultCassandraProperties cassandra = new VaultCassandraProperties();
/**
@@ -64,14 +69,14 @@ public class CassandraSecretIntegrationTests extends IntegrationTestSupport {
assumeTrue(CanConnect.to(new InetSocketAddress(CASSANDRA_HOST, CASSANDRA_PORT)));
cassandra.setEnabled(true);
cassandra.setRole("readonly");
this.cassandra.setEnabled(true);
this.cassandra.setRole("readonly");
if (!prepare().hasSecretBackend(cassandra.getBackend())) {
prepare().mountSecret(cassandra.getBackend());
if (!prepare().hasSecretBackend(this.cassandra.getBackend())) {
prepare().mountSecret(this.cassandra.getBackend());
}
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
VaultOperations vaultOperations = this.vaultRule.prepare().getVaultOperations();
Map<String, String> connection = new HashMap<>();
connection.put("hosts", CASSANDRA_HOST);
@@ -79,7 +84,7 @@ public class CassandraSecretIntegrationTests extends IntegrationTestSupport {
connection.put("password", CASSANDRA_PASSWORD);
vaultOperations.write(
String.format("%s/config/connection", cassandra.getBackend()),
String.format("%s/config/connection", this.cassandra.getBackend()),
connection);
Map<String, String> role = new HashMap<>();
@@ -87,20 +92,21 @@ public class CassandraSecretIntegrationTests extends IntegrationTestSupport {
role.put("creation_cql", CREATE_USER_AND_GRANT_CQL);
role.put("consistency", "All");
vaultOperations.write(
String.format("%s/roles/%s", cassandra.getBackend(), cassandra.getRole()),
role);
vaultOperations.write(String.format("%s/roles/%s", this.cassandra.getBackend(),
this.cassandra.getRole()), role);
configOperations = new VaultConfigTemplate(vaultOperations, vaultProperties);
this.configOperations = new VaultConfigTemplate(vaultOperations,
this.vaultProperties);
}
@Test
public void shouldCreateCredentialsCorrectly() {
Map<String, Object> secretProperties = configOperations
.read(forDatabase(cassandra)).getData();
Map<String, Object> secretProperties = this.configOperations
.read(forDatabase(this.cassandra)).getData();
assertThat(secretProperties).containsKeys("spring.data.cassandra.username",
"spring.data.cassandra.password");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -32,9 +33,9 @@ import org.springframework.cloud.vault.util.Settings;
import org.springframework.cloud.vault.util.Version;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.forDatabase;
/**
* Integration tests for {@link VaultConfigTemplate} using the mongodb secret backend.
@@ -44,14 +45,20 @@ import static org.springframework.cloud.vault.config.databases.VaultConfigDataba
*/
public class MongoSecretIntegrationTests extends IntegrationTestSupport {
private final static int MONGODB_PORT = 27017;
private final static String MONGODB_HOST = "localhost";
private final static String ROOT_CREDENTIALS = String.format(
"mongodb://springvault:springvault@%s:%d/admin?ssl=false", MONGODB_HOST, MONGODB_PORT);
private final static String ROLES = "[ \"readWrite\", { \"role\": \"read\", \"db\": \"admin\" } ]";
private static final int MONGODB_PORT = 27017;
private static final String MONGODB_HOST = "localhost";
private static final String ROOT_CREDENTIALS = String.format(
"mongodb://springvault:springvault@%s:%d/admin?ssl=false", MONGODB_HOST,
MONGODB_PORT);
private static final String ROLES = "[ \"readWrite\", { \"role\": \"read\", \"db\": \"admin\" } ]";
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigOperations configOperations;
private VaultMongoProperties mongodb = new VaultMongoProperties();
/**
@@ -63,37 +70,38 @@ public class MongoSecretIntegrationTests extends IntegrationTestSupport {
assumeTrue(CanConnect.to(new InetSocketAddress(MONGODB_HOST, MONGODB_PORT)));
assumeTrue(prepare().getVersion().isGreaterThanOrEqualTo(Version.parse("0.6.2")));
mongodb.setEnabled(true);
mongodb.setRole("readonly");
this.mongodb.setEnabled(true);
this.mongodb.setRole("readonly");
if (!prepare().hasSecretBackend(mongodb.getBackend())) {
prepare().mountSecret(mongodb.getBackend());
if (!prepare().hasSecretBackend(this.mongodb.getBackend())) {
prepare().mountSecret(this.mongodb.getBackend());
}
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
VaultOperations vaultOperations = this.vaultRule.prepare().getVaultOperations();
vaultOperations.write(String.format("%s/config/connection", mongodb.getBackend()),
vaultOperations.write(
String.format("%s/config/connection", this.mongodb.getBackend()),
Collections.singletonMap("uri", ROOT_CREDENTIALS));
Map<String, String> role = new HashMap<>();
role.put("db", "admin");
role.put("roles", ROLES);
vaultOperations.write(
String.format("%s/roles/%s", mongodb.getBackend(), mongodb.getRole()),
role);
vaultOperations.write(String.format("%s/roles/%s", this.mongodb.getBackend(),
this.mongodb.getRole()), role);
configOperations = new VaultConfigTemplate(vaultOperations, vaultProperties);
this.configOperations = new VaultConfigTemplate(vaultOperations,
this.vaultProperties);
}
@Test
public void shouldCreateCredentialsCorrectly() {
Map<String, Object> secretProperties = configOperations
.read(forDatabase(mongodb))
.getData();
Map<String, Object> secretProperties = this.configOperations
.read(forDatabase(this.mongodb)).getData();
assertThat(secretProperties).containsKeys("spring.data.mongodb.username",
"spring.data.mongodb.password");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -31,9 +32,9 @@ import org.springframework.cloud.vault.util.Settings;
import org.springframework.cloud.vault.util.Version;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.forDatabase;
/**
* Integration tests for {@link VaultConfigTemplate} using the {@code database} secret
@@ -44,15 +45,20 @@ import static org.springframework.cloud.vault.config.databases.VaultConfigDataba
*/
public class MySqlDatabaseSecretIntegrationTests extends IntegrationTestSupport {
private final static int MYSQL_PORT = 3306;
private final static String MYSQL_HOST = "localhost";
private final static String ROOT_CREDENTIALS = String.format(
"springvault:springvault@tcp(%s:%d)/", MYSQL_HOST, MYSQL_PORT);
private final static String CREATE_USER_AND_GRANT_SQL = "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';"
private static final int MYSQL_PORT = 3306;
private static final String MYSQL_HOST = "localhost";
private static final String ROOT_CREDENTIALS = String
.format("springvault:springvault@tcp(%s:%d)/", MYSQL_HOST, MYSQL_PORT);
private static final String CREATE_USER_AND_GRANT_SQL = "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';"
+ "GRANT SELECT ON *.* TO '{{name}}'@'%';";
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigOperations configOperations;
@SuppressWarnings("deprecation")
private VaultMySqlProperties mySql = new VaultMySqlProperties();
@@ -65,41 +71,43 @@ public class MySqlDatabaseSecretIntegrationTests extends IntegrationTestSupport
assumeTrue(CanConnect.to(new InetSocketAddress(MYSQL_HOST, MYSQL_PORT)));
assumeTrue(prepare().getVersion().isGreaterThanOrEqualTo(Version.parse("0.7.1")));
mySql.setEnabled(true);
mySql.setRole("readonly");
mySql.setBackend("database");
this.mySql.setEnabled(true);
this.mySql.setRole("readonly");
this.mySql.setBackend("database");
if (!prepare().hasSecretBackend(mySql.getBackend())) {
prepare().mountSecret(mySql.getBackend());
if (!prepare().hasSecretBackend(this.mySql.getBackend())) {
prepare().mountSecret(this.mySql.getBackend());
}
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
VaultOperations vaultOperations = this.vaultRule.prepare().getVaultOperations();
Map<String, String> config = new HashMap<>();
config.put("plugin_name", "mysql-legacy-database-plugin");
config.put("connection_url", ROOT_CREDENTIALS);
config.put("allowed_roles", "readonly");
vaultOperations.write(String.format("%s/config/mysql", mySql.getBackend()),
vaultOperations.write(String.format("%s/config/mysql", this.mySql.getBackend()),
config);
Map<String, String> body = new HashMap<>();
body.put("db_name", "mysql");
body.put("creation_statements", CREATE_USER_AND_GRANT_SQL);
vaultOperations.write(
String.format("%s/roles/%s", mySql.getBackend(), mySql.getRole()), body);
vaultOperations.write(String.format("%s/roles/%s", this.mySql.getBackend(),
this.mySql.getRole()), body);
configOperations = new VaultConfigTemplate(vaultOperations, vaultProperties);
this.configOperations = new VaultConfigTemplate(vaultOperations,
this.vaultProperties);
}
@Test
public void shouldCreateCredentialsCorrectly() {
Map<String, Object> secretProperties = configOperations.read(forDatabase(mySql))
.getData();
Map<String, Object> secretProperties = this.configOperations
.read(forDatabase(this.mySql)).getData();
assertThat(secretProperties).containsKeys("spring.datasource.username",
"spring.datasource.password");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -30,9 +31,9 @@ import org.springframework.cloud.vault.util.IntegrationTestSupport;
import org.springframework.cloud.vault.util.Settings;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.forDatabase;
/**
* Integration tests for {@link VaultConfigTemplate} using the mysql secret backend. This
@@ -42,15 +43,20 @@ import static org.springframework.cloud.vault.config.databases.VaultConfigDataba
*/
public class MySqlSecretIntegrationTests extends IntegrationTestSupport {
private final static int MYSQL_PORT = 3306;
private final static String MYSQL_HOST = "localhost";
private final static String ROOT_CREDENTIALS = String
private static final int MYSQL_PORT = 3306;
private static final String MYSQL_HOST = "localhost";
private static final String ROOT_CREDENTIALS = String
.format("springvault:springvault@tcp(%s:%d)/", MYSQL_HOST, MYSQL_PORT);
private final static String CREATE_USER_AND_GRANT_SQL = "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';"
private static final String CREATE_USER_AND_GRANT_SQL = "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';"
+ "GRANT SELECT ON *.* TO '{{name}}'@'%';";
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigOperations configOperations;
@SuppressWarnings("deprecation")
private VaultMySqlProperties mySql = new VaultMySqlProperties();
@@ -62,32 +68,36 @@ public class MySqlSecretIntegrationTests extends IntegrationTestSupport {
assumeTrue(CanConnect.to(new InetSocketAddress(MYSQL_HOST, MYSQL_PORT)));
mySql.setEnabled(true);
mySql.setRole("readonly");
this.mySql.setEnabled(true);
this.mySql.setRole("readonly");
if (!prepare().hasSecretBackend(mySql.getBackend())) {
prepare().mountSecret(mySql.getBackend());
if (!prepare().hasSecretBackend(this.mySql.getBackend())) {
prepare().mountSecret(this.mySql.getBackend());
}
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
VaultOperations vaultOperations = this.vaultRule.prepare().getVaultOperations();
vaultOperations.write(String.format("%s/config/connection", mySql.getBackend()),
vaultOperations.write(
String.format("%s/config/connection", this.mySql.getBackend()),
Collections.singletonMap("connection_url", ROOT_CREDENTIALS));
vaultOperations.write(
String.format("%s/roles/%s", mySql.getBackend(), mySql.getRole()),
String.format("%s/roles/%s", this.mySql.getBackend(),
this.mySql.getRole()),
Collections.singletonMap("sql", CREATE_USER_AND_GRANT_SQL));
configOperations = new VaultConfigTemplate(vaultOperations, vaultProperties);
this.configOperations = new VaultConfigTemplate(vaultOperations,
this.vaultProperties);
}
@Test
public void shouldCreateCredentialsCorrectly() {
Map<String, Object> secretProperties = configOperations.read(forDatabase(mySql))
.getData();
Map<String, Object> secretProperties = this.configOperations
.read(forDatabase(this.mySql)).getData();
assertThat(secretProperties).containsKeys("spring.datasource.username",
"spring.datasource.password");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -30,9 +31,9 @@ import org.springframework.cloud.vault.util.IntegrationTestSupport;
import org.springframework.cloud.vault.util.Settings;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.config.databases.VaultConfigDatabaseBootstrapConfiguration.DatabaseSecretBackendMetadataFactory.forDatabase;
/**
* Integration tests for
@@ -44,19 +45,22 @@ import static org.springframework.cloud.vault.config.databases.VaultConfigDataba
*/
public class PostgreSqlSecretIntegrationTests extends IntegrationTestSupport {
private final static String POSTGRES_HOST = "localhost";
private final static int POSTGRES_PORT = 5432;
private static final String POSTGRES_HOST = "localhost";
private final static String CONNECTION_URL = String.format(
"postgresql://springvault:springvault@%s:%d/postgres?sslmode=disable", POSTGRES_HOST,
POSTGRES_PORT);
private static final int POSTGRES_PORT = 5432;
private final static String CREATE_USER_AND_GRANT_SQL = "CREATE ROLE \"{{name}}\" WITH "
private static final String CONNECTION_URL = String.format(
"postgresql://springvault:springvault@%s:%d/postgres?sslmode=disable",
POSTGRES_HOST, POSTGRES_PORT);
private static final String CREATE_USER_AND_GRANT_SQL = "CREATE ROLE \"{{name}}\" WITH "
+ "LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';\n"
+ "GRANT SELECT ON ALL TABLES IN SCHEMA public TO \"{{name}}\";";
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigOperations configOperations;
@SuppressWarnings("deprecation")
private VaultPostgreSqlProperties postgreSql = new VaultPostgreSqlProperties();
@@ -68,35 +72,37 @@ public class PostgreSqlSecretIntegrationTests extends IntegrationTestSupport {
assumeTrue(CanConnect.to(new InetSocketAddress(POSTGRES_HOST, POSTGRES_PORT)));
postgreSql.setEnabled(true);
postgreSql.setRole("readonly");
this.postgreSql.setEnabled(true);
this.postgreSql.setRole("readonly");
if (!prepare().hasSecretBackend(postgreSql.getBackend())) {
prepare().mountSecret(postgreSql.getBackend());
if (!prepare().hasSecretBackend(this.postgreSql.getBackend())) {
prepare().mountSecret(this.postgreSql.getBackend());
}
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
VaultOperations vaultOperations = this.vaultRule.prepare().getVaultOperations();
vaultOperations.write(
String.format("%s/config/connection", postgreSql.getBackend()),
String.format("%s/config/connection", this.postgreSql.getBackend()),
Collections.singletonMap("connection_url", CONNECTION_URL));
vaultOperations.write(
String.format("%s/roles/%s", postgreSql.getBackend(),
postgreSql.getRole()),
String.format("%s/roles/%s", this.postgreSql.getBackend(),
this.postgreSql.getRole()),
Collections.singletonMap("sql", CREATE_USER_AND_GRANT_SQL));
configOperations = new VaultConfigTemplate(vaultOperations, vaultProperties);
this.configOperations = new VaultConfigTemplate(vaultOperations,
this.vaultProperties);
}
@Test
public void shouldCreateCredentialsCorrectly() {
Map<String, Object> secretProperties = configOperations
.read(forDatabase(postgreSql)).getData();
Map<String, Object> secretProperties = this.configOperations
.read(forDatabase(this.postgreSql)).getData();
assertThat(secretProperties).containsKeys("spring.datasource.username",
"spring.datasource.password");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -36,8 +37,8 @@ import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the cassandra secret backend. In case this test should fail
@@ -54,13 +55,15 @@ import static org.junit.Assume.*;
"spring.data.cassandra.jmx-enabled=false" })
public class VaultConfigCassandraTests {
private final static String CASSANDRA_HOST = "localhost";
private final static int CASSANDRA_PORT = 9042;
private static final String CASSANDRA_HOST = "localhost";
private final static String CASSANDRA_USERNAME = "springvault";
private final static String CASSANDRA_PASSWORD = "springvault";
private static final int CASSANDRA_PORT = 9042;
private final static String CREATE_USER_AND_GRANT_CQL = "CREATE USER '{{username}}' WITH PASSWORD '{{password}}' NOSUPERUSER;"
private static final String CASSANDRA_USERNAME = "springvault";
private static final String CASSANDRA_PASSWORD = "springvault";
private static final String CREATE_USER_AND_GRANT_CQL = "CREATE USER '{{username}}' WITH PASSWORD '{{password}}' NOSUPERUSER;"
+ "GRANT SELECT ON ALL KEYSPACES TO {{username}};";
/**
@@ -107,12 +110,12 @@ public class VaultConfigCassandraTests {
@Test
public void shouldConnectUsingCluster() {
cluster.connect().close();
this.cluster.connect().close();
}
@Test
public void shouldUseAuthenticationSet() {
assertThat(cluster.getConfiguration().getProtocolOptions().getAuthProvider())
assertThat(this.cluster.getConfiguration().getProtocolOptions().getAuthProvider())
.isInstanceOf(PlainTextAuthProvider.class);
}
@@ -120,7 +123,8 @@ public class VaultConfigCassandraTests {
public void shouldConnectUsingCassandraClient() {
try (Cluster cluster = Cluster.builder().addContactPoint(CASSANDRA_HOST)
.withAuthProvider(new PlainTextAuthProvider(username, password)).build()) {
.withAuthProvider(new PlainTextAuthProvider(this.username, this.password))
.build()) {
Session session = cluster.connect();
session.close();
}
@@ -132,5 +136,7 @@ public class VaultConfigCassandraTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import org.junit.Test;
@@ -30,7 +31,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link VaultConfigDatabaseBootstrapConfiguration}.
@@ -54,10 +55,10 @@ public class VaultConfigDatabaseBootstrapConfigurationTests
@Test
public void shouldApplyCustomConfiguration() {
SecretBackendMetadata metadata = factory.createMetadata(properties);
SecretBackendMetadata metadata = this.factory.createMetadata(this.properties);
assertThat(metadata).isInstanceOf(GenericSecretBackendMetadata.class);
assertThat(metadata.getPath()).isEqualTo(properties.getRole());
assertThat(metadata.getPath()).isEqualTo(this.properties.getRole());
}
@Configuration
@@ -76,5 +77,7 @@ public class VaultConfigDatabaseBootstrapConfigurationTests
}
};
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -40,7 +41,7 @@ import org.springframework.cloud.vault.util.Version;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.junit.Assume.*;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the mongodb secret backend. In case this test should fail
@@ -58,11 +59,15 @@ import static org.junit.Assume.*;
"spring.data.mongodb.database=admin" })
public class VaultConfigMongoTests {
private final static int MONGODB_PORT = 27017;
private final static String MONGODB_HOST = "localhost";
private final static String ROOT_CREDENTIALS = String.format(
"mongodb://springvault:springvault@%s:%d/admin?ssl=false", MONGODB_HOST, MONGODB_PORT);
private final static String ROLES = "[ \"readWrite\", { \"role\": \"read\", \"db\": \"admin\" } ]";
private static final int MONGODB_PORT = 27017;
private static final String MONGODB_HOST = "localhost";
private static final String ROOT_CREDENTIALS = String.format(
"mongodb://springvault:springvault@%s:%d/admin?ssl=false", MONGODB_HOST,
MONGODB_PORT);
private static final String ROLES = "[ \"readWrite\", { \"role\": \"read\", \"db\": \"admin\" } ]";
/**
* Initialize the mongo secret backend.
@@ -106,11 +111,10 @@ public class VaultConfigMongoTests {
@Test
public void shouldConnectUsingDataSource() {
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
MongoDatabase mongoDatabase = this.mongoClient.getDatabase("admin");
List<Document> collections = mongoDatabase.listCollections()
.into(
new ArrayList<>());
.into(new ArrayList<>());
for (Document collection : collections) {
if (collection.getString("name").equals("hello")) {
@@ -127,5 +131,7 @@ public class VaultConfigMongoTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args).registerShutdownHook();
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -38,7 +39,7 @@ import org.springframework.cloud.vault.util.Version;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.junit.Assume.*;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the database secret backend. In case this test should fail
@@ -56,11 +57,14 @@ import static org.junit.Assume.*;
"spring.main.allow-bean-definition-overriding=true" })
public class VaultConfigMySqlDatabaseTests {
private final static int MYSQL_PORT = 3306;
private final static String MYSQL_HOST = "localhost";
private final static String ROOT_CREDENTIALS = String.format(
"springvault:springvault@tcp(%s:%d)/", MYSQL_HOST, MYSQL_PORT);
private final static String CREATE_USER_AND_GRANT_SQL = "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';"
private static final int MYSQL_PORT = 3306;
private static final String MYSQL_HOST = "localhost";
private static final String ROOT_CREDENTIALS = String
.format("springvault:springvault@tcp(%s:%d)/", MYSQL_HOST, MYSQL_PORT);
private static final String CREATE_USER_AND_GRANT_SQL = "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';"
+ "GRANT SELECT ON *.* TO '{{name}}'@'%';";
/**
@@ -108,14 +112,15 @@ public class VaultConfigMySqlDatabaseTests {
@Test
public void shouldConnectUsingDataSource() throws SQLException {
dataSource.getConnection().close();
this.dataSource.getConnection().close();
}
@Test
public void shouldConnectUsingJdbcUrlConnection() throws SQLException {
String url = String.format("jdbc:mysql://%s?useSSL=false&serverTimezone=UTC", MYSQL_HOST);
DriverManager.getConnection(url, username, password).close();
String url = String.format("jdbc:mysql://%s?useSSL=false&serverTimezone=UTC",
MYSQL_HOST);
DriverManager.getConnection(url, this.username, this.password).close();
}
@SpringBootApplication
@@ -124,5 +129,7 @@ public class VaultConfigMySqlDatabaseTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
@@ -36,7 +37,7 @@ import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.junit.Assume.*;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the mysql secret backend. In case this test should fail because
@@ -53,11 +54,14 @@ import static org.junit.Assume.*;
"spring.main.allow-bean-definition-overriding=true" })
public class VaultConfigMySqlTests {
private final static int MYSQL_PORT = 3306;
private final static String MYSQL_HOST = "localhost";
private final static String ROOT_CREDENTIALS = String
private static final int MYSQL_PORT = 3306;
private static final String MYSQL_HOST = "localhost";
private static final String ROOT_CREDENTIALS = String
.format("springvault:springvault@tcp(%s:%d)/", MYSQL_HOST, MYSQL_PORT);
private final static String CREATE_USER_AND_GRANT_SQL = "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';"
private static final String CREATE_USER_AND_GRANT_SQL = "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';"
+ "GRANT SELECT ON *.* TO '{{name}}'@'%';";
/**
@@ -96,14 +100,15 @@ public class VaultConfigMySqlTests {
@Test
public void shouldConnectUsingDataSource() throws SQLException {
dataSource.getConnection().close();
this.dataSource.getConnection().close();
}
@Test
public void shouldConnectUsingJdbcUrlConnection() throws SQLException {
String url = String.format("jdbc:mysql://%s?useSSL=false&serverTimezone=UTC", MYSQL_HOST);
DriverManager.getConnection(url, username, password).close();
String url = String.format("jdbc:mysql://%s?useSSL=false&serverTimezone=UTC",
MYSQL_HOST);
DriverManager.getConnection(url, this.username, this.password).close();
}
@SpringBootApplication
@@ -112,5 +117,7 @@ public class VaultConfigMySqlTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -38,8 +38,8 @@ import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the postgresql secret backend. In case this test should fail
@@ -57,14 +57,15 @@ import static org.junit.Assume.*;
"spring.main.allow-bean-definition-overriding=true" })
public class VaultConfigPostgreSqlTests {
private final static String POSTGRES_HOST = "localhost";
private final static int POSTGRES_PORT = 5432;
private static final String POSTGRES_HOST = "localhost";
private final static String CONNECTION_URL = String.format(
"postgresql://springvault:springvault@%s:%d/postgres?sslmode=disable", POSTGRES_HOST,
POSTGRES_PORT);
private static final int POSTGRES_PORT = 5432;
private final static String CREATE_USER_AND_GRANT_SQL = "CREATE ROLE \"{{name}}\" WITH "
private static final String CONNECTION_URL = String.format(
"postgresql://springvault:springvault@%s:%d/postgres?sslmode=disable",
POSTGRES_HOST, POSTGRES_PORT);
private static final String CREATE_USER_AND_GRANT_SQL = "CREATE ROLE \"{{name}}\" WITH "
+ "LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';\n"
+ "GRANT SELECT ON ALL TABLES IN SCHEMA public TO \"{{name}}\";";
@@ -104,7 +105,7 @@ public class VaultConfigPostgreSqlTests {
@Test
public void shouldConnectUsingDataSource() throws SQLException {
Connection connection = dataSource.getConnection();
Connection connection = this.dataSource.getConnection();
assertThat(connection.getSchema()).isEqualTo("public");
connection.close();
@@ -115,7 +116,7 @@ public class VaultConfigPostgreSqlTests {
String url = String.format("jdbc:postgresql://%s:%d/postgres?ssl=false",
POSTGRES_HOST, POSTGRES_PORT);
DriverManager.getConnection(url, username, password).close();
DriverManager.getConnection(url, this.username, this.password).close();
}
@SpringBootApplication
@@ -124,5 +125,7 @@ public class VaultConfigPostgreSqlTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.rabbitmq;
import java.util.HashMap;
@@ -73,7 +74,6 @@ public class VaultConfigRabbitMqBootstrapConfiguration {
* username/password property names to names provided with
* {@link VaultRabbitMqProperties#getUsernameProperty()} and
* {@link VaultRabbitMqProperties#getPasswordProperty()}.
*
* @param properties must not be {@literal null}.
* @return the {@link SecretBackendMetadata}
*/
@@ -119,5 +119,7 @@ public class VaultConfigRabbitMqBootstrapConfiguration {
}
};
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.rabbitmq;
import javax.validation.constraints.NotEmpty;
@@ -60,4 +61,5 @@ public class VaultRabbitMqProperties implements VaultSecretBackendDescriptor {
*/
@NotEmpty
private String passwordProperty = "spring.rabbitmq.password";
}

View File

@@ -2,4 +2,5 @@
* RabbitMQ integration with Vault.
* @author Mark Paluch
*/
package org.springframework.cloud.vault.config.rabbitmq;
package org.springframework.cloud.vault.config.rabbitmq;

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.rabbitmq;
import java.net.InetSocketAddress;
@@ -31,9 +32,9 @@ import org.springframework.cloud.vault.util.Settings;
import org.springframework.cloud.vault.util.Version;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.cloud.vault.config.rabbitmq.VaultConfigRabbitMqBootstrapConfiguration.RabbitMqSecretBackendMetadataFactory.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.config.rabbitmq.VaultConfigRabbitMqBootstrapConfiguration.RabbitMqSecretBackendMetadataFactory.forRabbitMq;
/**
* Integration tests for {@link VaultConfigTemplate} using the rabbitmq secret backend.
@@ -43,19 +44,23 @@ import static org.springframework.cloud.vault.config.rabbitmq.VaultConfigRabbitM
*/
public class RabbitMqSecretIntegrationTests extends IntegrationTestSupport {
private final static int RABBITMQ_HTTP_MANAGEMENT_PORT = 15672;
private final static String RABBITMQ_HOST = "localhost";
private static final int RABBITMQ_HTTP_MANAGEMENT_PORT = 15672;
private final static String RABBITMQ_USERNAME = "guest";
private final static String RABBITMQ_PASSWORD = "guest";
private static final String RABBITMQ_HOST = "localhost";
private final static String RABBITMQ_URI = String.format("http://%s:%d",
private static final String RABBITMQ_USERNAME = "guest";
private static final String RABBITMQ_PASSWORD = "guest";
private static final String RABBITMQ_URI = String.format("http://%s:%d",
RABBITMQ_HOST, RABBITMQ_HTTP_MANAGEMENT_PORT);
private final static String VHOSTS_ROLE = "{\"/\":{\"write\": \".*\", \"read\": \".*\"}}";
private static final String VHOSTS_ROLE = "{\"/\":{\"write\": \".*\", \"read\": \".*\"}}";
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigTemplate configOperations;
private VaultRabbitMqProperties rabbitmq = new VaultRabbitMqProperties();
/**
@@ -68,11 +73,11 @@ public class RabbitMqSecretIntegrationTests extends IntegrationTestSupport {
.to(new InetSocketAddress(RABBITMQ_HOST, RABBITMQ_HTTP_MANAGEMENT_PORT)));
assumeTrue(prepare().getVersion().isGreaterThanOrEqualTo(Version.parse("0.6.2")));
rabbitmq.setEnabled(true);
rabbitmq.setRole("readonly");
this.rabbitmq.setEnabled(true);
this.rabbitmq.setRole("readonly");
if (!prepare().hasSecretBackend(rabbitmq.getBackend())) {
prepare().mountSecret(rabbitmq.getBackend());
if (!prepare().hasSecretBackend(this.rabbitmq.getBackend())) {
prepare().mountSecret(this.rabbitmq.getBackend());
}
Map<String, String> connection = new HashMap<>();
@@ -83,22 +88,26 @@ public class RabbitMqSecretIntegrationTests extends IntegrationTestSupport {
VaultOperations vaultOperations = prepare().getVaultOperations();
vaultOperations.write(
String.format("%s/config/connection", rabbitmq.getBackend()), connection);
String.format("%s/config/connection", this.rabbitmq.getBackend()),
connection);
vaultOperations.write(
String.format("%s/roles/%s", rabbitmq.getBackend(), rabbitmq.getRole()),
String.format("%s/roles/%s", this.rabbitmq.getBackend(),
this.rabbitmq.getRole()),
Collections.singletonMap("vhosts", VHOSTS_ROLE));
configOperations = new VaultConfigTemplate(vaultOperations, vaultProperties);
this.configOperations = new VaultConfigTemplate(vaultOperations,
this.vaultProperties);
}
@Test
public void shouldCreateCredentialsCorrectly() {
Map<String, Object> secretProperties = configOperations
.read(forRabbitMq(rabbitmq)).getData();
Map<String, Object> secretProperties = this.configOperations
.read(forRabbitMq(this.rabbitmq)).getData();
assertThat(secretProperties).containsKeys("spring.rabbitmq.username",
"spring.rabbitmq.password");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config.rabbitmq;
import org.junit.Test;
@@ -53,10 +54,10 @@ public class VaultConfigRabbitMqBootstrapConfigurationTests
@Test
public void shouldApplyCustomConfiguration() {
SecretBackendMetadata metadata = factory.createMetadata(properties);
SecretBackendMetadata metadata = this.factory.createMetadata(this.properties);
assertThat(metadata).isInstanceOf(GenericSecretBackendMetadata.class);
assertThat(metadata.getPath()).isEqualTo(properties.getRole());
assertThat(metadata.getPath()).isEqualTo(this.properties.getRole());
}
@Configuration
@@ -75,5 +76,7 @@ public class VaultConfigRabbitMqBootstrapConfigurationTests
}
};
}
}
}

View File

@@ -38,7 +38,7 @@ import org.springframework.cloud.vault.util.Version;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.junit.Assume.*;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the rabbitmq secret backend. In case this test should fail
@@ -55,17 +55,20 @@ import static org.junit.Assume.*;
"spring.rabbitmq.address=localhost" })
public class VaultConfigRabbitMqTests {
private final static int RABBITMQ_HTTP_MANAGEMENT_PORT = 15672;
private final static int RABBITMQ_PORT = 5672;
private final static String RABBITMQ_HOST = "localhost";
private static final int RABBITMQ_HTTP_MANAGEMENT_PORT = 15672;
private final static String RABBITMQ_USERNAME = "guest";
private final static String RABBITMQ_PASSWORD = "guest";
private static final int RABBITMQ_PORT = 5672;
private final static String RABBITMQ_URI = String.format("http://%s:%d",
private static final String RABBITMQ_HOST = "localhost";
private static final String RABBITMQ_USERNAME = "guest";
private static final String RABBITMQ_PASSWORD = "guest";
private static final String RABBITMQ_URI = String.format("http://%s:%d",
RABBITMQ_HOST, RABBITMQ_HTTP_MANAGEMENT_PORT);
private final static String VHOSTS_ROLE = "{\"/\":{\"write\": \".*\", \"read\": \".*\"}}";
private static final String VHOSTS_ROLE = "{\"/\":{\"write\": \".*\", \"read\": \".*\"}}";
/**
* Initialize the rabbitmq secret backend.
@@ -110,7 +113,7 @@ public class VaultConfigRabbitMqTests {
@Test
public void shouldConnectSpringConnectionFactory() {
connectionFactory.createConnection().close();
this.connectionFactory.createConnection().close();
}
@Test
@@ -119,8 +122,8 @@ public class VaultConfigRabbitMqTests {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(RABBITMQ_HOST);
factory.setPort(RABBITMQ_PORT);
factory.setUsername(username);
factory.setPassword(password);
factory.setUsername(this.username);
factory.setPassword(this.password);
try (Connection connection = factory.newConnection()) {
connection.createChannel().close();
@@ -133,5 +136,7 @@ public class VaultConfigRabbitMqTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.io.ByteArrayInputStream;
@@ -38,14 +39,40 @@ import org.springframework.cloud.vault.config.VaultProperties.GcpIamProperties;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.vault.authentication.*;
import org.springframework.vault.authentication.AppIdAuthentication;
import org.springframework.vault.authentication.AppIdAuthenticationOptions;
import org.springframework.vault.authentication.AppIdUserIdMechanism;
import org.springframework.vault.authentication.AppRoleAuthentication;
import org.springframework.vault.authentication.AppRoleAuthenticationOptions;
import org.springframework.vault.authentication.AppRoleAuthenticationOptions.AppRoleAuthenticationOptionsBuilder;
import org.springframework.vault.authentication.AppRoleAuthenticationOptions.RoleId;
import org.springframework.vault.authentication.AppRoleAuthenticationOptions.SecretId;
import org.springframework.vault.authentication.AwsEc2Authentication;
import org.springframework.vault.authentication.AwsEc2AuthenticationOptions;
import org.springframework.vault.authentication.AwsEc2AuthenticationOptions.Nonce;
import org.springframework.vault.authentication.AwsIamAuthentication;
import org.springframework.vault.authentication.AwsIamAuthenticationOptions;
import org.springframework.vault.authentication.AwsIamAuthenticationOptions.AwsIamAuthenticationOptionsBuilder;
import org.springframework.vault.authentication.AzureMsiAuthentication;
import org.springframework.vault.authentication.AzureMsiAuthenticationOptions;
import org.springframework.vault.authentication.ClientAuthentication;
import org.springframework.vault.authentication.ClientCertificateAuthentication;
import org.springframework.vault.authentication.CubbyholeAuthentication;
import org.springframework.vault.authentication.CubbyholeAuthenticationOptions;
import org.springframework.vault.authentication.GcpComputeAuthentication;
import org.springframework.vault.authentication.GcpComputeAuthenticationOptions;
import org.springframework.vault.authentication.GcpComputeAuthenticationOptions.GcpComputeAuthenticationOptionsBuilder;
import org.springframework.vault.authentication.GcpCredentialSupplier;
import org.springframework.vault.authentication.GcpIamAuthentication;
import org.springframework.vault.authentication.GcpIamAuthenticationOptions;
import org.springframework.vault.authentication.GcpIamAuthenticationOptions.GcpIamAuthenticationOptionsBuilder;
import org.springframework.vault.authentication.IpAddressUserId;
import org.springframework.vault.authentication.KubernetesAuthentication;
import org.springframework.vault.authentication.KubernetesAuthenticationOptions;
import org.springframework.vault.authentication.KubernetesServiceAccountTokenFile;
import org.springframework.vault.authentication.MacAddressUserId;
import org.springframework.vault.authentication.StaticUserId;
import org.springframework.vault.authentication.TokenAuthentication;
import org.springframework.vault.support.VaultToken;
import org.springframework.web.client.RestOperations;
@@ -72,47 +99,47 @@ class ClientAuthenticationFactory {
*/
ClientAuthentication createClientAuthentication() {
switch (vaultProperties.getAuthentication()) {
switch (this.vaultProperties.getAuthentication()) {
case APPID:
return appIdAuthentication(vaultProperties);
return appIdAuthentication(this.vaultProperties);
case APPROLE:
return appRoleAuthentication(vaultProperties);
return appRoleAuthentication(this.vaultProperties);
case AWS_EC2:
return awsEc2Authentication(vaultProperties);
return awsEc2Authentication(this.vaultProperties);
case AWS_IAM:
return awsIamAuthentication(vaultProperties);
return awsIamAuthentication(this.vaultProperties);
case AZURE_MSI:
return azureMsiAuthentication(vaultProperties);
return azureMsiAuthentication(this.vaultProperties);
case CERT:
return new ClientCertificateAuthentication(restOperations);
return new ClientCertificateAuthentication(this.restOperations);
case CUBBYHOLE:
return cubbyholeAuthentication();
case GCP_GCE:
return gcpGceAuthentication(vaultProperties);
return gcpGceAuthentication(this.vaultProperties);
case GCP_IAM:
return gcpIamAuthentication(vaultProperties);
return gcpIamAuthentication(this.vaultProperties);
case KUBERNETES:
return kubernetesAuthentication(vaultProperties);
return kubernetesAuthentication(this.vaultProperties);
case TOKEN:
Assert.hasText(vaultProperties.getToken(),
Assert.hasText(this.vaultProperties.getToken(),
"Token (spring.cloud.vault.token) must not be empty");
return new TokenAuthentication(vaultProperties.getToken());
return new TokenAuthentication(this.vaultProperties.getToken());
}
throw new UnsupportedOperationException(String.format(
"Client authentication %s not supported",
vaultProperties.getAuthentication()));
throw new UnsupportedOperationException(
String.format("Client authentication %s not supported",
this.vaultProperties.getAuthentication()));
}
private ClientAuthentication appIdAuthentication(VaultProperties vaultProperties) {
@@ -126,7 +153,7 @@ class ClientAuthenticationFactory {
.path(appId.getAppIdPath()) //
.userIdMechanism(getClientAuthentication(appId)).build();
return new AppIdAuthentication(authenticationOptions, restOperations);
return new AppIdAuthentication(authenticationOptions, this.restOperations);
}
private AppIdUserIdMechanism getClientAuthentication(
@@ -147,8 +174,8 @@ class ClientAuthenticationFactory {
if (StringUtils.hasText(appId.getNetworkInterface())) {
try {
return new MacAddressUserId(Integer.parseInt(appId
.getNetworkInterface()));
return new MacAddressUserId(
Integer.parseInt(appId.getNetworkInterface()));
}
catch (NumberFormatException e) {
return new MacAddressUserId(appId.getNetworkInterface());
@@ -164,9 +191,10 @@ class ClientAuthenticationFactory {
private ClientAuthentication appRoleAuthentication(VaultProperties vaultProperties) {
AppRoleAuthenticationOptions options = getAppRoleAuthenticationOptions(vaultProperties);
AppRoleAuthenticationOptions options = getAppRoleAuthenticationOptions(
vaultProperties);
return new AppRoleAuthentication(options, restOperations);
return new AppRoleAuthentication(options, this.restOperations);
}
static AppRoleAuthenticationOptions getAppRoleAuthenticationOptions(
@@ -232,8 +260,8 @@ class ClientAuthenticationFactory {
VaultProperties.AwsEc2Properties awsEc2 = vaultProperties.getAwsEc2();
Nonce nonce = StringUtils.hasText(awsEc2.getNonce()) ? Nonce.provided(awsEc2
.getNonce().toCharArray()) : Nonce.generated();
Nonce nonce = StringUtils.hasText(awsEc2.getNonce())
? Nonce.provided(awsEc2.getNonce().toCharArray()) : Nonce.generated();
AwsEc2AuthenticationOptions authenticationOptions = AwsEc2AuthenticationOptions
.builder().role(awsEc2.getRole()) //
@@ -242,8 +270,8 @@ class ClientAuthenticationFactory {
.identityDocumentUri(URI.create(awsEc2.getIdentityDocument())) //
.build();
return new AwsEc2Authentication(authenticationOptions, restOperations,
externalRestOperations);
return new AwsEc2Authentication(authenticationOptions, this.restOperations,
this.externalRestOperations);
}
private ClientAuthentication awsIamAuthentication(VaultProperties vaultProperties) {
@@ -267,10 +295,10 @@ class ClientAuthenticationFactory {
builder.path(awsIam.getAwsPath()) //
.credentialsProvider(credentialsProvider);
AwsIamAuthenticationOptions options = builder.credentialsProvider(
credentialsProvider).build();
AwsIamAuthenticationOptions options = builder
.credentialsProvider(credentialsProvider).build();
return new AwsIamAuthentication(options, restOperations);
return new AwsIamAuthentication(options, this.restOperations);
}
private ClientAuthentication azureMsiAuthentication(VaultProperties vaultProperties) {
@@ -283,20 +311,21 @@ class ClientAuthenticationFactory {
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder()
.role(azureMsi.getRole()).build();
return new AzureMsiAuthentication(options, restOperations, externalRestOperations);
return new AzureMsiAuthentication(options, this.restOperations,
this.externalRestOperations);
}
private ClientAuthentication cubbyholeAuthentication() {
Assert.hasText(vaultProperties.getToken(),
Assert.hasText(this.vaultProperties.getToken(),
"Initial Token (spring.cloud.vault.token) for Cubbyhole authentication must not be empty");
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() //
.wrapped() //
.initialToken(VaultToken.of(vaultProperties.getToken())) //
.initialToken(VaultToken.of(this.vaultProperties.getToken())) //
.build();
return new CubbyholeAuthentication(options, restOperations);
return new CubbyholeAuthentication(options, this.restOperations);
}
private ClientAuthentication gcpGceAuthentication(VaultProperties vaultProperties) {
@@ -313,8 +342,8 @@ class ClientAuthenticationFactory {
builder.serviceAccount(gcp.getServiceAccount());
}
return new GcpComputeAuthentication(builder.build(), restOperations,
externalRestOperations);
return new GcpComputeAuthentication(builder.build(), this.restOperations,
this.externalRestOperations);
}
private ClientAuthentication gcpIamAuthentication(VaultProperties vaultProperties) {
@@ -324,8 +353,8 @@ class ClientAuthenticationFactory {
Assert.hasText(gcp.getRole(),
"Role (spring.cloud.vault.gcp-iam.role) must not be empty");
GcpIamAuthenticationOptionsBuilder builder = GcpIamAuthenticationOptions
.builder().path(gcp.getGcpPath()).role(gcp.getRole())
GcpIamAuthenticationOptionsBuilder builder = GcpIamAuthenticationOptions.builder()
.path(gcp.getGcpPath()).role(gcp.getRole())
.jwtValidity(gcp.getJwtValidity());
if (StringUtils.hasText(gcp.getProjectId())) {
@@ -342,48 +371,47 @@ class ClientAuthenticationFactory {
GcpIamAuthenticationOptions options = builder.build();
try {
return new GcpIamAuthentication(options, restOperations);
return new GcpIamAuthentication(options, this.restOperations);
}
catch (IOException | GeneralSecurityException e) {
throw new IllegalStateException("Cannot create GcpIamAuthentication", e);
}
}
private GoogleCredential getGoogleCredential(GcpIamProperties gcp) throws IOException {
private GoogleCredential getGoogleCredential(GcpIamProperties gcp)
throws IOException {
GcpCredentials credentialProperties = gcp.getCredentials();
if (credentialProperties.getLocation() != null) {
return GoogleCredential.fromStream(credentialProperties.getLocation()
.getInputStream());
return GoogleCredential
.fromStream(credentialProperties.getLocation().getInputStream());
}
if (StringUtils.hasText(credentialProperties.getEncodedKey())) {
return GoogleCredential.fromStream(new ByteArrayInputStream(Base64
.getDecoder().decode(credentialProperties.getEncodedKey())));
return GoogleCredential.fromStream(new ByteArrayInputStream(
Base64.getDecoder().decode(credentialProperties.getEncodedKey())));
}
return GoogleCredential.getApplicationDefault();
}
private ClientAuthentication kubernetesAuthentication(VaultProperties vaultProperties) {
private ClientAuthentication kubernetesAuthentication(
VaultProperties vaultProperties) {
VaultProperties.KubernetesProperties kubernetes = vaultProperties.getKubernetes();
Assert.hasText(kubernetes.getRole(),
"Role (spring.cloud.vault.kubernetes.role) must not be empty");
Assert.hasText(
kubernetes.getServiceAccountTokenFile(),
Assert.hasText(kubernetes.getServiceAccountTokenFile(),
"Service account token file (spring.cloud.vault.kubernetes.service-account-token-file) must not be empty");
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions
.builder()
.path(kubernetes.getKubernetesPath())
.role(kubernetes.getRole())
.jwtSupplier(
new KubernetesServiceAccountTokenFile(kubernetes
.getServiceAccountTokenFile())).build();
.builder().path(kubernetes.getKubernetesPath()).role(kubernetes.getRole())
.jwtSupplier(new KubernetesServiceAccountTokenFile(
kubernetes.getServiceAccountTokenFile()))
.build();
return new KubernetesAuthentication(options, restOperations);
return new KubernetesAuthentication(options, this.restOperations);
}
private static class AwsCredentialProvider {
@@ -416,5 +444,7 @@ class ClientAuthenticationFactory {
}
};
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.ArrayList;
@@ -72,7 +73,7 @@ class DefaultSecretBackendConfigurer
Assert.notNull(metadata, "SecretBackendMetadata must not be null");
secretBackends.put(metadata.getPath(), metadata);
this.secretBackends.put(metadata.getPath(), metadata);
return this;
}
@@ -92,7 +93,7 @@ class DefaultSecretBackendConfigurer
Assert.notNull(requestedSecret, "RequestedSecret must not be null");
Assert.notNull(propertyTransformer, "PropertyTransformer must not be null");
secretBackends.put(requestedSecret.getPath(),
this.secretBackends.put(requestedSecret.getPath(),
new SimpleLeasingSecretBackendMetadata(
createMetadata(requestedSecret.getPath(), propertyTransformer),
requestedSecret.getMode()));
@@ -119,16 +120,16 @@ class DefaultSecretBackendConfigurer
}
public boolean isRegisterDefaultGenericSecretBackends() {
return registerDefaultGenericSecretBackends;
return this.registerDefaultGenericSecretBackends;
}
public boolean isRegisterDefaultDiscoveredSecretBackends() {
return registerDefaultDiscoveredSecretBackends;
return this.registerDefaultDiscoveredSecretBackends;
}
@Override
public List<SecretBackendMetadata> getSecretBackends() {
return new ArrayList<>(secretBackends.values());
return new ArrayList<>(this.secretBackends.values());
}
@RequiredArgsConstructor
@@ -140,23 +141,24 @@ class DefaultSecretBackendConfigurer
@Override
public String getName() {
return String.format("Context backend: %s", path);
return String.format("Context backend: %s", this.path);
}
@Override
public String getPath() {
return path;
return this.path;
}
@Override
public PropertyTransformer getPropertyTransformer() {
return propertyTransformer;
return this.propertyTransformer;
}
@Override
public Map<String, String> getVariables() {
return Collections.singletonMap("path", path);
return Collections.singletonMap("path", this.path);
}
}
private static class SimpleLeasingSecretBackendMetadata
@@ -172,7 +174,9 @@ class DefaultSecretBackendConfigurer
@Override
public Mode getLeaseMode() {
return mode;
return this.mode;
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.net.URI;
@@ -41,7 +42,7 @@ import org.springframework.vault.client.VaultEndpointProvider;
* @since 1.1
*/
@Configuration
@ConditionalOnProperty(value = "spring.cloud.vault.discovery.enabled")
@ConditionalOnProperty("spring.cloud.vault.discovery.enabled")
@EnableConfigurationProperties(VaultProperties.class)
@Order(Ordered.LOWEST_PRECEDENCE - 2)
@EnableDiscoveryClient
@@ -93,4 +94,5 @@ public class DiscoveryClientVaultBootstrapConfiguration {
return () -> vaultEndpoint;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.List;
@@ -31,8 +32,8 @@ import org.springframework.cloud.client.discovery.DiscoveryClient;
*/
@CommonsLog
@RequiredArgsConstructor
public class DiscoveryClientVaultServiceInstanceProvider implements
VaultServiceInstanceProvider {
public class DiscoveryClientVaultServiceInstanceProvider
implements VaultServiceInstanceProvider {
private final DiscoveryClient client;
@@ -44,8 +45,8 @@ public class DiscoveryClientVaultServiceInstanceProvider implements
List<ServiceInstance> instances = this.client.getInstances(serviceId);
if (instances.isEmpty()) {
throw new IllegalStateException("No instances found of Vault server ("
+ serviceId + ")");
throw new IllegalStateException(
"No instances found of Vault server (" + serviceId + ")");
}
ServiceInstance instance = instances.get(0);
@@ -54,4 +55,5 @@ public class DiscoveryClientVaultServiceInstanceProvider implements
return instance;
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.List;
@@ -24,8 +25,8 @@ import org.springframework.util.Assert;
*
* @author Mark Paluch
*/
public class GenericSecretBackendMetadata extends KeyValueSecretBackendMetadata implements
SecretBackendMetadata {
public final class GenericSecretBackendMetadata extends KeyValueSecretBackendMetadata
implements SecretBackendMetadata {
private GenericSecretBackendMetadata(String path) {
super(path);
@@ -34,7 +35,6 @@ public class GenericSecretBackendMetadata extends KeyValueSecretBackendMetadata
/**
* Create a {@link SecretBackendMetadata} for the {@code generic} secret backend given
* a {@code secretBackendPath} and {@code key}.
*
* @param secretBackendPath the secret backend mount path without leading/trailing
* slashes, must not be empty or {@literal null}.
* @param key the key within the secret backend. May contain slashes but not
@@ -43,7 +43,8 @@ public class GenericSecretBackendMetadata extends KeyValueSecretBackendMetadata
*/
public static SecretBackendMetadata create(String secretBackendPath, String key) {
Assert.hasText(secretBackendPath, "Secret backend path must not be null or empty");
Assert.hasText(secretBackendPath,
"Secret backend path must not be null or empty");
Assert.hasText(key, "Key must not be null or empty");
return create(String.format("%s/%s", secretBackendPath, key));
@@ -52,7 +53,6 @@ public class GenericSecretBackendMetadata extends KeyValueSecretBackendMetadata
/**
* Create a {@link SecretBackendMetadata} for the {@code generic} secret backend given
* a {@code path}.
*
* @param path the relative path of the secret. slashes, must not be empty or
* {@literal null}.
* @return the {@link SecretBackendMetadata}
@@ -65,8 +65,7 @@ public class GenericSecretBackendMetadata extends KeyValueSecretBackendMetadata
/**
* Build a list of context paths from application name and the active profile names.
* Application name and profiles support multiple (comma-separated) values.
*
* @param properties
* @param properties the generic backend properties.
* @param profiles active application profiles.
* @return list of context paths.
*/
@@ -79,7 +78,6 @@ public class GenericSecretBackendMetadata extends KeyValueSecretBackendMetadata
* Create a list of context names from a combination of application name and
* application name with profile name. Using an empty application name will return an
* empty list.
*
* @param applicationName the application name. May be empty.
* @param profiles active application profiles.
* @param profileSeparator profile separator character between application name and
@@ -92,4 +90,5 @@ public class GenericSecretBackendMetadata extends KeyValueSecretBackendMetadata
return KeyValueSecretBackendMetadata.buildContexts(applicationName, profiles,
profileSeparator);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.ArrayList;
@@ -21,8 +22,8 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -35,10 +36,11 @@ import org.springframework.vault.core.util.PropertyTransformers;
* @author Mark Paluch
* @since 2.0
*/
public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport implements
SecretBackendMetadata {
public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
implements SecretBackendMetadata {
private final String path;
private final PropertyTransformer propertyTransformer;
KeyValueSecretBackendMetadata(String path) {
@@ -59,7 +61,6 @@ public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
* Create a {@link SecretBackendMetadata} for the {@code kv} secret backend given a
* {@code secretBackendPath} and {@code key}. Use plain mount and key paths. The
* required {@code data} segment is added by this method.
*
* @param secretBackendPath the secret backend mount path without leading/trailing
* slashes and without the {@code data} path segment, must not be empty or
* {@literal null}.
@@ -69,7 +70,8 @@ public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
*/
public static SecretBackendMetadata create(String secretBackendPath, String key) {
Assert.hasText(secretBackendPath, "Secret backend path must not be null or empty");
Assert.hasText(secretBackendPath,
"Secret backend path must not be null or empty");
Assert.hasText(key, "Key must not be null or empty");
return create(String.format("%s/data/%s", secretBackendPath, key),
@@ -79,7 +81,6 @@ public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
/**
* Create a {@link SecretBackendMetadata} for the {@code generic} secret backend given
* a {@code path}.
*
* @param path the relative path of the secret. slashes, must not be empty or
* {@literal null}.
* @return the {@link SecretBackendMetadata}
@@ -91,7 +92,6 @@ public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
/**
* Create a {@link SecretBackendMetadata} for the {@code generic} secret backend given
* a {@code path}.
*
* @param path the relative path of the secret. slashes, must not be empty or
* {@literal null}.
* @param propertyTransformer property transformer.
@@ -104,19 +104,18 @@ public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
@Override
public String getPath() {
return path;
return this.path;
}
@Override
public PropertyTransformer getPropertyTransformer() {
return propertyTransformer;
return this.propertyTransformer;
}
/**
* Build a list of context paths from application name and the active profile names.
* Application name and profiles support multiple (comma-separated) values.
*
* @param properties
* @param properties the key-value backend properties.
* @param profiles active application profiles.
* @return list of context paths.
*/
@@ -146,7 +145,6 @@ public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
* Create a list of context names from a combination of application name and
* application name with profile name. Using an empty application name will return an
* empty list.
*
* @param applicationName the application name. May be empty.
* @param profiles active application profiles.
* @param profileSeparator profile separator character between application name and
@@ -185,7 +183,7 @@ public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
/**
* {@link PropertyTransformer} that strips a prefix from property names.
*/
static class UnwrappingPropertyTransformer implements PropertyTransformer {
static final class UnwrappingPropertyTransformer implements PropertyTransformer {
private final String prefixToStrip;
@@ -209,19 +207,22 @@ public class KeyValueSecretBackendMetadata extends SecretBackendMetadataSupport
}
@Override
public Map<String, Object> transformProperties(Map<String, ? extends Object> input) {
public Map<String, Object> transformProperties(
Map<String, ? extends Object> input) {
Map<String, Object> target = new LinkedHashMap<>(input.size(), 1);
for (Entry<String, ? extends Object> entry : input.entrySet()) {
if (entry.getKey().startsWith(prefixToStrip + ".")) {
target.put(entry.getKey().substring(prefixToStrip.length() + 1),
if (entry.getKey().startsWith(this.prefixToStrip + ".")) {
target.put(entry.getKey().substring(this.prefixToStrip.length() + 1),
entry.getValue());
}
}
return target;
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.springframework.vault.core.lease.domain.RequestedSecret.Mode;
@@ -29,11 +30,11 @@ public interface LeasingSecretBackendMetadata extends SecretBackendMetadata {
/**
* Return the lease mode of this secret backend.
* <p/>
* <p>
* Lease mode is considered only by lease-aware property sources.
*
* @return the lease mode of this secret backend.
* @since 1.1
*/
Mode getLeaseMode();
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.concurrent.atomic.AtomicReference;
@@ -45,13 +46,12 @@ class LeasingVaultPropertySourceLocator extends VaultPropertySourceLocatorSuppor
/**
* Creates a new {@link LeasingVaultPropertySourceLocator}.
*
* @param properties must not be {@literal null}.
* @param propertySourceLocatorConfiguration must not be {@literal null}.
* @param secretLeaseContainer must not be {@literal null}.
* @since 1.1
*/
public LeasingVaultPropertySourceLocator(VaultProperties properties,
LeasingVaultPropertySourceLocator(VaultProperties properties,
PropertySourceLocatorConfiguration propertySourceLocatorConfiguration,
SecretLeaseContainer secretLeaseContainer) {
@@ -66,13 +66,12 @@ class LeasingVaultPropertySourceLocator extends VaultPropertySourceLocatorSuppor
@Override
public int getOrder() {
return properties.getConfig().getOrder();
return this.properties.getConfig().getOrder();
}
/**
* Create {@link VaultPropertySource} initialized with a
* {@link SecretBackendMetadata}.
*
* Create {@link VaultPropertySource} initialized with a {@link SecretBackendMetadata}
* .
* @param accessor the {@link SecretBackendMetadata}.
* @return the {@link VaultPropertySource} to use.
*/
@@ -81,7 +80,7 @@ class LeasingVaultPropertySourceLocator extends VaultPropertySourceLocatorSuppor
RequestedSecret secret = getRequestedSecret(accessor);
if (properties.isFailFast()) {
if (this.properties.isFailFast()) {
return createVaultPropertySourceFailFast(secret, accessor);
}
@@ -107,13 +106,12 @@ class LeasingVaultPropertySourceLocator extends VaultPropertySourceLocatorSuppor
/**
* Decorated {@link PropertySource} creation to catch and throw the first error that
* occurred during initial secret retrieval.
*
* @param secret
* @param accessor
* @return
* @param secret the requested secret.
* @param accessor the metadata accessor.
* @return the property source for the {@link RequestedSecret}.
*/
private PropertySource<?> createVaultPropertySourceFailFast(
final RequestedSecret secret, SecretBackendMetadata accessor) {
private PropertySource<?> createVaultPropertySourceFailFast(RequestedSecret secret,
SecretBackendMetadata accessor) {
final AtomicReference<Exception> errorRef = new AtomicReference<>();
@@ -150,4 +148,5 @@ class LeasingVaultPropertySourceLocator extends VaultPropertySourceLocatorSuppor
return new LeaseAwareVaultPropertySource(accessor.getName(),
this.secretLeaseContainer, secret, accessor.getPropertyTransformer());
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.HashMap;
@@ -45,7 +46,6 @@ public class PropertyNameTransformer implements PropertyTransformer {
/**
* Adds a key name transformation by providing a {@code sourceKeyName} and a
* {@code targetKeyName}.
*
* @param sourceKeyName must not be empty or {@literal null}.
* @param targetKeyName must not be empty or {@literal null}.
*/
@@ -54,7 +54,7 @@ public class PropertyNameTransformer implements PropertyTransformer {
Assert.hasText(sourceKeyName, "Source key name must not be empty");
Assert.hasText(targetKeyName, "Target key name must not be empty");
nameMapping.put(sourceKeyName, targetKeyName);
this.nameMapping.put(sourceKeyName, targetKeyName);
}
@Override
@@ -70,8 +70,8 @@ public class PropertyNameTransformer implements PropertyTransformer {
String translatedKey = key;
if (nameMapping.containsKey(key)) {
translatedKey = nameMapping.get(key);
if (this.nameMapping.containsKey(key)) {
translatedKey = this.nameMapping.get(key);
}
transformed.put(translatedKey, input.get(key));
@@ -79,4 +79,5 @@ public class PropertyNameTransformer implements PropertyTransformer {
return transformed;
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collection;
@@ -29,8 +30,8 @@ public interface PropertySourceLocatorConfiguration {
/**
* Return a {@link Collection} of {@link SecretBackendMetadata} to be instantiated as
* {@link org.springframework.core.env.PropertySource}.
*
* @return a {@link Collection} of {@link SecretBackendMetadata}.
*/
Collection<SecretBackendMetadata> getSecretBackends();
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.springframework.vault.core.lease.domain.RequestedSecret;
@@ -40,7 +41,6 @@ public interface SecretBackendConfigurer {
/**
* Add a {@link SecretBackendMetadata} given its {@code path}.
*
* @param path must not be {@literal null} or empty.
* @return {@code this} {@link SecretBackendConfigurer}.
*/
@@ -49,7 +49,6 @@ public interface SecretBackendConfigurer {
/**
* Add a {@link SecretBackendMetadata} given its {@code path} and
* {@link PropertyTransformer}.
*
* @param path must not be {@literal null} or empty.
* @param propertyTransformer must not be {@literal null}.
* @return {@code this} {@link SecretBackendConfigurer}.
@@ -58,7 +57,6 @@ public interface SecretBackendConfigurer {
/**
* Add a {@link SecretBackendMetadata}.
*
* @param metadata must not be {@literal null}.
* @return {@code this} {@link SecretBackendConfigurer}.
*/
@@ -68,7 +66,6 @@ public interface SecretBackendConfigurer {
* Add a {@link SecretBackendMetadata} given {@link RequestedSecret}. Property sources
* supporting leasing will derive lease renewal/rotation from
* {@link RequestedSecret.Mode}.
*
* @param requestedSecret must not be {@literal null} or empty.
* @return {@code this} {@link SecretBackendConfigurer}.
*/
@@ -78,7 +75,6 @@ public interface SecretBackendConfigurer {
* Add a {@link SecretBackendMetadata} given {@link RequestedSecret} and
* {@link PropertyTransformer}. Property sources supporting leasing will derive lease
* renewal/rotation from {@link RequestedSecret.Mode}.
*
* @param requestedSecret must not be {@literal null} or empty.
* @param propertyTransformer must not be {@literal null}.
* @return {@code this} {@link SecretBackendConfigurer}.
@@ -88,7 +84,6 @@ public interface SecretBackendConfigurer {
/**
* Register default generic secret backend property sources.
*
* @param registerDefault {@literal true} to enable default generic secret backend
* registration.
* @return {@code this} {@link SecretBackendConfigurer}.
@@ -98,11 +93,11 @@ public interface SecretBackendConfigurer {
/**
* Register default discovered secret backend property sources from
* {@link SecretBackendMetadata} via {@link VaultSecretBackendDescriptor} beans.
*
* @param registerDefault {@literal true} to enable default discovered secret backend
* registration via {@link VaultSecretBackendDescriptor} beans.
* @return {@code this} {@link SecretBackendConfigurer}.
*/
SecretBackendConfigurer registerDefaultDiscoveredSecretBackends(
boolean registerDefault);
}

View File

@@ -13,13 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import lombok.experimental.UtilityClass;
import lombok.extern.apachecommons.CommonsLog;
/**
@@ -29,10 +29,9 @@ import lombok.extern.apachecommons.CommonsLog;
* @author Mark Paluch
*/
@CommonsLog
@UtilityClass
class SecretBackendFactories {
final class SecretBackendFactories {
public static Collection<SecretBackendMetadata> createSecretBackendMetadata(
static Collection<SecretBackendMetadata> createSecretBackendMetadata(
Collection<VaultSecretBackendDescriptor> vaultSecretBackendDescriptors,
Collection<SecretBackendMetadataFactory<? super VaultSecretBackendDescriptor>> factories) {
@@ -73,4 +72,9 @@ class SecretBackendFactories {
}
return accessor;
}
private SecretBackendFactories() {
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Map;
@@ -33,14 +34,12 @@ public interface SecretBackendMetadata {
/**
* Return a readable name of this secret backend.
*
* @return the name of this secret backend.
*/
String getName();
/**
* Return the path of this secret backend.
*
* @return the path of this secret backend.
* @since 1.1
*/
@@ -49,15 +48,15 @@ public interface SecretBackendMetadata {
/**
* Return a {@link PropertyTransformer} to post-process properties retrieved from
* Vault.
*
* @return the property transformer.
* @see org.springframework.vault.core.util.PropertyTransformers
*/
PropertyTransformer getPropertyTransformer();
/**
* @return URL template variables. URI variables should declare either {@code backend}
* and {@code key} or {@code path} properties.
* @return the URL template variables. URI variables should declare either
* {@code backend} and {@code key} or {@code path} properties.
*/
Map<String, String> getVariables();
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
/**
@@ -31,6 +32,7 @@ package org.springframework.cloud.vault.config;
* Typically implemented by secret backend providers that implement access to a particular
* backend using read operations.
*
* @param <T> descriptor type.
* @author Mark Paluch
* @see SecretBackendMetadata
* @see LeasingSecretBackendMetadata
@@ -41,7 +43,6 @@ public interface SecretBackendMetadataFactory<T extends VaultSecretBackendDescri
/**
* Converts a {@link VaultSecretBackendDescriptor} into a
* {@link SecretBackendMetadata}.
*
* @param backendDescriptor must not be {@literal null}.
* @return the {@link SecretBackendMetadata}.
* @see LeasingSecretBackendMetadata
@@ -51,10 +52,10 @@ public interface SecretBackendMetadataFactory<T extends VaultSecretBackendDescri
/**
* Checks whether the {@link VaultSecretBackendDescriptor} is supported by this
* {@link SecretBackendMetadataFactory}.
*
* @param backendDescriptor must not be {@literal null}.
* @return {@literal true} if the given {@link VaultSecretBackendDescriptor} is
* supported.
*/
boolean supports(VaultSecretBackendDescriptor backendDescriptor);
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -45,4 +46,5 @@ public abstract class SecretBackendMetadataSupport implements SecretBackendMetad
public Map<String, String> getVariables() {
return Collections.singletonMap("path", getPath());
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Map;
@@ -23,7 +24,7 @@ import org.springframework.vault.core.util.PropertyTransformer;
/**
* Provides a convenient implementation of the {@link SecretBackendMetadata} interface
* that can be subclassed to override specific methods.
* <p/>
* <p>
* This class implements the Wrapper or Decorator pattern. Methods default to calling
* through to the wrapped request object.
*
@@ -37,7 +38,6 @@ public class SecretBackendMetadataWrapper implements SecretBackendMetadata {
/**
* Create a new {@link SecretBackendMetadataWrapper} given
* {@link SecretBackendMetadata}.
*
* @param delegate must not be {@literal null}.
*/
public SecretBackendMetadataWrapper(SecretBackendMetadata delegate) {
@@ -49,21 +49,22 @@ public class SecretBackendMetadataWrapper implements SecretBackendMetadata {
@Override
public String getName() {
return delegate.getName();
return this.delegate.getName();
}
@Override
public String getPath() {
return delegate.getPath();
return this.delegate.getPath();
}
@Override
public PropertyTransformer getPropertyTransformer() {
return delegate.getPropertyTransformer();
return this.delegate.getPropertyTransformer();
}
@Override
public Map<String, String> getVariables() {
return delegate.getVariables();
return this.delegate.getVariables();
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Map;
@@ -26,4 +27,5 @@ import org.springframework.vault.support.VaultResponseSupport;
* @author Mark Paluch
*/
public class Secrets extends VaultResponseSupport<Map<String, Object>> {
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.time.Duration;
@@ -42,8 +43,8 @@ import org.springframework.vault.authentication.SimpleSessionManager;
import org.springframework.vault.client.SimpleVaultEndpointProvider;
import org.springframework.vault.client.VaultClients;
import org.springframework.vault.client.VaultEndpointProvider;
import org.springframework.vault.config.ClientHttpRequestFactoryFactory;
import org.springframework.vault.config.AbstractVaultConfiguration.ClientFactoryWrapper;
import org.springframework.vault.config.ClientHttpRequestFactoryFactory;
import org.springframework.vault.core.VaultOperations;
import org.springframework.vault.core.VaultTemplate;
import org.springframework.vault.support.ClientOptions;
@@ -89,21 +90,20 @@ public class VaultBootstrapConfiguration implements InitializingBean {
VaultEndpointProvider provider = endpointProvider.getIfAvailable();
if (provider == null) {
provider = SimpleVaultEndpointProvider.of(VaultConfigurationUtil
.createVaultEndpoint(vaultProperties));
provider = SimpleVaultEndpointProvider
.of(VaultConfigurationUtil.createVaultEndpoint(vaultProperties));
}
this.endpointProvider = provider;
}
@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() {
ClientHttpRequestFactory clientHttpRequestFactory = clientHttpRequestFactoryWrapper()
.getClientHttpRequestFactory();
this.restOperations = VaultClients.createRestTemplate(endpointProvider,
this.restOperations = VaultClients.createRestTemplate(this.endpointProvider,
clientHttpRequestFactory);
this.externalRestOperations = new RestTemplate(clientHttpRequestFactory);
@@ -115,7 +115,6 @@ public class VaultBootstrapConfiguration implements InitializingBean {
* as root bean because {@link ClientHttpRequestFactory} is configured with
* {@link ClientOptions} and {@link SslConfiguration} which are not necessarily
* applicable for the whole application.
*
* @return the {@link ClientFactoryWrapper} to wrap a {@link ClientHttpRequestFactory}
* instance.
*/
@@ -123,35 +122,35 @@ public class VaultBootstrapConfiguration implements InitializingBean {
@ConditionalOnMissingBean
public ClientFactoryWrapper clientHttpRequestFactoryWrapper() {
ClientOptions clientOptions = new ClientOptions(Duration.ofMillis(vaultProperties
.getConnectionTimeout()), Duration.ofMillis(vaultProperties
.getReadTimeout()));
ClientOptions clientOptions = new ClientOptions(
Duration.ofMillis(this.vaultProperties.getConnectionTimeout()),
Duration.ofMillis(this.vaultProperties.getReadTimeout()));
SslConfiguration sslConfiguration = VaultConfigurationUtil
.createSslConfiguration(vaultProperties.getSsl());
.createSslConfiguration(this.vaultProperties.getSsl());
return new ClientFactoryWrapper(ClientHttpRequestFactoryFactory.create(
clientOptions, sslConfiguration));
return new ClientFactoryWrapper(
ClientHttpRequestFactoryFactory.create(clientOptions, sslConfiguration));
}
/**
* Creates a {@link VaultTemplate}.
*
* @return
* @see #clientHttpRequestFactoryWrapper()
* @param sessionManager the {@link SessionManager}.
* @return the {@link VaultTemplate} bean.
* @see VaultBootstrapConfiguration#clientHttpRequestFactoryWrapper()
*/
@Bean
@ConditionalOnMissingBean(VaultOperations.class)
public VaultTemplate vaultTemplate(SessionManager sessionManager) {
return new VaultTemplate(endpointProvider, clientHttpRequestFactoryWrapper()
.getClientHttpRequestFactory(), sessionManager);
return new VaultTemplate(this.endpointProvider,
clientHttpRequestFactoryWrapper().getClientHttpRequestFactory(),
sessionManager);
}
/**
* Creates a new {@link TaskSchedulerWrapper} that encapsulates a bean implementing
* {@link TaskScheduler} and {@link AsyncTaskExecutor}.
*
* @return
* @return the {@link TaskSchedulerWrapper} bean.
* @see ThreadPoolTaskScheduler
*/
@Bean
@@ -166,13 +165,16 @@ public class VaultBootstrapConfiguration implements InitializingBean {
// This is to destroy bootstrap resources
// otherwise, the bootstrap context is not shut down cleanly
applicationContext.registerShutdownHook();
this.applicationContext.registerShutdownHook();
return new TaskSchedulerWrapper(threadPoolTaskScheduler);
}
/**
* @return the {@link SessionManager} for Vault session management.
* @param clientAuthentication the {@link ClientAuthentication}.
* @param asyncTaskExecutorFactory the {@link ObjectFactory} for
* {@link TaskSchedulerWrapper}.
* @see SessionManager
* @see LifecycleAwareSessionManager
*/
@@ -181,10 +183,10 @@ public class VaultBootstrapConfiguration implements InitializingBean {
public SessionManager vaultSessionManager(ClientAuthentication clientAuthentication,
ObjectFactory<TaskSchedulerWrapper> asyncTaskExecutorFactory) {
if (vaultProperties.getConfig().getLifecycle().isEnabled()) {
if (this.vaultProperties.getConfig().getLifecycle().isEnabled()) {
return new LifecycleAwareSessionManager(clientAuthentication,
asyncTaskExecutorFactory.getObject().getTaskScheduler(),
restOperations);
this.restOperations);
}
return new SimpleSessionManager(clientAuthentication);
@@ -201,7 +203,7 @@ public class VaultBootstrapConfiguration implements InitializingBean {
public ClientAuthentication clientAuthentication() {
ClientAuthenticationFactory factory = new ClientAuthenticationFactory(
vaultProperties, restOperations, externalRestOperations);
this.vaultProperties, this.restOperations, this.externalRestOperations);
return factory.createClientAuthentication();
}
@@ -218,17 +220,19 @@ public class VaultBootstrapConfiguration implements InitializingBean {
}
ThreadPoolTaskScheduler getTaskScheduler() {
return taskScheduler;
return this.taskScheduler;
}
@Override
public void destroy() throws Exception {
taskScheduler.destroy();
this.taskScheduler.destroy();
}
@Override
public void afterPropertiesSet() throws Exception {
taskScheduler.afterPropertiesSet();
this.taskScheduler.afterPropertiesSet();
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Arrays;
@@ -66,11 +67,11 @@ public class VaultBootstrapPropertySourceConfiguration implements InitializingBe
@SuppressWarnings("unchecked")
public void afterPropertiesSet() {
this.vaultSecretBackendDescriptors = applicationContext.getBeansOfType(
VaultSecretBackendDescriptor.class).values();
this.vaultSecretBackendDescriptors = this.applicationContext
.getBeansOfType(VaultSecretBackendDescriptor.class).values();
this.factories = (Collection) applicationContext.getBeansOfType(
SecretBackendMetadataFactory.class).values();
this.factories = (Collection) this.applicationContext
.getBeansOfType(SecretBackendMetadataFactory.class).values();
}
@Bean
@@ -83,21 +84,20 @@ public class VaultBootstrapPropertySourceConfiguration implements InitializingBe
VaultConfigTemplate vaultConfigTemplate = new VaultConfigTemplate(operations,
vaultProperties);
PropertySourceLocatorConfiguration configuration = getPropertySourceConfiguration(Arrays
.asList(kvBackendProperties, genericBackendProperties));
PropertySourceLocatorConfiguration configuration = getPropertySourceConfiguration(
Arrays.asList(kvBackendProperties, genericBackendProperties));
if (vaultProperties.getConfig().getLifecycle().isEnabled()) {
// This is to destroy bootstrap resources
// otherwise, the bootstrap context is not shut down cleanly
applicationContext.registerShutdownHook();
this.applicationContext.registerShutdownHook();
SecretLeaseContainer secretLeaseContainer = secretLeaseContainerObjectFactory
.getObject();
secretLeaseContainer.start();
return new LeasingVaultPropertySourceLocator(vaultProperties,
configuration,
return new LeasingVaultPropertySourceLocator(vaultProperties, configuration,
secretLeaseContainer);
}
@@ -107,15 +107,14 @@ public class VaultBootstrapPropertySourceConfiguration implements InitializingBe
/**
* Apply configuration through {@link VaultConfigurer}.
*
* @param keyValueBackends configured backend (key-value, generic secret backend).
* @return
* @return the {@link PropertySourceLocatorConfiguration}.
*/
private PropertySourceLocatorConfiguration getPropertySourceConfiguration(
List<VaultKeyValueBackendPropertiesSupport> keyValueBackends) {
Collection<VaultConfigurer> configurers = applicationContext.getBeansOfType(
VaultConfigurer.class).values();
Collection<VaultConfigurer> configurers = this.applicationContext
.getBeansOfType(VaultConfigurer.class).values();
DefaultSecretBackendConfigurer secretBackendConfigurer = new DefaultSecretBackendConfigurer();
@@ -139,7 +138,7 @@ public class VaultBootstrapPropertySourceConfiguration implements InitializingBe
}
List<String> contexts = KeyValueSecretBackendMetadata.buildContexts(
keyValueBackend, Arrays.asList(applicationContext
keyValueBackend, Arrays.asList(this.applicationContext
.getEnvironment().getActiveProfiles()));
if (keyValueBackend instanceof VaultKeyValueBackendProperties
@@ -147,20 +146,21 @@ public class VaultBootstrapPropertySourceConfiguration implements InitializingBe
.getBackendVersion() == 2) {
for (String context : contexts) {
secretBackendConfigurer.add(KeyValueSecretBackendMetadata.create(
keyValueBackend.getBackend(), context));
secretBackendConfigurer.add(KeyValueSecretBackendMetadata
.create(keyValueBackend.getBackend(), context));
}
}
else {
for (String context : contexts) {
secretBackendConfigurer.add(GenericSecretBackendMetadata.create(
keyValueBackend.getBackend(), context));
secretBackendConfigurer.add(GenericSecretBackendMetadata
.create(keyValueBackend.getBackend(), context));
}
}
}
Collection<SecretBackendMetadata> backendAccessors = SecretBackendFactories
.createSecretBackendMetadata(vaultSecretBackendDescriptors, factories);
.createSecretBackendMetadata(this.vaultSecretBackendDescriptors,
this.factories);
backendAccessors.forEach(secretBackendConfigurer::add);
}
@@ -168,7 +168,8 @@ public class VaultBootstrapPropertySourceConfiguration implements InitializingBe
if (secretBackendConfigurer.isRegisterDefaultDiscoveredSecretBackends()) {
Collection<SecretBackendMetadata> backendAccessors = SecretBackendFactories
.createSecretBackendMetadata(vaultSecretBackendDescriptors, factories);
.createSecretBackendMetadata(this.vaultSecretBackendDescriptors,
this.factories);
backendAccessors.forEach(secretBackendConfigurer::add);
}
@@ -177,6 +178,8 @@ public class VaultBootstrapPropertySourceConfiguration implements InitializingBe
}
/**
* @param vaultOperations the {@link VaultOperations}.
* @param taskSchedulerWrapper the {@link TaskSchedulerWrapper}.
* @return the {@link SessionManager} for Vault session management.
* @see SessionManager
* @see LifecycleAwareSessionManager
@@ -189,4 +192,5 @@ public class VaultBootstrapPropertySourceConfiguration implements InitializingBe
return new SecretLeaseContainer(vaultOperations,
taskSchedulerWrapper.getTaskScheduler());
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.springframework.vault.core.VaultOperations;
@@ -31,10 +32,9 @@ public interface VaultConfigOperations {
* Read secrets from a secret backend encapsulated within a
* {@link SecretBackendMetadata}. Reading data using this method is suitable for
* secret backends that do not require a request body.
*
* @param secretBackendMetadata must not be {@literal null}.
* @return the configuration data. May be empty but never {@literal null}.
* @throws IllegalStateException if {@link VaultProperties#isFailFast()} is enabled.
* @throws IllegalStateException if {@link VaultProperties#failFast} is enabled.
*/
Secrets read(SecretBackendMetadata secretBackendMetadata);
@@ -42,4 +42,5 @@ public interface VaultConfigOperations {
* @return the underlying {@link VaultOperations}.
*/
VaultOperations getVaultOperations();
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Map;
@@ -36,11 +37,11 @@ import org.springframework.vault.support.VaultResponse;
public class VaultConfigTemplate implements VaultConfigOperations {
private final VaultOperations vaultOperations;
private final VaultProperties properties;
/**
* Create a new {@link VaultConfigTemplate} given {@link VaultOperations}.
*
* @param vaultOperations must not be {@literal null}.
* @param properties must not be {@literal null}.
*/
@@ -63,7 +64,7 @@ public class VaultConfigTemplate implements VaultConfigOperations {
secretBackendMetadata.getPath()));
try {
VaultResponse vaultResponse = vaultOperations
VaultResponse vaultResponse = this.vaultOperations
.read(secretBackendMetadata.getPath());
if (vaultResponse == null) {
@@ -85,7 +86,7 @@ public class VaultConfigTemplate implements VaultConfigOperations {
}
catch (VaultException e) {
if (properties.isFailFast()) {
if (this.properties.isFailFast()) {
throw new IllegalStateException(
"Could not locate PropertySource and the fail fast property is set, failing.",
e);
@@ -118,6 +119,7 @@ public class VaultConfigTemplate implements VaultConfigOperations {
}
public VaultOperations getVaultOperations() {
return vaultOperations;
return this.vaultOperations;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.net.URI;
@@ -25,17 +26,16 @@ import org.springframework.vault.support.SslConfiguration.KeyStoreConfiguration;
/**
* Support class for Vault configuration providing utility methods.
*
*
* @author Mark Paluch
* @since 2.1
*/
class VaultConfigurationUtil {
final class VaultConfigurationUtil {
/**
* Create a {@link SslConfiguration} given {@link Ssl SSL properties}.
*
* @param ssl
* @return
* @param ssl the SSL properties.
* @return the SSL configuration.
*/
static SslConfiguration createSslConfiguration(Ssl ssl) {
@@ -48,8 +48,8 @@ class VaultConfigurationUtil {
if (ssl.getKeyStore() != null) {
if (StringUtils.hasText(ssl.getKeyStorePassword())) {
keyStore = KeyStoreConfiguration.of(ssl.getKeyStore(), ssl
.getKeyStorePassword().toCharArray());
keyStore = KeyStoreConfiguration.of(ssl.getKeyStore(),
ssl.getKeyStorePassword().toCharArray());
}
else {
keyStore = KeyStoreConfiguration.of(ssl.getKeyStore());
@@ -59,8 +59,8 @@ class VaultConfigurationUtil {
if (ssl.getTrustStore() != null) {
if (StringUtils.hasText(ssl.getTrustStorePassword())) {
trustStore = KeyStoreConfiguration.of(ssl.getTrustStore(), ssl
.getTrustStorePassword().toCharArray());
trustStore = KeyStoreConfiguration.of(ssl.getTrustStore(),
ssl.getTrustStorePassword().toCharArray());
}
else {
trustStore = KeyStoreConfiguration.of(ssl.getTrustStore());
@@ -72,9 +72,8 @@ class VaultConfigurationUtil {
/**
* Create a {@link VaultEndpoint} given {@link VaultProperties}.
*
* @param vaultProperties
* @return
* @param vaultProperties the Vault properties.
* @return the endpoint.
*/
static VaultEndpoint createVaultEndpoint(VaultProperties vaultProperties) {
@@ -89,4 +88,9 @@ class VaultConfigurationUtil {
return vaultEndpoint;
}
private VaultConfigurationUtil() {
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
/**
@@ -41,9 +42,9 @@ public interface VaultConfigurer {
/**
* Configure the secret backends that are instantiated as
* {@link org.springframework.core.env.PropertySource property sources}.
*
* @param configurer the {@link SecretBackendConfigurer} to configure secret backends,
* must not be {@literal null}.
*/
void addSecretBackends(SecretBackendConfigurer configurer);
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import javax.validation.constraints.NotEmpty;
@@ -33,8 +34,8 @@ import org.springframework.validation.annotation.Validated;
@ConfigurationProperties("spring.cloud.vault.generic")
@Data
@Validated
public class VaultGenericBackendProperties implements EnvironmentAware,
VaultKeyValueBackendPropertiesSupport {
public class VaultGenericBackendProperties
implements EnvironmentAware, VaultKeyValueBackendPropertiesSupport {
/**
* Enable the generic backend.
@@ -81,4 +82,5 @@ public class VaultGenericBackendProperties implements EnvironmentAware,
}
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
@@ -38,7 +39,7 @@ public class VaultHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Builder builder) {
VaultHealth vaultHealthResponse = vaultOperations.opsForSys().health();
VaultHealth vaultHealthResponse = this.vaultOperations.opsForSys().health();
if (!vaultHealthResponse.isInitialized()) {
builder.down().withDetail("state", "Vault uninitialized");
@@ -61,4 +62,5 @@ public class VaultHealthIndicator extends AbstractHealthIndicator {
builder.withDetail("version", vaultHealthResponse.getVersion());
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
@@ -41,4 +42,5 @@ import org.springframework.context.annotation.Import;
@Import({ VaultHealthIndicatorConfiguration.class,
VaultReactiveHealthIndicatorConfiguration.class })
public class VaultHealthIndicatorAutoConfiguration {
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Map;
@@ -39,7 +40,7 @@ class VaultHealthIndicatorConfiguration extends
private final Map<String, VaultOperations> vaultTemplates;
public VaultHealthIndicatorConfiguration(Map<String, VaultOperations> vaultTemplates) {
VaultHealthIndicatorConfiguration(Map<String, VaultOperations> vaultTemplates) {
this.vaultTemplates = vaultTemplates;
}
@@ -48,4 +49,5 @@ class VaultHealthIndicatorConfiguration extends
public HealthIndicator vaultHealthIndicator() {
return this.createHealthIndicator(this.vaultTemplates);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import javax.validation.constraints.NotEmpty;
@@ -34,8 +35,8 @@ import org.springframework.validation.annotation.Validated;
@ConfigurationProperties("spring.cloud.vault.kv")
@Data
@Validated
public class VaultKeyValueBackendProperties implements EnvironmentAware,
VaultKeyValueBackendPropertiesSupport {
public class VaultKeyValueBackendProperties
implements EnvironmentAware, VaultKeyValueBackendPropertiesSupport {
/**
* Enable the kev-value backend.
@@ -90,4 +91,5 @@ public class VaultKeyValueBackendProperties implements EnvironmentAware,
}
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
/**
@@ -40,7 +41,7 @@ public interface VaultKeyValueBackendPropertiesSupport {
String getDefaultContext();
/**
* Profile separator character.
* @return profile separator character.
*/
String getProfileSeparator();

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.time.Duration;
@@ -73,12 +74,12 @@ public class VaultProperties implements EnvironmentAware {
private Discovery discovery = new Discovery();
/**
* Connection timeout;
* Connection timeout.
*/
private int connectionTimeout = 5000;
/**
* Read timeout;
* Read timeout.
*/
private int readTimeout = 15000;
@@ -129,9 +130,15 @@ public class VaultProperties implements EnvironmentAware {
}
}
/**
* Discovery properties.
*/
@Data
public static class Discovery {
/**
* Default service Id.
*/
public static final String DEFAULT_VAULT = "vault";
/**
@@ -144,8 +151,12 @@ public class VaultProperties implements EnvironmentAware {
* Service id to locate Vault.
*/
private String serviceId = DEFAULT_VAULT;
}
/**
* AppId properties.
*/
@Data
@Validated
public static class AppIdProperties {
@@ -155,14 +166,14 @@ public class VaultProperties implements EnvironmentAware {
*
* @see org.springframework.vault.authentication.MacAddressUserId
*/
public final static String MAC_ADDRESS = "MAC_ADDRESS";
public static final String MAC_ADDRESS = "MAC_ADDRESS";
/**
* Property value for UserId generation using an IP-Address.
*
* @see org.springframework.vault.authentication.IpAddressUserId
*/
public final static String IP_ADDRESS = "IP_ADDRESS";
public static final String IP_ADDRESS = "IP_ADDRESS";
/**
* Mount path of the AppId authentication backend.
@@ -180,8 +191,12 @@ public class VaultProperties implements EnvironmentAware {
*/
@NotEmpty
private String userId = MAC_ADDRESS;
}
/**
* AppRole properties.
*/
@Data
@Validated
public static class AppRoleProperties {
@@ -205,8 +220,12 @@ public class VaultProperties implements EnvironmentAware {
* The SecretId.
*/
private String secretId = null;
}
/**
* AWS-EC2 properties.
*/
@Data
@Validated
public static class AwsEc2Properties {
@@ -233,8 +252,12 @@ public class VaultProperties implements EnvironmentAware {
* generation.
*/
private String nonce;
}
/**
* AWS-IAM properties.
*/
@Data
public static class AwsIamProperties {
@@ -254,8 +277,12 @@ public class VaultProperties implements EnvironmentAware {
* headers of login requests.
*/
private String serverName;
}
/**
* Azure MSI properties.
*/
@Data
public static class AzureMsiProperties {
@@ -269,8 +296,12 @@ public class VaultProperties implements EnvironmentAware {
* Name of the role.
*/
private String role = "";
}
/**
* GCP-GCE properties.
*/
@Data
public static class GcpGceProperties {
@@ -289,8 +320,12 @@ public class VaultProperties implements EnvironmentAware {
* Optional service account id. Using the default id if left unconfigured.
*/
private String serviceAccount = "";
}
/**
* GCP-IAM properties.
*/
@Data
public static class GcpIamProperties {
@@ -324,8 +359,12 @@ public class VaultProperties implements EnvironmentAware {
* Credentials configuration.
*/
private final GcpCredentials credentials = new GcpCredentials();
}
/**
* GCP credential properties.
*/
@Data
public static class GcpCredentials {
@@ -342,8 +381,12 @@ public class VaultProperties implements EnvironmentAware {
* The base64 encoded contents of an OAuth2 account private key in JSON format.
*/
private String encodedKey;
}
/**
* Kubernetes properties.
*/
@Data
public static class KubernetesProperties {
@@ -363,8 +406,12 @@ public class VaultProperties implements EnvironmentAware {
*/
@NotEmpty
private String serviceAccountTokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token";
}
/**
* SSL properties.
*/
@Data
@Validated
public static class Ssl {
@@ -394,8 +441,12 @@ public class VaultProperties implements EnvironmentAware {
*/
@NotEmpty
private String certAuthPath = "cert";
}
/**
* Property source properties.
*/
@Data
public static class Config {
@@ -408,6 +459,7 @@ public class VaultProperties implements EnvironmentAware {
private int order = 0;
private Lifecycle lifecycle = new Lifecycle();
}
/**
@@ -421,9 +473,16 @@ public class VaultProperties implements EnvironmentAware {
* Enable lifecycle management.
*/
private boolean enabled = true;
}
/**
* Enumeration of authentication methods.
*/
public enum AuthenticationMethod {
TOKEN, APPID, APPROLE, AWS_EC2, AWS_IAM, AZURE_MSI, CERT, CUBBYHOLE, GCP_GCE, GCP_IAM, KUBERNETES
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.LinkedHashMap;
@@ -43,12 +44,11 @@ class VaultPropertySource extends EnumerablePropertySource<VaultConfigOperations
/**
* Creates a new {@link VaultPropertySource}.
*
* @param operations must not be {@literal null}.
* @param failFast fail if properties could not be read because of access errors.
* @param secretBackendMetadata must not be {@literal null}.
*/
public VaultPropertySource(VaultConfigOperations operations, boolean failFast,
VaultPropertySource(VaultConfigOperations operations, boolean failFast,
SecretBackendMetadata secretBackendMetadata) {
super(secretBackendMetadata.getName(), operations);
@@ -68,16 +68,16 @@ class VaultPropertySource extends EnumerablePropertySource<VaultConfigOperations
try {
this.secrets = this.source.read(this.secretBackendMetadata);
if (this.secrets != null) {
this.properties.putAll(secrets.getData());
this.properties.putAll(this.secrets.getData());
}
}
catch (RuntimeException e) {
String message = String.format(
"Unable to read properties from Vault using %s for %s ", getName(),
secretBackendMetadata.getVariables());
this.secretBackendMetadata.getVariables());
if (failFast) {
if (this.failFast) {
throw e;
}
@@ -95,4 +95,5 @@ class VaultPropertySource extends EnumerablePropertySource<VaultConfigOperations
Set<String> strings = this.properties.keySet();
return strings.toArray(new String[strings.size()]);
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
@@ -33,17 +34,17 @@ class VaultPropertySourceLocator extends VaultPropertySourceLocatorSupport
implements PriorityOrdered {
private final VaultConfigOperations operations;
private final VaultProperties properties;
/**
* Creates a new {@link VaultPropertySourceLocator}.
*
* @param operations must not be {@literal null}.
* @param properties must not be {@literal null}.
* @param propertySourceLocatorConfiguration must not be {@literal null}.
* @since 1.1
*/
public VaultPropertySourceLocator(VaultConfigOperations operations,
VaultPropertySourceLocator(VaultConfigOperations operations,
VaultProperties properties,
PropertySourceLocatorConfiguration propertySourceLocatorConfiguration) {
@@ -58,7 +59,7 @@ class VaultPropertySourceLocator extends VaultPropertySourceLocatorSupport
@Override
public int getOrder() {
return properties.getConfig().getOrder();
return this.properties.getConfig().getOrder();
}
/**
@@ -74,9 +75,8 @@ class VaultPropertySourceLocator extends VaultPropertySourceLocatorSupport
}
/**
* Create {@link VaultPropertySource} initialized with a
* {@link SecretBackendMetadata}.
*
* Create {@link VaultPropertySource} initialized with a {@link SecretBackendMetadata}
* .
* @param accessor the {@link SecretBackendMetadata}.
* @return the {@link VaultPropertySource} to use.
*/
@@ -85,4 +85,5 @@ class VaultPropertySourceLocator extends VaultPropertySourceLocatorSupport
return new VaultPropertySource(this.operations, this.properties.isFailFast(),
accessor);
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.ArrayList;
@@ -31,8 +32,6 @@ import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.util.Assert;
import static org.springframework.cloud.vault.config.GenericSecretBackendMetadata.*;
/**
* Abstract {@link PropertySourceLocator} to create {@link PropertySource}s based on
* {@link VaultGenericBackendProperties} and {@link SecretBackendMetadata}.
@@ -47,7 +46,6 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
/**
* Creates a new {@link VaultPropertySourceLocatorSupport}.
*
* @param propertySourceName must not be {@literal null} or empty.
* @param genericBackendProperties must not be {@literal null}.
* @param backendAccessors must not be {@literal null}.
@@ -63,7 +61,6 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
/**
* Creates a new {@link VaultPropertySourceLocatorSupport} given a
* {@link PropertySourceLocatorConfiguration}.
*
* @param propertySourceName must not be {@literal null} or empty.
* @param propertySourceLocatorConfiguration must not be {@literal null}.
* @since 1.1
@@ -108,8 +105,8 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
@Override
public PropertySource<?> locate(Environment environment) {
if (propertySourceLocatorConfiguration instanceof EnvironmentAware) {
((EnvironmentAware) propertySourceLocatorConfiguration)
if (this.propertySourceLocatorConfiguration instanceof EnvironmentAware) {
((EnvironmentAware) this.propertySourceLocatorConfiguration)
.setEnvironment(environment);
}
@@ -127,7 +124,6 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
/**
* Allows initialization the {@link PropertySource} before use. Implementations may
* override this method to preload properties in the {@link PropertySource}.
*
* @param propertySource must not be {@literal null}.
*/
protected void initialize(CompositePropertySource propertySource) {
@@ -135,28 +131,26 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
/**
* Creates a {@link CompositePropertySource}.
*
* @param environment must not be {@literal null}.
* @return
* @return the composite {@link PropertySource}.
*/
protected CompositePropertySource createCompositePropertySource(
Environment environment) {
List<PropertySource<?>> propertySources = doCreatePropertySources(environment);
return doCreateCompositePropertySource(propertySourceName, propertySources);
return doCreateCompositePropertySource(this.propertySourceName, propertySources);
}
/**
* Create {@link PropertySource}s given {@link Environment} from the property
* configuration.
*
* @param environment must not be {@literal null}.
* @return a {@link List} of ordered {@link PropertySource}s.
*/
protected List<PropertySource<?>> doCreatePropertySources(Environment environment) {
Collection<SecretBackendMetadata> secretBackends = propertySourceLocatorConfiguration
Collection<SecretBackendMetadata> secretBackends = this.propertySourceLocatorConfiguration
.getSecretBackends();
List<SecretBackendMetadata> sorted = new ArrayList<>(secretBackends);
List<PropertySource<?>> propertySources = new ArrayList<>();
@@ -179,9 +173,8 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
* Create {@link PropertySource}s using the generic {@literal secret} backend.
* Property sources for the generic secret backend derive from the application name
* and active profiles to generate context paths.
*
* @param environment must not be {@literal null}.
* @return
* @return {@link List} of {@link PropertySource}s.
*/
protected List<PropertySource<?>> doCreateGenericPropertySources(
Environment environment) {
@@ -191,7 +184,6 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
/**
* Create a {@link CompositePropertySource} given a {@link List} of
* {@link PropertySource}s.
*
* @param propertySourceName the property source name.
* @param propertySources the property sources.
* @return the {@link CompositePropertySource} to use.
@@ -210,9 +202,8 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
}
/**
* Create {@link VaultPropertySource} initialized with a
* {@link SecretBackendMetadata}.
*
* Create {@link VaultPropertySource} initialized with a {@link SecretBackendMetadata}
* .
* @param accessor the {@link SecretBackendMetadata}.
* @return the {@link VaultPropertySource} to use.
*/
@@ -235,16 +226,17 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
@Override
public Collection<SecretBackendMetadata> getSecretBackends() {
if (genericBackendProperties.isEnabled()) {
if (this.genericBackendProperties.isEnabled()) {
List<String> contexts = GenericSecretBackendMetadata.buildContexts(
genericBackendProperties,
Arrays.asList(environment.getActiveProfiles()));
this.genericBackendProperties,
Arrays.asList(this.environment.getActiveProfiles()));
List<SecretBackendMetadata> result = new ArrayList<>(contexts.size());
for (String context : contexts) {
result.add(create(genericBackendProperties.getBackend(), context));
result.add(GenericSecretBackendMetadata
.create(this.genericBackendProperties.getBackend(), context));
}
return result;
@@ -252,6 +244,7 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
return Collections.emptyList();
}
}
@RequiredArgsConstructor
@@ -262,8 +255,9 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
@Override
public Collection<SecretBackendMetadata> getSecretBackends() {
return metadata;
return this.metadata;
}
}
private static class CompositePropertySourceConfiguration
@@ -271,7 +265,7 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
private final List<PropertySourceLocatorConfiguration> configurations;
public CompositePropertySourceConfiguration(
CompositePropertySourceConfiguration(
PropertySourceLocatorConfiguration... configurations) {
List<PropertySourceLocatorConfiguration> copy = new ArrayList<>(
@@ -287,7 +281,7 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
List<SecretBackendMetadata> result = new ArrayList<>();
for (PropertySourceLocatorConfiguration configuration : configurations) {
for (PropertySourceLocatorConfiguration configuration : this.configurations) {
result.addAll(configuration.getSecretBackends());
}
@@ -297,11 +291,13 @@ public abstract class VaultPropertySourceLocatorSupport implements PropertySourc
@Override
public void setEnvironment(Environment environment) {
for (PropertySourceLocatorConfiguration configuration : configurations) {
for (PropertySourceLocatorConfiguration configuration : this.configurations) {
if (configuration instanceof EnvironmentAware) {
((EnvironmentAware) configuration).setEnvironment(environment);
}
}
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.time.Duration;
@@ -92,14 +93,14 @@ public class VaultReactiveBootstrapConfiguration {
* Creates a {@link ClientHttpConnector} configured with {@link ClientOptions} and
* {@link SslConfiguration} which are not necessarily applicable for the whole
* application.
*
* @param vaultProperties the Vault properties.
* @return the {@link ClientHttpConnector}.
*/
private static ClientHttpConnector createConnector(VaultProperties vaultProperties) {
ClientOptions clientOptions = new ClientOptions(Duration.ofMillis(vaultProperties
.getConnectionTimeout()), Duration.ofMillis(vaultProperties
.getReadTimeout()));
ClientOptions clientOptions = new ClientOptions(
Duration.ofMillis(vaultProperties.getConnectionTimeout()),
Duration.ofMillis(vaultProperties.getReadTimeout()));
SslConfiguration sslConfiguration = VaultConfigurationUtil
.createSslConfiguration(vaultProperties.getSsl());
@@ -109,19 +110,22 @@ public class VaultReactiveBootstrapConfiguration {
/**
* Creates a {@link ReactiveVaultTemplate}.
*
* @return
* @param tokenSupplier the {@link VaultTokenSupplier}.
* @return the {@link ReactiveVaultTemplate} bean.
* @see #reactiveVaultSessionManager(BeanFactory, ObjectFactory)
*/
@Bean
@ConditionalOnMissingBean(ReactiveVaultOperations.class)
public ReactiveVaultTemplate reactiveVaultTemplate(
ReactiveSessionManager tokenSupplier) {
return new ReactiveVaultTemplate(vaultEndpoint, clientHttpConnector,
return new ReactiveVaultTemplate(this.vaultEndpoint, this.clientHttpConnector,
tokenSupplier);
}
/**
* @param beanFactory the {@link BeanFactory}.
* @param asyncTaskExecutorFactory the {@link ObjectFactory} for
* {@link TaskSchedulerWrapper}.
* @return {@link ReactiveSessionManager} for reactive session use.
* @see ReactiveSessionManager
* @see ReactiveLifecycleAwareSessionManager
@@ -134,10 +138,10 @@ public class VaultReactiveBootstrapConfiguration {
VaultTokenSupplier vaultTokenSupplier = beanFactory.getBean("vaultTokenSupplier",
VaultTokenSupplier.class);
if (vaultProperties.getConfig().getLifecycle().isEnabled()) {
if (this.vaultProperties.getConfig().getLifecycle().isEnabled()) {
WebClient webClient = ReactiveVaultClients.createWebClient(vaultEndpoint,
clientHttpConnector);
WebClient webClient = ReactiveVaultClients.createWebClient(this.vaultEndpoint,
this.clientHttpConnector);
return new ReactiveLifecycleAwareSessionManager(vaultTokenSupplier,
asyncTaskExecutorFactory.getObject().getTaskScheduler(), webClient);
}
@@ -146,6 +150,7 @@ public class VaultReactiveBootstrapConfiguration {
}
/**
* @param sessionManager the {@link ReactiveSessionManager}.
* @return {@link SessionManager} adapter wrapping {@link ReactiveSessionManager}.
*/
@Bean
@@ -155,6 +160,7 @@ public class VaultReactiveBootstrapConfiguration {
}
/**
* @param beanFactory the {@link BeanFactory}.
* @return the {@link VaultTokenSupplier} for reactive Vault session management
* adapting {@link ClientAuthentication} that also implement
* {@link AuthenticationStepsFactory}.
@@ -191,14 +197,14 @@ public class VaultReactiveBootstrapConfiguration {
}
if (clientAuthentication instanceof AuthenticationStepsFactory) {
return createAuthenticationStepsOperator((AuthenticationStepsFactory) clientAuthentication);
return createAuthenticationStepsOperator(
(AuthenticationStepsFactory) clientAuthentication);
}
throw new IllegalStateException(
String.format(
"Cannot construct VaultTokenSupplier from %s. "
+ "ClientAuthentication must implement AuthenticationStepsFactory or be TokenAuthentication",
clientAuthentication));
throw new IllegalStateException(String.format(
"Cannot construct VaultTokenSupplier from %s. "
+ "ClientAuthentication must implement AuthenticationStepsFactory or be TokenAuthentication",
clientAuthentication));
}
throw new IllegalStateException(
@@ -212,4 +218,5 @@ public class VaultReactiveBootstrapConfiguration {
return new AuthenticationStepsOperator(factory.getAuthenticationSteps(),
webClient);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.lang.reflect.UndeclaredThrowableException;
@@ -49,14 +50,12 @@ public class VaultReactiveHealthIndicator extends AbstractReactiveHealthIndicato
@Override
protected Mono<Health> doHealthCheck(Builder builder) {
return vaultOperations
.doWithSession(it -> it.get().uri("sys/health").exchange())
.flatMap(it -> it.bodyToMono(VaultHealthImpl.class))
return this.vaultOperations
.doWithSession((it) -> it.get().uri("sys/health").exchange())
.flatMap((it) -> it.bodyToMono(VaultHealthImpl.class))
.onErrorResume(WebClientResponseException.class,
VaultReactiveHealthIndicator::deserializeError)
.map(vaultHealthResponse -> {
return getHealth(builder, vaultHealthResponse);
});
.map((vaultHealthResponse) -> getHealth(builder, vaultHealthResponse));
}
private static Mono<? extends VaultHealthImpl> deserializeError(
@@ -74,7 +73,8 @@ public class VaultReactiveHealthIndicator extends AbstractReactiveHealthIndicato
}
}
private static Health getHealth(Builder builder, VaultHealthImpl vaultHealthResponse) {
private static Health getHealth(Builder builder,
VaultHealthImpl vaultHealthResponse) {
if (!vaultHealthResponse.isInitialized()) {
builder.withDetail("state", "Vault uninitialized");
@@ -101,11 +101,14 @@ public class VaultReactiveHealthIndicator extends AbstractReactiveHealthIndicato
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
static class VaultHealthImpl implements VaultHealth {
private static final class VaultHealthImpl implements VaultHealth {
private final boolean initialized;
private final boolean sealed;
private final boolean standby;
private final int serverTimeUtc;
@Nullable
@@ -123,5 +126,7 @@ public class VaultReactiveHealthIndicator extends AbstractReactiveHealthIndicato
this.serverTimeUtc = serverTimeUtc;
this.version = version;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Map;
@@ -37,20 +38,20 @@ import org.springframework.vault.core.ReactiveVaultOperations;
@Configuration
@ConditionalOnClass(Flux.class)
@ConditionalOnBean(ReactiveVaultOperations.class)
class VaultReactiveHealthIndicatorConfiguration
extends
class VaultReactiveHealthIndicatorConfiguration extends
CompositeReactiveHealthIndicatorConfiguration<VaultReactiveHealthIndicator, ReactiveVaultOperations> {
private final Map<String, ReactiveVaultOperations> reactiveVaultTemplates;
public VaultReactiveHealthIndicatorConfiguration(
VaultReactiveHealthIndicatorConfiguration(
Map<String, ReactiveVaultOperations> reactiveVaultTemplates) {
this.reactiveVaultTemplates = reactiveVaultTemplates;
}
@Bean
@ConditionalOnMissingBean(name = { "vaultReactiveHealthIndicator" })
public ReactiveHealthIndicator vaultReactiveHealthIndicator() {
ReactiveHealthIndicator vaultReactiveHealthIndicator() {
return this.createHealthIndicator(this.reactiveVaultTemplates);
}
}

View File

@@ -31,7 +31,6 @@ public interface VaultSecretBackendDescriptor {
/**
* Backend path without leading/trailing slashes.
*
* @return the backend path such as {@code secret} or {@code mysql}.
*/
String getBackend();
@@ -40,4 +39,5 @@ public interface VaultSecretBackendDescriptor {
* @return {@literal true} if the backend is enabled.
*/
boolean isEnabled();
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.springframework.cloud.client.ServiceInstance;
@@ -28,10 +29,10 @@ public interface VaultServiceInstanceProvider {
/**
* Lookup {@link ServiceInstance} by {@code serviceId}.
*
* @param serviceId the service Id.
* @return {@link ServiceInstance} for the given {@code serviceId}.
* @throws IllegalStateException if no service with {@code serviceId} was found.
*/
ServiceInstance getVaultServerInstance(String serviceId);
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.junit.Test;
@@ -65,4 +66,5 @@ public class ApplicationFailFastTests {
"--server.port=0", "--spring.cloud.vault.failFast=false",
"--spring.cloud.vault.port=9999");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.junit.Test;
@@ -22,7 +23,8 @@ import org.springframework.vault.authentication.AppRoleAuthenticationOptions.Rol
import org.springframework.vault.authentication.AppRoleAuthenticationOptions.SecretId;
import org.springframework.vault.support.VaultToken;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Unit tests for {@link }ClientAuthenticationFactory}.
@@ -42,8 +44,8 @@ public class ClientAuthenticationFactoryUnitTests {
.getAppRoleAuthenticationOptions(properties);
assertThat(options.getRoleId()).isInstanceOf(RoleId.provided("foo").getClass());
assertThat(options.getSecretId()).isInstanceOf(
SecretId.provided("bar").getClass());
assertThat(options.getSecretId())
.isInstanceOf(SecretId.provided("bar").getClass());
}
@Test
@@ -72,8 +74,8 @@ public class ClientAuthenticationFactoryUnitTests {
assertThat(options.getAppRole()).isEqualTo("my-role");
assertThat(options.getRoleId()).isInstanceOf(RoleId.provided("foo").getClass());
assertThat(options.getSecretId()).isInstanceOf(
SecretId.pull(VaultToken.of("token")).getClass());
assertThat(options.getSecretId())
.isInstanceOf(SecretId.pull(VaultToken.of("token")).getClass());
}
@Test
@@ -87,10 +89,10 @@ public class ClientAuthenticationFactoryUnitTests {
.getAppRoleAuthenticationOptions(properties);
assertThat(options.getAppRole()).isEqualTo("my-role");
assertThat(options.getRoleId()).isInstanceOf(
RoleId.pull(VaultToken.of("token")).getClass());
assertThat(options.getSecretId()).isInstanceOf(
SecretId.pull(VaultToken.of("token")).getClass());
assertThat(options.getRoleId())
.isInstanceOf(RoleId.pull(VaultToken.of("token")).getClass());
assertThat(options.getSecretId())
.isInstanceOf(SecretId.pull(VaultToken.of("token")).getClass());
}
@Test
@@ -102,10 +104,10 @@ public class ClientAuthenticationFactoryUnitTests {
AppRoleAuthenticationOptions options = ClientAuthenticationFactory
.getAppRoleAuthenticationOptions(properties);
assertThat(options.getRoleId()).isInstanceOf(
RoleId.wrapped(VaultToken.of("token")).getClass());
assertThat(options.getSecretId()).isInstanceOf(
SecretId.wrapped(VaultToken.of("token")).getClass());
assertThat(options.getRoleId())
.isInstanceOf(RoleId.wrapped(VaultToken.of("token")).getClass());
assertThat(options.getSecretId())
.isInstanceOf(SecretId.wrapped(VaultToken.of("token")).getClass());
}
@Test
@@ -118,10 +120,10 @@ public class ClientAuthenticationFactoryUnitTests {
AppRoleAuthenticationOptions options = ClientAuthenticationFactory
.getAppRoleAuthenticationOptions(properties);
assertThat(options.getRoleId()).isInstanceOf(
RoleId.wrapped(VaultToken.of("token")).getClass());
assertThat(options.getSecretId()).isInstanceOf(
SecretId.provided("bar").getClass());
assertThat(options.getRoleId())
.isInstanceOf(RoleId.wrapped(VaultToken.of("token")).getClass());
assertThat(options.getSecretId())
.isInstanceOf(SecretId.provided("bar").getClass());
}
@Test
@@ -135,8 +137,8 @@ public class ClientAuthenticationFactoryUnitTests {
.getAppRoleAuthenticationOptions(properties);
assertThat(options.getRoleId()).isInstanceOf(RoleId.provided("foo").getClass());
assertThat(options.getSecretId()).isInstanceOf(
SecretId.wrapped(VaultToken.of("token")).getClass());
assertThat(options.getSecretId())
.isInstanceOf(SecretId.wrapped(VaultToken.of("token")).getClass());
}
@Test
@@ -144,10 +146,9 @@ public class ClientAuthenticationFactoryUnitTests {
VaultProperties properties = new VaultProperties();
assertThatThrownBy(
() -> ClientAuthenticationFactory
.getAppRoleAuthenticationOptions(properties)).isInstanceOf(
IllegalArgumentException.class);
assertThatThrownBy(() -> ClientAuthenticationFactory
.getAppRoleAuthenticationOptions(properties))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@@ -156,9 +157,9 @@ public class ClientAuthenticationFactoryUnitTests {
VaultProperties properties = new VaultProperties();
properties.getAppRole().setRole("my-role");
assertThatThrownBy(
() -> ClientAuthenticationFactory
.getAppRoleAuthenticationOptions(properties)).isInstanceOf(
IllegalArgumentException.class);
assertThatThrownBy(() -> ClientAuthenticationFactory
.getAppRoleAuthenticationOptions(properties))
.isInstanceOf(IllegalArgumentException.class);
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.net.URI;
@@ -33,9 +34,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.vault.client.VaultEndpoint;
import org.springframework.vault.client.VaultEndpointProvider;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.when;
/**
* Tests for {@link DiscoveryClientVaultBootstrapConfiguration}.
@@ -52,8 +53,7 @@ public class DiscoveryClientVaultBootstrapConfigurationTests {
@Test
public void shouldRegisterDefaultBeans() {
contextRunner
.withUserConfiguration(DiscoveryConfiguration.class)
this.contextRunner.withUserConfiguration(DiscoveryConfiguration.class)
.withPropertyValues("spring.cloud.vault.token=foo",
"spring.cloud.vault.discovery.enabled=true")
.run(context -> {
@@ -72,30 +72,28 @@ public class DiscoveryClientVaultBootstrapConfigurationTests {
@Test
public void shouldNotRegisterBeansIfDiscoveryDisabled() {
contextRunner
.withUserConfiguration(DiscoveryConfiguration.class)
this.contextRunner.withUserConfiguration(DiscoveryConfiguration.class)
.withPropertyValues("spring.cloud.vault.token=foo",
"spring.cloud.vault.discovery.enabled=false")
.run(context -> {
assertThat(
context.getBeanNamesForType(VaultServiceInstanceProvider.class))
.isEmpty();
assertThat(context
.getBeanNamesForType(VaultServiceInstanceProvider.class))
.isEmpty();
});
}
@Test
public void shouldNotRegisterBeansIfVaultDisabled() {
contextRunner
.withUserConfiguration(DiscoveryConfiguration.class)
this.contextRunner.withUserConfiguration(DiscoveryConfiguration.class)
.withPropertyValues("spring.cloud.vault.token=foo",
"spring.cloud.vault.enabled=false")
.run(context -> {
assertThat(
context.getBeanNamesForType(VaultServiceInstanceProvider.class))
.isEmpty();
assertThat(context
.getBeanNamesForType(VaultServiceInstanceProvider.class))
.isEmpty();
});
}
@@ -107,21 +105,27 @@ public class DiscoveryClientVaultBootstrapConfigurationTests {
DiscoveryClient discoveryClient() {
DiscoveryClient mock = Mockito.mock(DiscoveryClient.class);
when(mock.getInstances(anyString())).thenReturn(
Collections.singletonList(new SimpleServiceInstance(URI
.create("https://foo:1234"))));
when(mock.getInstances(anyString())).thenReturn(Collections.singletonList(
new SimpleServiceInstance(URI.create("https://foo:1234"))));
return mock;
}
}
@Data
static class SimpleServiceInstance implements ServiceInstance {
private URI uri;
private String host;
private int port;
private boolean secure;
private Map<String, String> metadata = new LinkedHashMap<>();
private String serviceId;
public SimpleServiceInstance(URI uri) {
@@ -138,6 +142,7 @@ public class DiscoveryClientVaultBootstrapConfigurationTests {
}
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Arrays;
@@ -21,7 +22,7 @@ import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link GenericSecretBackendMetadata}.
@@ -35,8 +36,8 @@ public class GenericSecretBackendMetadataUnitTests {
@Test
public void shouldCreateDefaultContexts() {
List<String> contexts = GenericSecretBackendMetadata.buildContexts(properties,
Collections.emptyList());
List<String> contexts = GenericSecretBackendMetadata
.buildContexts(this.properties, Collections.emptyList());
assertThat(contexts).hasSize(1).contains("application");
}
@@ -44,10 +45,10 @@ public class GenericSecretBackendMetadataUnitTests {
@Test
public void shouldCreateDefaultForAppNameAndDefaultContext() {
properties.setApplicationName("my-app");
this.properties.setApplicationName("my-app");
List<String> contexts = GenericSecretBackendMetadata.buildContexts(properties,
Collections.emptyList());
List<String> contexts = GenericSecretBackendMetadata
.buildContexts(this.properties, Collections.emptyList());
assertThat(contexts).hasSize(2).containsSequence("my-app", "application");
}
@@ -55,10 +56,10 @@ public class GenericSecretBackendMetadataUnitTests {
@Test
public void shouldCreateDefaultForAppNameAndDefaultContextWithProfiles() {
properties.setApplicationName("my-app");
this.properties.setApplicationName("my-app");
List<String> contexts = GenericSecretBackendMetadata.buildContexts(properties,
Arrays.asList("cloud", "local"));
List<String> contexts = GenericSecretBackendMetadata
.buildContexts(this.properties, Arrays.asList("cloud", "local"));
assertThat(contexts).hasSize(6).containsSequence("my-app/local", "my-app/cloud",
"my-app", "application/local", "application/cloud", "application");
@@ -67,11 +68,11 @@ public class GenericSecretBackendMetadataUnitTests {
@Test
public void shouldCreateAppNameContextIfDefaultIsDisabled() {
properties.setApplicationName("my-app");
properties.setDefaultContext("");
this.properties.setApplicationName("my-app");
this.properties.setDefaultContext("");
List<String> contexts = GenericSecretBackendMetadata.buildContexts(properties,
Collections.emptyList());
List<String> contexts = GenericSecretBackendMetadata
.buildContexts(this.properties, Collections.emptyList());
assertThat(contexts).hasSize(1).containsSequence("my-app");
}
@@ -79,10 +80,10 @@ public class GenericSecretBackendMetadataUnitTests {
@Test
public void shouldCreateContextsForCommaSeparatedAppName() {
properties.setApplicationName("foo,bar");
this.properties.setApplicationName("foo,bar");
List<String> contexts = GenericSecretBackendMetadata.buildContexts(properties,
Collections.emptyList());
List<String> contexts = GenericSecretBackendMetadata
.buildContexts(this.properties, Collections.emptyList());
assertThat(contexts).hasSize(3).containsSequence("bar", "foo", "application");
}
@@ -90,13 +91,14 @@ public class GenericSecretBackendMetadataUnitTests {
@Test
public void shouldCreateContextsWithProfile() {
properties.setApplicationName("foo,bar");
this.properties.setApplicationName("foo,bar");
List<String> contexts = GenericSecretBackendMetadata.buildContexts(properties,
Arrays.asList("cloud", "local"));
List<String> contexts = GenericSecretBackendMetadata
.buildContexts(this.properties, Arrays.asList("cloud", "local"));
assertThat(contexts).hasSize(9).containsSequence("bar/local", "bar/cloud", "bar",
"foo/local", "foo/cloud", "foo", "application/local", "application/cloud",
"application");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.HashMap;
@@ -24,8 +25,8 @@ import org.junit.Test;
import org.springframework.cloud.vault.util.IntegrationTestSupport;
import org.springframework.cloud.vault.util.Settings;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.cloud.vault.config.GenericSecretBackendMetadata.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.cloud.vault.config.GenericSecretBackendMetadata.create;
/**
* Integration tests for {@link VaultConfigTemplate} using the generic secret backend.
@@ -35,22 +36,23 @@ import static org.springframework.cloud.vault.config.GenericSecretBackendMetadat
public class GenericSecretIntegrationTests extends IntegrationTestSupport {
private VaultProperties vaultProperties = Settings.createVaultProperties();
private VaultConfigOperations configOperations;
@Before
public void setUp() {
vaultProperties.setFailFast(false);
this.vaultProperties.setFailFast(false);
prepare().getVaultOperations().write("secret/app-name", createData());
configOperations = new VaultConfigTemplate(prepare().getVaultOperations(),
vaultProperties);
this.configOperations = new VaultConfigTemplate(prepare().getVaultOperations(),
this.vaultProperties);
}
@Test
public void shouldReturnSecretsCorrectly() {
Map<String, Object> secretProperties = configOperations
Map<String, Object> secretProperties = this.configOperations
.read(create("secret", "app-name")).getData();
assertThat(secretProperties).containsAllEntriesOf(createExpectedMap());
@@ -59,7 +61,7 @@ public class GenericSecretIntegrationTests extends IntegrationTestSupport {
@Test
public void shouldReturnNullIfNotFound() {
Secrets secrets = configOperations.read(create("secret", "missing"));
Secrets secrets = this.configOperations.read(create("secret", "missing"));
assertThat(secrets).isNull();
}
@@ -85,4 +87,5 @@ public class GenericSecretIntegrationTests extends IntegrationTestSupport {
return data;
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.junit.Before;
@@ -50,10 +51,10 @@ public class LeasingVaultPropertySourceLocatorUnitTests {
@Before
public void before() {
propertySourceLocator = new LeasingVaultPropertySourceLocator(
this.propertySourceLocator = new LeasingVaultPropertySourceLocator(
new VaultProperties(), VaultPropertySourceLocatorSupport
.createConfiguration(new VaultGenericBackendProperties()),
secretLeaseContainer);
this.secretLeaseContainer);
}
@Test
@@ -62,27 +63,27 @@ public class LeasingVaultPropertySourceLocatorUnitTests {
VaultProperties vaultProperties = new VaultProperties();
vaultProperties.getConfig().setOrder(10);
propertySourceLocator = new LeasingVaultPropertySourceLocator(vaultProperties,
VaultPropertySourceLocatorSupport.createConfiguration(
this.propertySourceLocator = new LeasingVaultPropertySourceLocator(
vaultProperties, VaultPropertySourceLocatorSupport.createConfiguration(
new VaultGenericBackendProperties()),
secretLeaseContainer);
this.secretLeaseContainer);
assertThat(propertySourceLocator.getOrder()).isEqualTo(10);
assertThat(this.propertySourceLocator.getOrder()).isEqualTo(10);
}
@Test
public void shouldLocatePropertySources() {
when(configurableEnvironment.getActiveProfiles()).thenReturn(new String[0]);
when(this.configurableEnvironment.getActiveProfiles()).thenReturn(new String[0]);
PropertySource<?> propertySource = propertySourceLocator
.locate(configurableEnvironment);
PropertySource<?> propertySource = this.propertySourceLocator
.locate(this.configurableEnvironment);
assertThat(propertySource).isInstanceOf(CompositePropertySource.class);
CompositePropertySource composite = (CompositePropertySource) propertySource;
assertThat(composite.getPropertySources()).hasSize(1);
verify(secretLeaseContainer)
verify(this.secretLeaseContainer)
.addRequestedSecret(RequestedSecret.rotating("secret/application"));
}
@@ -94,16 +95,17 @@ public class LeasingVaultPropertySourceLocatorUnitTests {
configurer.add(rotating);
configurer.add("database/mysql/creds/readonly");
propertySourceLocator = new LeasingVaultPropertySourceLocator(
new VaultProperties(), configurer, secretLeaseContainer);
this.propertySourceLocator = new LeasingVaultPropertySourceLocator(
new VaultProperties(), configurer, this.secretLeaseContainer);
PropertySource<?> propertySource = propertySourceLocator
.locate(configurableEnvironment);
PropertySource<?> propertySource = this.propertySourceLocator
.locate(this.configurableEnvironment);
assertThat(propertySource).isInstanceOf(CompositePropertySource.class);
verify(secretLeaseContainer).addRequestedSecret(rotating);
verify(secretLeaseContainer).addRequestedSecret(
verify(this.secretLeaseContainer).addRequestedSecret(rotating);
verify(this.secretLeaseContainer).addRequestedSecret(
RequestedSecret.renewable("database/mysql/creds/readonly"));
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.HashMap;
@@ -20,7 +21,7 @@ import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link PropertyNameTransformer}.
@@ -51,4 +52,5 @@ public class PropertyNameTransformerUnitTests {
assertThat(transformer.transformProperties(null)).isNull();
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -32,7 +33,7 @@ import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.ReactiveVaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test using config infrastructure with token authentication.
@@ -68,7 +69,7 @@ public class ReactiveVaultOperationsTests {
@Test
public void shouldAccessVault() {
StepVerifier.create(reactiveOperations.read("secret/testVaultApp"))
StepVerifier.create(this.reactiveOperations.read("secret/testVaultApp"))
.consumeNextWith(actual -> {
assertThat(actual.getData()).containsEntry("vault.value", "foo");
}).verifyComplete();
@@ -80,5 +81,7 @@ public class ReactiveVaultOperationsTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -41,7 +42,7 @@ import org.springframework.vault.authentication.ClientAuthentication;
import org.springframework.vault.core.VaultOperations;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Mark Paluch
@@ -51,8 +52,8 @@ import static org.assertj.core.api.Assertions.*;
VaultConfigAppIdCustomMechanismTests.TestApplication.class }, properties = {
"spring.cloud.vault.authentication=appid",
"VaultConfigAppIdCustomMechanismTests.custom.config=true",
"spring.cloud.vault.applicationName=VaultConfigAppIdCustomMechanismTests",
"spring.main.allow-bean-definition-overriding=true" })
"spring.cloud.vault.applicationName=VaultConfigAppIdCustomMechanismTests",
"spring.main.allow-bean-definition-overriding=true" })
public class VaultConfigAppIdCustomMechanismTests {
@BeforeClass
@@ -106,7 +107,7 @@ public class VaultConfigAppIdCustomMechanismTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo(getClass().getSimpleName());
assertThat(this.configValue).isEqualTo(getClass().getSimpleName());
}
@SpringBootApplication
@@ -115,6 +116,7 @@ public class VaultConfigAppIdCustomMechanismTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
@Configuration
@@ -134,6 +136,7 @@ public class VaultConfigAppIdCustomMechanismTests {
.userIdMechanism(new StaticUserIdMechanism()).build(),
restTemplate);
}
}
public static class StaticUserIdMechanism implements AppIdUserIdMechanism {
@@ -142,5 +145,7 @@ public class VaultConfigAppIdCustomMechanismTests {
public String createUserId() {
return "static-string";
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -33,7 +34,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.authentication.IpAddressUserId;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test using config infrastructure with AppId authentication.
@@ -49,7 +50,9 @@ import static org.assertj.core.api.Assertions.*;
@SpringBootTest(classes = VaultConfigAppIdTests.TestApplication.class, properties = {
"spring.cloud.vault.authentication=appid",
"spring.cloud.vault.app-id.user-id=IP_ADDRESS",
"spring.cloud.vault.application-name=VaultConfigAppIdTests" }) // see https://github.com/spring-cloud/spring-cloud-commons/issues/214
"spring.cloud.vault.application-name=VaultConfigAppIdTests" })
// see
// https://github.com/spring-cloud/spring-cloud-commons/issues/214
public class VaultConfigAppIdTests {
@BeforeClass
@@ -104,7 +107,7 @@ public class VaultConfigAppIdTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo("foo");
assertThat(this.configValue).isEqualTo("foo");
}
@SpringBootApplication
@@ -113,5 +116,7 @@ public class VaultConfigAppIdTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -33,8 +34,8 @@ import org.springframework.cloud.vault.util.Version;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
/**
* Integration test using config infrastructure with AppRole authentication.
@@ -49,7 +50,8 @@ import static org.junit.Assume.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = VaultConfigAppRoleTests.TestApplication.class, properties = {
"spring.cloud.vault.authentication=approle",
"spring.cloud.vault.application-name=VaultConfigAppRoleTests" }) // see
"spring.cloud.vault.application-name=VaultConfigAppRoleTests" })
// see
// https://github.com/spring-cloud/spring-cloud-commons/issues/214
public class VaultConfigAppRoleTests {
@@ -109,7 +111,7 @@ public class VaultConfigAppRoleTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo("foo");
assertThat(this.configValue).isEqualTo("foo");
}
@SpringBootApplication
@@ -118,5 +120,7 @@ public class VaultConfigAppRoleTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -34,8 +35,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import org.springframework.vault.support.VaultResponse;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
/**
* Integration test using config infrastructure with Cubbyhole authentication.
@@ -69,15 +70,14 @@ public class VaultConfigCubbyholeAuthenticationTests {
Collections.singletonMap("vault.value",
VaultConfigCubbyholeAuthenticationTests.class.getSimpleName()));
VaultResponse vaultResponse = vaultOperations
.doWithSession(restOperations -> {
VaultResponse vaultResponse = vaultOperations.doWithSession(restOperations -> {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Vault-Wrap-TTL", "1h");
return restOperations.postForObject("/auth/token/create", new HttpEntity<>(
headers), VaultResponse.class);
});
return restOperations.postForObject("/auth/token/create",
new HttpEntity<>(headers), VaultResponse.class);
});
String initialToken = vaultResponse.getWrapInfo().get("token");
System.setProperty("spring.cloud.vault.token", initialToken);
@@ -93,7 +93,7 @@ public class VaultConfigCubbyholeAuthenticationTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo(getClass().getSimpleName());
assertThat(this.configValue).isEqualTo(getClass().getSimpleName());
}
@SpringBootApplication
@@ -102,5 +102,7 @@ public class VaultConfigCubbyholeAuthenticationTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -31,7 +32,7 @@ import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultTemplate;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test using config infrastructure with token authentication.
@@ -65,14 +66,14 @@ public class VaultConfigDisabledTests {
@Test
public void shouldNotContainVaultProperties() {
assertThat(environment.containsProperty("vault.value")).isFalse();
assertThat(this.environment.containsProperty("vault.value")).isFalse();
}
@Test
public void shouldNotContainVaultBeans() {
// Beans are registered in parent (bootstrap) context.
ApplicationContext parent = applicationContext.getParent();
ApplicationContext parent = this.applicationContext.getParent();
assertThat(parent.getBeanNamesForType(VaultTemplate.class)).isEmpty();
assertThat(parent.getBeanNamesForType(VaultPropertySourceLocator.class))
@@ -85,5 +86,7 @@ public class VaultConfigDisabledTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -29,7 +30,7 @@ import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test using config infrastructure with token authentication.
@@ -60,7 +61,7 @@ public class VaultConfigGenericBackendDisabledTests {
@Test
public void shouldNotContainVaultProperties() {
assertThat(environment.containsProperty("vault.value")).isFalse();
assertThat(this.environment.containsProperty("vault.value")).isFalse();
}
@SpringBootApplication
@@ -69,5 +70,7 @@ public class VaultConfigGenericBackendDisabledTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.io.File;
@@ -66,9 +67,8 @@ public class VaultConfigKubernetesTests {
vaultRule.before();
String minikubeIp = System.getProperty("MINIKUBE_IP");
assumeTrue(StringUtils.hasText(minikubeIp)
&& vaultRule.prepare().getVersion()
.isGreaterThanOrEqualTo(Version.parse("0.8.3")));
assumeTrue(StringUtils.hasText(minikubeIp) && vaultRule.prepare().getVersion()
.isGreaterThanOrEqualTo(Version.parse("0.8.3")));
if (!vaultRule.prepare().hasAuth("kubernetes")) {
vaultRule.prepare().mountAuth("kubernetes");
@@ -76,8 +76,8 @@ public class VaultConfigKubernetesTests {
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
Policy policy = Policy.of(Rule.builder().path("*")
.capabilities(BuiltinCapabilities.READ).build());
Policy policy = Policy.of(
Rule.builder().path("*").capabilities(BuiltinCapabilities.READ).build());
vaultOperations.opsForSys().createOrUpdatePolicy("testpolicy", policy);
@@ -105,7 +105,7 @@ public class VaultConfigKubernetesTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo("foo");
assertThat(this.configValue).isEqualTo("foo");
}
@SpringBootApplication
@@ -114,5 +114,7 @@ public class VaultConfigKubernetesTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -36,7 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultTemplate;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test using config infrastructure with token authentication.
@@ -52,7 +53,8 @@ import static org.assertj.core.api.Assertions.*;
@SpringBootTest(classes = VaultConfigTests.TestApplication.class, properties = {
"spring.cloud.vault.host=foo", "spring.cloud.vault.port=80",
"spring.cloud.vault.uri=https://localhost:8200",
"spring.cloud.vault.application-name=testVaultApp" }) // see
"spring.cloud.vault.application-name=testVaultApp" })
// see
// https://github.com/spring-cloud/spring-cloud-commons/issues/214
public class VaultConfigTests {
@@ -80,24 +82,24 @@ public class VaultConfigTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo("foo");
assertThat(this.configValue).isEqualTo("foo");
}
@Test
public void shouldContainProperty() {
assertThat(environment.containsProperty("vault.value")).isTrue();
assertThat(environment.getProperty("vault.value")).isEqualTo("foo");
assertThat(this.environment.containsProperty("vault.value")).isTrue();
assertThat(this.environment.getProperty("vault.value")).isEqualTo("foo");
assertThat(environment.containsProperty("nested.key")).isTrue();
assertThat(environment.getProperty("nested.key")).isEqualTo("value");
assertThat(this.environment.containsProperty("nested.key")).isTrue();
assertThat(this.environment.getProperty("nested.key")).isEqualTo("value");
}
@Test
public void shouldContainVaultBeans() {
// Beans are registered in parent (bootstrap) context.
ApplicationContext parent = applicationContext.getParent();
ApplicationContext parent = this.applicationContext.getParent();
assertThat(parent.getBeanNamesForType(VaultTemplate.class)).isNotEmpty();
assertThat(parent.getBeanNamesForType(LeasingVaultPropertySourceLocator.class))
@@ -108,7 +110,7 @@ public class VaultConfigTests {
public void shouldNotContainRestTemplateArtifacts() {
// Beans are registered in parent (bootstrap) context.
ApplicationContext parent = applicationContext.getParent();
ApplicationContext parent = this.applicationContext.getParent();
assertThat(parent.getBeanNamesForType(RestTemplate.class)).isEmpty();
assertThat(parent.getBeanNamesForType(ClientHttpRequestFactory.class)).isEmpty();
@@ -120,5 +122,7 @@ public class VaultConfigTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.io.File;
@@ -35,8 +36,8 @@ import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.cloud.vault.util.Settings.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.cloud.vault.util.Settings.findWorkDir;
/**
* Integration test using config infrastructure with TLS certificate authentication. In
@@ -99,7 +100,7 @@ public class VaultConfigTlsCertAuthenticationTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo("foo");
assertThat(this.configValue).isEqualTo("foo");
}
@SpringBootApplication
@@ -108,5 +109,7 @@ public class VaultConfigTlsCertAuthenticationTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -30,7 +31,7 @@ import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test using config infrastructure with token authentication.
@@ -43,7 +44,8 @@ import static org.assertj.core.api.Assertions.*;
* @author Mark Paluch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = VaultConfigWithContextTests.TestApplication.class, properties = "spring.cloud.vault.application-name=testVaultApp") // see
@SpringBootTest(classes = VaultConfigWithContextTests.TestApplication.class, properties = "spring.cloud.vault.application-name=testVaultApp")
// see
// https://github.com/spring-cloud/spring-cloud-commons/issues/214
@ActiveProfiles("my-profile")
public class VaultConfigWithContextTests {
@@ -68,7 +70,7 @@ public class VaultConfigWithContextTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo("hello");
assertThat(this.configValue).isEqualTo("hello");
}
@SpringBootApplication
@@ -77,5 +79,7 @@ public class VaultConfigWithContextTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -31,7 +32,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test using config infrastructure with token authentication.
@@ -67,7 +68,7 @@ public class VaultConfigWithVaultConfigurerTests {
@Test
public void contextLoads() {
assertThat(configValue).isEqualTo("hello");
assertThat(this.configValue).isEqualTo("hello");
}
@SpringBootApplication
@@ -76,6 +77,7 @@ public class VaultConfigWithVaultConfigurerTests {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
public static class ConfigurerBootstrapApplication {
@@ -86,5 +88,7 @@ public class VaultConfigWithVaultConfigurerTests {
return configurer -> configurer
.add("secret/VaultConfigWithVaultConfigurerTests");
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.junit.Before;
@@ -27,8 +28,9 @@ import org.springframework.vault.core.VaultOperations;
import org.springframework.vault.core.VaultSysOperations;
import org.springframework.vault.support.VaultHealth;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link VaultHealthIndicator}.
@@ -52,19 +54,19 @@ public class VaultHealthIndicatorUnitTests {
@Before
public void before() {
healthIndicator = new VaultHealthIndicator(vaultOperations);
this.healthIndicator = new VaultHealthIndicator(this.vaultOperations);
when(vaultOperations.opsForSys()).thenReturn(vaultSysOperations);
when(vaultSysOperations.health()).thenReturn(healthResponse);
when(this.vaultOperations.opsForSys()).thenReturn(this.vaultSysOperations);
when(this.vaultSysOperations.health()).thenReturn(this.healthResponse);
}
@Test
public void shouldReportHealthyService() {
when(healthResponse.isInitialized()).thenReturn(true);
when(vaultOperations.opsForSys()).thenReturn(vaultSysOperations);
when(this.healthResponse.isInitialized()).thenReturn(true);
when(this.vaultOperations.opsForSys()).thenReturn(this.vaultSysOperations);
Health health = healthIndicator.health();
Health health = this.healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails()).isEmpty();
}
@@ -72,10 +74,10 @@ public class VaultHealthIndicatorUnitTests {
@Test
public void shouldReportSealedService() {
when(healthResponse.isInitialized()).thenReturn(true);
when(healthResponse.isSealed()).thenReturn(true);
when(this.healthResponse.isInitialized()).thenReturn(true);
when(this.healthResponse.isSealed()).thenReturn(true);
Health health = healthIndicator.health();
Health health = this.healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails()).containsEntry("state", "Vault sealed");
@@ -84,7 +86,7 @@ public class VaultHealthIndicatorUnitTests {
@Test
public void shouldReportUninitializedService() {
Health health = healthIndicator.health();
Health health = this.healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails()).containsEntry("state", "Vault uninitialized");
@@ -93,10 +95,10 @@ public class VaultHealthIndicatorUnitTests {
@Test
public void shouldReportStandbyService() {
when(healthResponse.isInitialized()).thenReturn(true);
when(healthResponse.isStandby()).thenReturn(true);
when(this.healthResponse.isInitialized()).thenReturn(true);
when(this.healthResponse.isStandby()).thenReturn(true);
Health health = healthIndicator.health();
Health health = this.healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails()).containsEntry("state", "Vault in standby");
@@ -105,11 +107,12 @@ public class VaultHealthIndicatorUnitTests {
@Test
public void exceptionsShouldReportDownStatus() {
reset(vaultSysOperations);
when(vaultSysOperations.health()).thenThrow(new IllegalStateException());
reset(this.vaultSysOperations);
when(this.vaultSysOperations.health()).thenThrow(new IllegalStateException());
Health health = healthIndicator.health();
Health health = this.healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails()).containsKey("error");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -23,7 +24,7 @@ import org.junit.Test;
import org.springframework.cloud.vault.util.IntegrationTestSupport;
import org.springframework.cloud.vault.util.Settings;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link VaultPropertySource}.
@@ -52,4 +53,5 @@ public class VaultPropertySourceIntegrationTests extends IntegrationTestSupport
assertThat(propertySource.getPropertyNames()).contains("key");
assertThat(propertySource.getProperty("key")).isEqualTo("value");
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import java.util.Collections;
@@ -29,7 +30,7 @@ import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test incorporating loading secrets using
@@ -48,6 +49,7 @@ public class VaultPropertySourceLocatorIntegrationTests extends IntegrationTestS
@SpringBootApplication
public static class TestApplication {
}
@BeforeClass
@@ -63,9 +65,9 @@ public class VaultPropertySourceLocatorIntegrationTests extends IntegrationTestS
"vault.value", "spring.application.name:integrationtest value"));
vaultRule.prepare().getVaultOperations().write("secret/neuromancer", Collections
.singletonMap("vault.value", "spring.cloud.vault.applicationName value"));
vaultRule.prepare().getVaultOperations().write(
"secret/neuromancer/integrationtest",
Collections.singletonMap("vault.value",
vaultRule.prepare().getVaultOperations()
.write("secret/neuromancer/integrationtest", Collections.singletonMap(
"vault.value",
"spring.cloud.vault.applicationName:integrationtest value"));
vaultRule.prepare().getVaultOperations().write("secret/icebreaker",
Collections.singletonMap("icebreaker.value", "additional context value"));
@@ -82,12 +84,14 @@ public class VaultPropertySourceLocatorIntegrationTests extends IntegrationTestS
@Test
public void getsSecretFromVaultUsingVaultApplicationName() {
assertThat(configValue)
assertThat(this.configValue)
.isEqualTo("spring.cloud.vault.applicationName:integrationtest value");
}
@Test
public void getsSecretFromVaultUsingAdditionalContext() {
assertThat(additionalValue).isEqualTo("additional context:integrationtest value");
assertThat(this.additionalValue)
.isEqualTo("additional context:integrationtest value");
}
}

Some files were not shown because too many files have changed in this diff Show More