diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java index f9896502..387b32d0 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java @@ -58,7 +58,8 @@ public class ConfigClientWatch implements Closeable, EnvironmentAware { this.running.compareAndSet(false, true); } - @Scheduled(initialDelayString = "${spring.cloud.config.watch.initialDelay:180000}", fixedDelayString = "${spring.cloud.config.watch.delay:500}") + @Scheduled(initialDelayString = "${spring.cloud.config.watch.initialDelay:180000}", + fixedDelayString = "${spring.cloud.config.watch.delay:500}") public void watchConfigServer() { if (this.running.get()) { String newState = this.environment.getProperty("config.client.state"); diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfiguration.java index 0787776a..60bda5a4 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfiguration.java @@ -43,7 +43,8 @@ import org.springframework.context.event.SmartApplicationListener; * * @author Dave Syer */ -@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false) +@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", + matchIfMissing = false) @Configuration @Import({ UtilAutoConfiguration.class }) @EnableDiscoveryClient diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractor.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractor.java index e1093c40..8bc8c661 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractor.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractor.java @@ -59,7 +59,7 @@ public class BitbucketPropertyPathNotificationExtractor } } else if ("pr:merged".equals(headers.getFirst("X-Event-Key")) - && StringUtils.hasText(headers.getFirst("X-Request-Id"))) { + && StringUtils.hasText(headers.getFirst("X-Request-Id"))) { // Bitbucket server // Bitbucket doesn't tell us the files that changed so this is a // broadcast to all apps diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfiguration.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfiguration.java index a9629200..7b7defec 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfiguration.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfiguration.java @@ -50,37 +50,46 @@ public class EnvironmentMonitorAutoConfiguration { protected static class PropertyPathNotificationExtractorConfiguration { @Bean - @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.github.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty( + value = "spring.cloud.config.server.monitor.github.enabled", + havingValue = "true", matchIfMissing = true) public GithubPropertyPathNotificationExtractor githubPropertyPathNotificationExtractor() { return new GithubPropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitlab.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty( + value = "spring.cloud.config.server.monitor.gitlab.enabled", + havingValue = "true", matchIfMissing = true) public GitlabPropertyPathNotificationExtractor gitlabPropertyPathNotificationExtractor() { return new GitlabPropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.bitbucket.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty( + value = "spring.cloud.config.server.monitor.bitbucket.enabled", + havingValue = "true", matchIfMissing = true) public BitbucketPropertyPathNotificationExtractor bitbucketPropertyPathNotificationExtractor() { return new BitbucketPropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitea.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitea.enabled", + havingValue = "true", matchIfMissing = true) public GiteaPropertyPathNotificationExtractor giteaPropertyPathNotificationExtractor() { return new GiteaPropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitee.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitee.enabled", + havingValue = "true", matchIfMissing = true) public GiteePropertyPathNotificationExtractor giteePropertyPathNotificationExtractor() { return new GiteePropertyPathNotificationExtractor(); } @Bean - @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gogs.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gogs.enabled", + havingValue = "true", matchIfMissing = true) public GogsPropertyPathNotificationExtractor gogsPropertyPathNotificationExtractor() { return new GogsPropertyPathNotificationExtractor(); } diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java index 2589093c..c7e6151b 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java @@ -97,7 +97,8 @@ public class PropertyPathEndpoint implements ApplicationEventPublisherAware { return Collections.emptySet(); } - @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping(method = RequestMethod.POST, + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public Set notifyByForm(@RequestHeader HttpHeaders headers, @RequestParam("path") List request) { Map map = new HashMap<>(); diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractorTests.java index 8df0ce52..c548eb42 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/BitbucketPropertyPathNotificationExtractorTests.java @@ -125,7 +125,8 @@ public class BitbucketPropertyPathNotificationExtractorTests { @Test public void bitbucketServerSamplePullRequest() throws Exception { // https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html - Map value = readPayload("pathsamples/bitbucketserver-prmerged.json"); + Map value = readPayload( + "pathsamples/bitbucketserver-prmerged.json"); setServerHeaders("pr:merged"); PropertyPathNotification extracted = this.extractor.extract(this.headers, value); assertThat(extracted).isNotNull(); diff --git a/spring-cloud-config-sample/src/test/java/sample/ApplicationBootstrapTests.java b/spring-cloud-config-sample/src/test/java/sample/ApplicationBootstrapTests.java index 78cec65c..34d2bbb2 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ApplicationBootstrapTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ApplicationBootstrapTests.java @@ -53,7 +53,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen // server on the classpath we need to set it explicitly properties = { "spring.cloud.config.enabled:true", "", "management.security.enabled=false", - "management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT) + "management.endpoints.web.exposure.include=*" }, + webEnvironment = RANDOM_PORT) public class ApplicationBootstrapTests { private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); diff --git a/spring-cloud-config-sample/src/test/java/sample/ApplicationTests.java b/spring-cloud-config-sample/src/test/java/sample/ApplicationTests.java index 29724550..0052e6eb 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ApplicationTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ApplicationTests.java @@ -44,7 +44,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen // server on the classpath we need to set it explicitly properties = { "spring.cloud.config.enabled:true", "management.security.enabled=false", - "management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT) + "management.endpoints.web.exposure.include=*" }, + webEnvironment = RANDOM_PORT) public class ApplicationTests { private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); diff --git a/spring-cloud-config-sample/src/test/java/sample/ServerNativeApplicationTests.java b/spring-cloud-config-sample/src/test/java/sample/ServerNativeApplicationTests.java index 0e16dbd7..2f36808f 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ServerNativeApplicationTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ServerNativeApplicationTests.java @@ -36,7 +36,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, properties = "spring.application.name:bad", webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = Application.class, properties = "spring.application.name:bad", + webEnvironment = RANDOM_PORT) public class ServerNativeApplicationTests { private static int configPort = 0; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EncryptionAutoConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EncryptionAutoConfiguration.java index 730ff71f..fc63c144 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EncryptionAutoConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EncryptionAutoConfiguration.java @@ -59,7 +59,8 @@ import org.springframework.util.StringUtils; public class EncryptionAutoConfiguration { @Configuration - @ConditionalOnProperty(value = "spring.cloud.config.server.encrypt.enabled", matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.config.server.encrypt.enabled", + matchIfMissing = true) protected static class EncryptorConfiguration { @Autowired(required = false) @@ -82,7 +83,8 @@ public class EncryptionAutoConfiguration { @Configuration @ConditionalOnClass(RsaSecretEncryptor.class) - @ConditionalOnProperty(prefix = "encrypt.key-store", value = "location", matchIfMissing = false) + @ConditionalOnProperty(prefix = "encrypt.key-store", value = "location", + matchIfMissing = false) protected static class KeyStoreConfiguration { @Autowired diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.java index 6b8a9fee..2ff0933e 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.java @@ -36,6 +36,7 @@ import org.springframework.cloud.config.server.composite.CompositeEnvironmentBea import org.springframework.cloud.config.server.composite.ConditionalOnMissingSearchPathLocator; import org.springframework.cloud.config.server.composite.ConditionalOnSearchPathLocator; import org.springframework.cloud.config.server.environment.CompositeEnvironmentRepository; +import org.springframework.cloud.config.server.environment.ConfigTokenProvider; import org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactory; import org.springframework.cloud.config.server.environment.ConsulEnvironmentWatch; import org.springframework.cloud.config.server.environment.CredhubEnvironmentProperties; @@ -45,6 +46,7 @@ import org.springframework.cloud.config.server.environment.EnvironmentRepository import org.springframework.cloud.config.server.environment.EnvironmentWatch; import org.springframework.cloud.config.server.environment.HttpClientConfigurableHttpConnectionFactory; import org.springframework.cloud.config.server.environment.HttpClientVaultRestTemplateFactory; +import org.springframework.cloud.config.server.environment.HttpRequestConfigTokenProvider; import org.springframework.cloud.config.server.environment.JdbcEnvironmentProperties; import org.springframework.cloud.config.server.environment.JdbcEnvironmentRepository; import org.springframework.cloud.config.server.environment.JdbcEnvironmentRepositoryFactory; @@ -83,6 +85,7 @@ import org.springframework.jdbc.core.JdbcTemplate; * @author Daniel Lavoie * @author Dylan Roberts * @author Alberto C. Ríos + * @author Scott Frederick */ @Configuration @EnableConfigurationProperties({ SvnKitEnvironmentProperties.class, @@ -90,15 +93,16 @@ import org.springframework.jdbc.core.JdbcTemplate; NativeEnvironmentProperties.class, VaultEnvironmentProperties.class, RedisEnvironmentProperties.class }) @Import({ CompositeRepositoryConfiguration.class, JdbcRepositoryConfiguration.class, - VaultRepositoryConfiguration.class, CredhubConfiguration.class, - CredhubRepositoryConfiguration.class, SvnRepositoryConfiguration.class, - NativeRepositoryConfiguration.class, GitRepositoryConfiguration.class, - RedisRepositoryConfiguration.class, GoogleCloudSourceConfiguration.class, - DefaultRepositoryConfiguration.class }) + VaultConfiguration.class, VaultRepositoryConfiguration.class, + CredhubConfiguration.class, CredhubRepositoryConfiguration.class, + SvnRepositoryConfiguration.class, NativeRepositoryConfiguration.class, + GitRepositoryConfiguration.class, RedisRepositoryConfiguration.class, + GoogleCloudSourceConfiguration.class, DefaultRepositoryConfiguration.class }) public class EnvironmentRepositoryConfiguration { @Bean - @ConditionalOnProperty(value = "spring.cloud.config.server.health.enabled", matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.config.server.health.enabled", + matchIfMissing = true) public ConfigServerHealthIndicator configServerHealthIndicator( EnvironmentRepository repository) { return new ConfigServerHealthIndicator(repository); @@ -132,6 +136,18 @@ public class EnvironmentRepositoryConfiguration { } + @Configuration + @ConditionalOnMissingBean(ConfigTokenProvider.class) + protected static class DefaultConfigTokenProvider { + + @Bean + public ConfigTokenProvider configTokenProvider( + ObjectProvider httpRequest) { + return new HttpRequestConfigTokenProvider(httpRequest); + } + + } + @Configuration @ConditionalOnClass(TransportConfigCallback.class) static class JGitFactoryConfig { @@ -180,9 +196,10 @@ public class EnvironmentRepositoryConfiguration { @Bean public VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory( ObjectProvider request, EnvironmentWatch watch, - Optional vaultRestTemplateFactory) { + Optional vaultRestTemplateFactory, + ConfigTokenProvider tokenProvider) { return new VaultEnvironmentRepositoryFactory(request, watch, - vaultRestTemplateFactory); + vaultRestTemplateFactory, tokenProvider); } } @@ -251,7 +268,8 @@ public class EnvironmentRepositoryConfiguration { } @Configuration -@ConditionalOnMissingBean(value = EnvironmentRepository.class, search = SearchStrategy.CURRENT) +@ConditionalOnMissingBean(value = EnvironmentRepository.class, + search = SearchStrategy.CURRENT) class DefaultRepositoryConfiguration { @Bean @@ -366,7 +384,7 @@ class CompositeRepositoryConfiguration { @Bean @ConditionalOnSearchPathLocator public SearchPathCompositeEnvironmentRepository searchPathCompositeEnvironmentRepository( - List environmentRepositories) throws Exception { + List environmentRepositories) { return new SearchPathCompositeEnvironmentRepository(environmentRepositories); } @@ -374,7 +392,7 @@ class CompositeRepositoryConfiguration { @Bean @ConditionalOnMissingSearchPathLocator public CompositeEnvironmentRepository compositeEnvironmentRepository( - List environmentRepositories) throws Exception { + List environmentRepositories) { return new CompositeEnvironmentRepository(environmentRepositories); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/VaultConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/VaultConfiguration.java new file mode 100644 index 00000000..e2b28381 --- /dev/null +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/VaultConfiguration.java @@ -0,0 +1,40 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.config.server.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.config.server.environment.ConfigTokenProvider; +import org.springframework.cloud.config.server.environment.EnvironmentConfigTokenProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** + * @author Scott Frederick + */ +@Configuration +public class VaultConfiguration { + + private static final String VAULT_TOKEN_PROPERTY_NAME = "spring.cloud.config.server.vault.token"; + + @Bean + @ConditionalOnProperty(VAULT_TOKEN_PROPERTY_NAME) + public ConfigTokenProvider configTokenProvider(Environment environment) { + return new EnvironmentConfigTokenProvider(environment, VAULT_TOKEN_PROPERTY_NAME); + } + +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConfigTokenProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConfigTokenProvider.java new file mode 100644 index 00000000..1fd281de --- /dev/null +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ConfigTokenProvider.java @@ -0,0 +1,26 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.config.server.environment; + +/** + * @author Scott Frederick + */ +public interface ConfigTokenProvider { + + String getToken(); + +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentConfigTokenProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentConfigTokenProvider.java new file mode 100644 index 00000000..a372600b --- /dev/null +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentConfigTokenProvider.java @@ -0,0 +1,40 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.config.server.environment; + +import org.springframework.core.env.Environment; + +/** + * @author Scott Frederick + */ +public class EnvironmentConfigTokenProvider implements ConfigTokenProvider { + + private final Environment environment; + + private final String propertyName; + + public EnvironmentConfigTokenProvider(Environment environment, String propertyName) { + this.environment = environment; + this.propertyName = propertyName; + } + + @Override + public String getToken() { + return environment.getProperty(propertyName); + } + +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java index c415133c..0d263060 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java @@ -62,7 +62,8 @@ import static org.springframework.cloud.config.server.support.EnvironmentPropert * */ @RestController -@RequestMapping(method = RequestMethod.GET, path = "${spring.cloud.config.server.prefix:}") +@RequestMapping(method = RequestMethod.GET, + path = "${spring.cloud.config.server.prefix:}") public class EnvironmentController { private EnvironmentRepository repository; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpRequestConfigTokenProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpRequestConfigTokenProvider.java new file mode 100644 index 00000000..76b424b3 --- /dev/null +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpRequestConfigTokenProvider.java @@ -0,0 +1,54 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.config.server.environment; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.cloud.config.client.ConfigClientProperties; +import org.springframework.util.StringUtils; + +/** + * @author Scott Frederick + */ +public class HttpRequestConfigTokenProvider implements ConfigTokenProvider { + + private ObjectProvider httpRequest; + + public HttpRequestConfigTokenProvider( + ObjectProvider httpRequest) { + this.httpRequest = httpRequest; + } + + @Override + public String getToken() { + HttpServletRequest request = httpRequest.getIfAvailable(); + if (request == null) { + throw new IllegalStateException("No HttpServletRequest available"); + } + + String token = request.getHeader(ConfigClientProperties.TOKEN_HEADER); + if (!StringUtils.hasLength(token)) { + throw new IllegalArgumentException( + "Missing required header in HttpServletRequest: " + + ConfigClientProperties.TOKEN_HEADER); + } + + return token; + } + +} diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepository.java index 7164bbd2..08f0bc7b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepository.java @@ -39,13 +39,13 @@ import org.springframework.validation.annotation.Validated; import org.springframework.web.client.RestTemplate; import static org.springframework.cloud.config.client.ConfigClientProperties.STATE_HEADER; -import static org.springframework.cloud.config.client.ConfigClientProperties.TOKEN_HEADER; /** * @author Spencer Gibb * @author Mark Paluch * @author Haroun Pacquee * @author Haytham Mohamed + * @author Scott Frederick */ @Validated public class VaultEnvironmentRepository implements EnvironmentRepository, Ordered { @@ -53,12 +53,12 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere /** * Vault token header name. */ - public static final String VAULT_TOKEN = "X-Vault-Token"; + private static final String VAULT_TOKEN = "X-Vault-Token"; /** * Vault namespace header name. */ - public static final String VAULT_NAMESPACE = "X-Vault-Namespace"; + static final String VAULT_NAMESPACE = "X-Vault-Namespace"; /** Vault host. Defaults to 127.0.0.1. */ @NotEmpty @@ -94,15 +94,25 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere private VaultKvAccessStrategy accessStrategy; // TODO: move to watchState:String on findOne? - private ObjectProvider request; + private final ObjectProvider request; - private EnvironmentWatch watch; + private final EnvironmentWatch watch; + + private final ConfigTokenProvider tokenProvider; public VaultEnvironmentRepository(ObjectProvider request, EnvironmentWatch watch, RestTemplate rest, VaultEnvironmentProperties properties) { + this(request, watch, rest, properties, + new HttpRequestConfigTokenProvider(request)); + } + + public VaultEnvironmentRepository(ObjectProvider request, + EnvironmentWatch watch, RestTemplate rest, + VaultEnvironmentProperties properties, ConfigTokenProvider tokenProvider) { this.request = request; this.watch = watch; + this.tokenProvider = tokenProvider; this.backend = properties.getBackend(); this.defaultKey = properties.getDefaultKey(); this.host = properties.getHost(); @@ -124,26 +134,17 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere @Override public Environment findOne(String application, String profile, String label) { - - HttpServletRequest servletRequest = this.request.getIfAvailable(); - if (servletRequest == null) { - throw new IllegalStateException("No HttpServletRequest available"); - } - - String state = servletRequest.getHeader(STATE_HEADER); - String newState = this.watch.watch(state); - String[] profiles = StringUtils.commaDelimitedListToStringArray(profile); List scrubbedProfiles = scrubProfiles(profiles); List keys = findKeys(application, scrubbedProfiles); Environment environment = new Environment(application, profiles, label, null, - newState); + getWatchState()); for (String key : keys) { // read raw 'data' key from vault - String data = read(servletRequest, key); + String data = read(key); if (data != null) { // data is in json format of which, yaml is a superset, so parse final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); @@ -159,6 +160,15 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere return environment; } + private String getWatchState() { + HttpServletRequest servletRequest = this.request.getIfAvailable(); + if (servletRequest != null) { + String state = servletRequest.getHeader(STATE_HEADER); + return this.watch.watch(state); + } + return null; + } + private List findKeys(String application, List profiles) { List keys = new ArrayList<>(); @@ -194,16 +204,9 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere } } - String read(HttpServletRequest servletRequest, String key) { - + private String read(String key) { HttpHeaders headers = new HttpHeaders(); - - String token = servletRequest.getHeader(TOKEN_HEADER); - if (!StringUtils.hasLength(token)) { - throw new IllegalArgumentException( - "Missing required header: " + TOKEN_HEADER); - } - headers.add(VAULT_TOKEN, token); + headers.add(VAULT_TOKEN, getToken()); if (StringUtils.hasText(this.namespace)) { headers.add(VAULT_NAMESPACE, this.namespace); } @@ -211,6 +214,15 @@ public class VaultEnvironmentRepository implements EnvironmentRepository, Ordere return this.accessStrategy.getData(headers, this.backend, key); } + private String getToken() { + String token = tokenProvider.getToken(); + if (!StringUtils.hasLength(token)) { + throw new IllegalArgumentException( + "A Vault token must be supplied by a token provider"); + } + return token; + } + public void setHost(String host) { this.host = host; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryFactory.java index 5c6df454..235788a3 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryFactory.java @@ -25,15 +25,18 @@ import org.springframework.web.client.RestTemplate; /** * @author Dylan Roberts + * @author Scott Frederick */ public class VaultEnvironmentRepositoryFactory implements EnvironmentRepositoryFactory { - private ObjectProvider request; + private final ObjectProvider request; - private EnvironmentWatch watch; + private final EnvironmentWatch watch; - private Optional vaultRestTemplateFactory; + private final Optional vaultRestTemplateFactory; + + private final ConfigTokenProvider tokenProvider; public VaultEnvironmentRepositoryFactory(ObjectProvider request, EnvironmentWatch watch, @@ -41,6 +44,17 @@ public class VaultEnvironmentRepositoryFactory implements this.request = request; this.watch = watch; this.vaultRestTemplateFactory = vaultRestTemplateFactory; + this.tokenProvider = new HttpRequestConfigTokenProvider(request); + } + + public VaultEnvironmentRepositoryFactory(ObjectProvider request, + EnvironmentWatch watch, + Optional vaultRestTemplateFactory, + ConfigTokenProvider tokenProvider) { + this.request = request; + this.watch = watch; + this.vaultRestTemplateFactory = vaultRestTemplateFactory; + this.tokenProvider = tokenProvider; } @Override @@ -50,10 +64,10 @@ public class VaultEnvironmentRepositoryFactory implements RestTemplate restTemplate = this.vaultRestTemplateFactory.get() .build(environmentProperties); return new VaultEnvironmentRepository(this.request, this.watch, restTemplate, - environmentProperties); + environmentProperties, tokenProvider); } return new VaultEnvironmentRepository(this.request, this.watch, - new RestTemplate(), environmentProperties); + new RestTemplate(), environmentProperties, tokenProvider); } /** diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceController.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceController.java index 1a28d860..cd0189f9 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceController.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/resource/ResourceController.java @@ -52,7 +52,8 @@ import static org.springframework.cloud.config.server.support.EnvironmentPropert * */ @RestController -@RequestMapping(method = RequestMethod.GET, path = "${spring.cloud.config.server.prefix:}") +@RequestMapping(method = RequestMethod.GET, + path = "${spring.cloud.config.server.prefix:}") public class ResourceController { private ResourceRepository resourceRepository; @@ -129,14 +130,16 @@ public class ResourceController { return retrieve(null, name, profile, label, path, resolvePlaceholders); } - @RequestMapping(value = "/{name}/{profile}/{label}/**", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) + @RequestMapping(value = "/{name}/{profile}/{label}/**", + produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public byte[] binary(@PathVariable String name, @PathVariable String profile, @PathVariable String label, ServletWebRequest request) throws IOException { String path = getFilePath(request, name, profile, label); return binary(request, name, profile, label, path); } - @RequestMapping(value = "/{name}/{profile}/**", params = "useDefaultLabel", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) + @RequestMapping(value = "/{name}/{profile}/**", params = "useDefaultLabel", + produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public byte[] binary(@PathVariable String name, @PathVariable String profile, ServletWebRequest request) throws IOException { String path = getFilePath(request, name, profile, null); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/BootstrapConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/BootstrapConfigServerIntegrationTests.java index dc396952..7c31ace6 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/BootstrapConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/BootstrapConfigServerIntegrationTests.java @@ -36,9 +36,10 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, properties = { - "spring.cloud.bootstrap.name:enable-bootstrap", "encrypt.rsa.algorithm=DEFAULT", - "encrypt.rsa.strong=false" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = ConfigServerApplication.class, + properties = { "spring.cloud.bootstrap.name:enable-bootstrap", + "encrypt.rsa.algorithm=DEFAULT", "encrypt.rsa.strong=false" }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({ "test", "encrypt" }) public class BootstrapConfigServerIntegrationTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java index 9ead658b..59fc1a24 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java @@ -106,7 +106,8 @@ public class CompositeIntegrationTests { "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", "spring.cloud.config.server.composite[0].type:git", "spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo", - "spring.cloud.config.server.composite[1].type:svn" }, webEnvironment = RANDOM_PORT) + "spring.cloud.config.server.composite[1].type:svn" }, + webEnvironment = RANDOM_PORT) @ActiveProfiles({ "test", "composite" }) public static class ListTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java index 32de5240..e7ecde3f 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java @@ -52,7 +52,9 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.anyString; @RunWith(SpringRunner.class) -@SpringBootTest(classes = TestConfiguration.class, properties = "spring.cloud.config.enabled:true", webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = TestConfiguration.class, + properties = "spring.cloud.config.enabled:true", + webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @DirtiesContext public class ConfigClientOnIntegrationTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java index 4201b43d..56912bb8 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java @@ -32,10 +32,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Alberto C. Ríos */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, properties = { - "spring.profiles.active:composite", - "spring.cloud.config.server.composite[0].type:credhub", - "spring.cloud.config.server.composite[0].url:https://credhub:8844" }, webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ConfigServerApplication.class, + properties = { "spring.profiles.active:composite", + "spring.cloud.config.server.composite[0].type:credhub", + "spring.cloud.config.server.composite[0].url:https://credhub:8844" }, + webEnvironment = RANDOM_PORT) public class CredhubCompositeConfigServerIntegrationTests extends CredhubIntegrationTest { @LocalServerPort diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java index c77f501d..764e2d1a 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java @@ -32,9 +32,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Alberto C. Ríos */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, properties = { - "spring.profiles.active:credhub", - "spring.cloud.config.server.credhub.url:https://credhub:8844" }, webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ConfigServerApplication.class, + properties = { "spring.profiles.active:credhub", + "spring.cloud.config.server.credhub.url:https://credhub:8844" }, + webEnvironment = RANDOM_PORT) public class CredhubConfigServerIntegrationTests extends CredhubIntegrationTest { @LocalServerPort diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java index 4f3b3fba..66402afb 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java @@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, properties = { - "spring.config.name:configserver" }, webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ConfigServerApplication.class, + properties = { "spring.config.name:configserver" }, webEnvironment = RANDOM_PORT) @ActiveProfiles({ "test", "native" }) public class NativeConfigServerIntegrationTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java index 07fc4181..28baea85 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java @@ -53,9 +53,10 @@ public class TransportConfigurationIntegrationTests { public static class PropertyBasedCallbackTest { @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class, - SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "spring.config.name:ssh/ssh-private-key-block" }) + @SpringBootTest( + classes = { ConfigServerApplication.class, SshPropertyValidator.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "spring.config.name:ssh/ssh-private-key-block" }) @ActiveProfiles({ "test", "git" }) public static class StaticTest { @@ -73,9 +74,10 @@ public class TransportConfigurationIntegrationTests { } @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class, - SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "spring.config.name:ssh/ssh-private-key-block-list" }) + @SpringBootTest( + classes = { ConfigServerApplication.class, SshPropertyValidator.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "spring.config.name:ssh/ssh-private-key-block-list" }) @ActiveProfiles({ "test", "composite" }) public static class ListTest { @@ -97,9 +99,10 @@ public class TransportConfigurationIntegrationTests { public static class PrivateKeyPropertyWithLineBreaks { @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class, - SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "spring.config.name:ssh/ssh-private-key-newline" }) + @SpringBootTest( + classes = { ConfigServerApplication.class, SshPropertyValidator.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "spring.config.name:ssh/ssh-private-key-newline" }) @ActiveProfiles({ "test", "git" }) public static class StaticTest { @@ -121,9 +124,10 @@ public class TransportConfigurationIntegrationTests { } @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class, - SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "spring.config.name:ssh/ssh-private-key-newline-list" }) + @SpringBootTest( + classes = { ConfigServerApplication.class, SshPropertyValidator.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "spring.config.name:ssh/ssh-private-key-newline-list" }) @ActiveProfiles({ "test", "composite" }) public static class ListTest { @@ -149,9 +153,10 @@ public class TransportConfigurationIntegrationTests { public static class SshPropertiesWithinNestedRepo { @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class, - SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "spring.config.name:ssh/ssh-nested-settings" }) + @SpringBootTest( + classes = { ConfigServerApplication.class, SshPropertyValidator.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "spring.config.name:ssh/ssh-nested-settings" }) @ActiveProfiles({ "test", "git" }) public static class StaticTest { @@ -179,9 +184,10 @@ public class TransportConfigurationIntegrationTests { } @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class, - SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "spring.config.name:ssh/ssh-nested-settings-list" }) + @SpringBootTest( + classes = { ConfigServerApplication.class, SshPropertyValidator.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "spring.config.name:ssh/ssh-nested-settings-list" }) @ActiveProfiles({ "test", "composite" }) public static class ListTest { @@ -213,8 +219,10 @@ public class TransportConfigurationIntegrationTests { public static class FileBasedCallbackTest { @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class, - SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + @SpringBootTest( + classes = { ConfigServerApplication.class, SshPropertyValidator.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "spring.cloud.config.server.git.uri=git@gitserver.com:team/repo.git", "spring.cloud.config.server.git.ignoreLocalSshSettings=false" }) @ActiveProfiles({ "test", "git" }) @@ -271,9 +279,10 @@ public class TransportConfigurationIntegrationTests { } @RunWith(SpringRunner.class) - @SpringBootTest(classes = { ConfigServerApplication.class, - SshPropertyValidator.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "spring.cloud.config.server.composite[0].type=git", + @SpringBootTest( + classes = { ConfigServerApplication.class, SshPropertyValidator.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "spring.cloud.config.server.composite[0].type=git", "spring.cloud.config.server.composite[0].uri=git@gitserver.com:team/repo.git", "spring.cloud.config.server.composite[0].ignoreLocalSshSettings=false" }) @ActiveProfiles({ "test", "composite" }) diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java index 81331d57..50e7b900 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java @@ -42,9 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigServerApplication.class, properties = { - "spring.config.name:configserver", - "spring.cloud.config.server.git.uri:file:./target/repos/config-repo" }, webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = ConfigServerApplication.class, + properties = { "spring.config.name:configserver", + "spring.cloud.config.server.git.uri:file:./target/repos/config-repo" }, + webEnvironment = RANDOM_PORT) @ActiveProfiles("test") public class VanillaConfigServerIntegrationTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java index 67ac0d12..bfa0366d 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java @@ -53,10 +53,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class CustomCompositeEnvironmentRepositoryTests { @RunWith(SpringRunner.class) - @SpringBootTest(classes = CustomCompositeEnvironmentRepositoryTests.StaticTests.Config.class, properties = { - "spring.config.name:compositeconfigserver", - "spring.cloud.config.server.git.uri:file:./target/repos/config-repo", - "spring.cloud.config.server.git.order:1" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + @SpringBootTest( + classes = CustomCompositeEnvironmentRepositoryTests.StaticTests.Config.class, + properties = { "spring.config.name:compositeconfigserver", + "spring.cloud.config.server.git.uri:file:./target/repos/config-repo", + "spring.cloud.config.server.git.order:1" }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({ "test", "git" }) @DirtiesContext public static class StaticTests { @@ -105,12 +107,14 @@ public class CustomCompositeEnvironmentRepositoryTests { } @RunWith(SpringRunner.class) - @SpringBootTest(classes = CustomCompositeEnvironmentRepositoryTests.ListTests.Config.class, properties = { - "spring.config.name:compositeconfigserver", - "spring.cloud.config.server.composite[0].type:git", - "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", - "spring.cloud.config.server.composite[1].type:custom", - "spring.cloud.config.server.composite[1].propertySourceName:p" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + @SpringBootTest( + classes = CustomCompositeEnvironmentRepositoryTests.ListTests.Config.class, + properties = { "spring.config.name:compositeconfigserver", + "spring.cloud.config.server.composite[0].type:git", + "spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo", + "spring.cloud.config.server.composite[1].type:custom", + "spring.cloud.config.server.composite[1].propertySourceName:p" }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({ "test", "composite" }) @DirtiesContext public static class ListTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java index a6cc147a..32006ce4 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java @@ -42,8 +42,9 @@ import static org.assertj.core.api.Assertions.assertThat; * */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, properties = { - "spring.config.name:configserver" }, webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = TestApplication.class, + properties = { "spring.config.name:configserver" }, + webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @DirtiesContext public class CustomEnvironmentRepositoryTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java index 6e3f260a..41456b7f 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java @@ -95,7 +95,7 @@ public class AwsCodeCommitCredentialsProviderTests { new CredentialItem.Password(), // this is ok new CredentialItem.StringType("OK To Login?", true) // this is not // ok - })).isFalse(); + })).isFalse(); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionIntegrationTests.java index 9d5f3002..5a92e043 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionIntegrationTests.java @@ -34,8 +34,9 @@ import static org.assertj.core.api.Assertions.assertThat; public class EncryptionIntegrationTests { @RunWith(SpringRunner.class) - @SpringBootTest(classes = { - ConfigServerApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "encrypt.key=foobar") + @SpringBootTest(classes = { ConfigServerApplication.class }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = "encrypt.key=foobar") @ActiveProfiles({ "test", "native" }) @DirtiesContext public static class ConfigSymmetricEncryptionIntegrationTests { @@ -53,8 +54,9 @@ public class EncryptionIntegrationTests { } @RunWith(SpringRunner.class) - @SpringBootTest(classes = { - ConfigServerApplication.class }, properties = "spring.cloud.bootstrap.name:symmetric-key-bootstrap", webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + @SpringBootTest(classes = { ConfigServerApplication.class }, + properties = "spring.cloud.bootstrap.name:symmetric-key-bootstrap", + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({ "test", "native" }) @DirtiesContext public static class BootstrapConfigSymmetricEncryptionIntegrationTests { @@ -72,8 +74,9 @@ public class EncryptionIntegrationTests { } @RunWith(SpringRunner.class) - @SpringBootTest(classes = { - ConfigServerApplication.class }, properties = "spring.cloud.bootstrap.name:keystore-bootstrap", webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + @SpringBootTest(classes = { ConfigServerApplication.class }, + properties = "spring.cloud.bootstrap.name:keystore-bootstrap", + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({ "test", "native" }) @DirtiesContext public static class KeystoreConfigurationIntegrationTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpRequestConfigTokenProviderTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpRequestConfigTokenProviderTests.java new file mode 100644 index 00000000..12c11aec --- /dev/null +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpRequestConfigTokenProviderTests.java @@ -0,0 +1,59 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.config.server.environment; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Test; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.mock.web.MockHttpServletRequest; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * @author Scott Frederick + */ +public class HttpRequestConfigTokenProviderTests { + + private ObjectProvider httpRequestProvider; + + private HttpRequestConfigTokenProvider tokenProvider; + + @Before + @SuppressWarnings("unchecked") + public void setUp() { + httpRequestProvider = mock(ObjectProvider.class); + tokenProvider = new HttpRequestConfigTokenProvider(httpRequestProvider); + } + + @Test(expected = IllegalStateException.class) + public void missingHttpRequest() { + when(httpRequestProvider.getIfAvailable()).thenReturn(null); + tokenProvider.getToken(); + } + + @Test(expected = IllegalArgumentException.class) + public void missingTokenHeader() { + when(httpRequestProvider.getIfAvailable()) + .thenReturn(new MockHttpServletRequest()); + tokenProvider.getToken(); + } + +} diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java index 6b961d3d..49d2eca7 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java @@ -38,9 +38,9 @@ import static org.assertj.core.api.Assertions.assertThat; * */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ApplicationConfiguration.class, properties = { - "spring.datasource.schema=classpath:schema-jdbc.sql", - "spring.datasource.data=classpath:data-jdbc.sql" }) +@SpringBootTest(classes = ApplicationConfiguration.class, + properties = { "spring.datasource.schema=classpath:schema-jdbc.sql", + "spring.datasource.data=classpath:data-jdbc.sql" }) @AutoConfigureTestDatabase @DirtiesContext public class JdbcEnvironmentRepositoryTests { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java index d0ac309e..e2b16a62 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java @@ -44,10 +44,12 @@ import static org.mockito.Mockito.when; * @author Dylan Roberts */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = VaultEnvironmentRepositoryIntegrationTests.TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "server.ssl.key-store=classpath:ssl-test.jks", - "server.ssl.key-store-password=password", "server.ssl.key-password=password", - "server.key-alias=ssl-test" }) +@SpringBootTest( + classes = VaultEnvironmentRepositoryIntegrationTests.TestApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { "server.ssl.key-store=classpath:ssl-test.jks", + "server.ssl.key-store-password=password", + "server.ssl.key-password=password", "server.key-alias=ssl-test" }) public class VaultEnvironmentRepositoryIntegrationTests { @Rule @@ -58,9 +60,11 @@ public class VaultEnvironmentRepositoryIntegrationTests { @Test public void withSslValidation() throws Exception { + ObjectProvider request = withRequest(); VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory = new VaultEnvironmentRepositoryFactory( - withRequest(), new EnvironmentWatch.Default(), - Optional.of(new HttpClientVaultRestTemplateFactory())); + request, new EnvironmentWatch.Default(), + Optional.of(new HttpClientVaultRestTemplateFactory()), + withTokenProvider(request)); VaultEnvironmentRepository vaultEnvironmentRepository = vaultEnvironmentRepositoryFactory .build(withEnvironmentProperties(false)); this.expectedException.expectCause(instanceOf(SSLHandshakeException.class)); @@ -70,9 +74,11 @@ public class VaultEnvironmentRepositoryIntegrationTests { @Test public void skipSslValidation() throws Exception { + ObjectProvider request = withRequest(); VaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory = new VaultEnvironmentRepositoryFactory( - withRequest(), new EnvironmentWatch.Default(), - Optional.of(new HttpClientVaultRestTemplateFactory())); + request, new EnvironmentWatch.Default(), + Optional.of(new HttpClientVaultRestTemplateFactory()), + withTokenProvider(request)); VaultEnvironmentRepository vaultEnvironmentRepository = vaultEnvironmentRepositoryFactory .build(withEnvironmentProperties(true)); @@ -99,6 +105,11 @@ public class VaultEnvironmentRepositoryIntegrationTests { return requestProvider; } + private ConfigTokenProvider withTokenProvider( + ObjectProvider request) { + return new HttpRequestConfigTokenProvider(request); + } + @SpringBootConfiguration @EnableAutoConfiguration public static class TestApplication { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java index db5ed57d..749fdc3e 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java @@ -34,7 +34,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; @@ -51,6 +50,7 @@ import static org.mockito.Mockito.when; * @author Haroun Pacquee * @author Mark Paluch * @author Haytham Mohamed + * @author Scott Frederick */ public class VaultEnvironmentRepositoryTests { @@ -61,19 +61,9 @@ public class VaultEnvironmentRepositoryTests { this.objectMapper = new ObjectMapper(); } - @SuppressWarnings("unchecked") - private ObjectProvider mockProvide(HttpServletRequest request) { - ObjectProvider objectProvider = mock(ObjectProvider.class); - when(objectProvider.getIfAvailable()).thenReturn(request); - return objectProvider; - } - @Test @SuppressWarnings("unchecked") public void testFindOneNoDefaultKey() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); - RestTemplate rest = mock(RestTemplate.class); ResponseEntity myAppResp = mock(ResponseEntity.class); @@ -95,8 +85,8 @@ public class VaultEnvironmentRepositoryTests { eq("application"))).thenReturn(appResp); VaultEnvironmentRepository repo = new VaultEnvironmentRepository( - mockProvide(configRequest), new EnvironmentWatch.Default(), rest, - new VaultEnvironmentProperties()); + mockHttpRequest(), new EnvironmentWatch.Default(), rest, + new VaultEnvironmentProperties(), mockTokenProvider()); Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument") @@ -104,13 +94,13 @@ public class VaultEnvironmentRepositoryTests { assertThat(e.getPropertySources().size()).as( "Properties for specified application and default application with key 'application' should be returned") .isEqualTo(2); - Map firstResult = new HashMap(); + Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()).as( "Properties for specified application should be returned in priority position") .isEqualTo(firstResult); - Map secondResult = new HashMap(); + Map secondResult = new HashMap<>(); secondResult.put("def-foo", "def-bar"); assertThat(e.getPropertySources().get(1).getSource()).as( "Properties for default application with key 'application' should be returned in second position") @@ -120,9 +110,6 @@ public class VaultEnvironmentRepositoryTests { @Test @SuppressWarnings("unchecked") public void testBackendWithSlashes() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); - RestTemplate rest = mock(RestTemplate.class); ResponseEntity myAppResp = mock(ResponseEntity.class); @@ -147,8 +134,8 @@ public class VaultEnvironmentRepositoryTests { properties.setBackend("foo/bar/secret"); VaultEnvironmentRepository repo = new VaultEnvironmentRepository( - mockProvide(configRequest), new EnvironmentWatch.Default(), rest, - properties); + mockHttpRequest(), new EnvironmentWatch.Default(), rest, properties, + mockTokenProvider()); Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument") @@ -156,13 +143,13 @@ public class VaultEnvironmentRepositoryTests { assertThat(e.getPropertySources().size()).as( "Properties for specified application and default application with key 'application' should be returned") .isEqualTo(2); - Map firstResult = new HashMap(); + Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()).as( "Properties for specified application should be returned in priority position") .isEqualTo(firstResult); - Map secondResult = new HashMap(); + Map secondResult = new HashMap<>(); secondResult.put("def-foo", "def-bar"); assertThat(e.getPropertySources().get(1).getSource()).as( "Properties for default application with key 'application' should be returned in second position") @@ -172,8 +159,6 @@ public class VaultEnvironmentRepositoryTests { @Test @SuppressWarnings("unchecked") public void testFindOneDefaultKeySetAndDifferentToApplication() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); RestTemplate rest = mock(RestTemplate.class); ResponseEntity myAppResp = mock(ResponseEntity.class); @@ -195,8 +180,8 @@ public class VaultEnvironmentRepositoryTests { eq("mydefaultkey"))).thenReturn(myDefaultKeyResp); VaultEnvironmentRepository repo = new VaultEnvironmentRepository( - mockProvide(configRequest), new EnvironmentWatch.Default(), rest, - new VaultEnvironmentProperties()); + mockHttpRequest(), new EnvironmentWatch.Default(), rest, + new VaultEnvironmentProperties(), mockTokenProvider()); repo.setDefaultKey("mydefaultkey"); Environment e = repo.findOne("myapp", null, null); @@ -206,13 +191,13 @@ public class VaultEnvironmentRepositoryTests { "Properties for specified application and default application with key 'mydefaultkey' should be returned") .isEqualTo(2); - Map firstResult = new HashMap(); + Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()).as( "Properties for specified application should be returned in priority position") .isEqualTo(firstResult); - Map secondResult = new HashMap(); + Map secondResult = new HashMap<>(); secondResult.put("def-foo", "def-bar"); assertThat(e.getPropertySources().get(1).getSource()).as( "Properties for default application with key 'mydefaultkey' should be returned in second position") @@ -222,8 +207,6 @@ public class VaultEnvironmentRepositoryTests { @Test @SuppressWarnings("unchecked") public void testFindOneDefaultKeySetAndDifferentToMultipleApplications() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); RestTemplate rest = mock(RestTemplate.class); ResponseEntity myAppResp = mock(ResponseEntity.class); @@ -232,8 +215,8 @@ public class VaultEnvironmentRepositoryTests { when(myAppVaultResp.getData()).thenReturn("{\"myapp-foo\":\"myapp-bar\"}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), - eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), - eq("myapp"))).thenReturn(myAppResp); + eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), + eq("myapp"))).thenReturn(myAppResp); ResponseEntity yourAppResp = mock(ResponseEntity.class); when(yourAppResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -241,8 +224,8 @@ public class VaultEnvironmentRepositoryTests { when(yourAppVaultResp.getData()).thenReturn("{\"yourapp-foo\":\"yourapp-bar\"}"); when(yourAppResp.getBody()).thenReturn(yourAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), - eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), - eq("yourapp"))).thenReturn(yourAppResp); + eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), + eq("yourapp"))).thenReturn(yourAppResp); ResponseEntity myDefaultKeyResp = mock(ResponseEntity.class); when(myDefaultKeyResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -250,45 +233,43 @@ public class VaultEnvironmentRepositoryTests { when(myDefaultKeyVaultResp.getData()).thenReturn("{\"def-foo\":\"def-bar\"}"); when(myDefaultKeyResp.getBody()).thenReturn(myDefaultKeyVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), - eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), - eq("mydefaultkey"))).thenReturn(myDefaultKeyResp); + eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), + eq("mydefaultkey"))).thenReturn(myDefaultKeyResp); VaultEnvironmentRepository repo = new VaultEnvironmentRepository( - mockProvide(configRequest), new EnvironmentWatch.Default(), rest, - new VaultEnvironmentProperties()); + mockHttpRequest(), new EnvironmentWatch.Default(), rest, + new VaultEnvironmentProperties(), mockTokenProvider()); repo.setDefaultKey("mydefaultkey"); Environment e = repo.findOne("myapp,yourapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument") - .isEqualTo("myapp,yourapp"); + .isEqualTo("myapp,yourapp"); assertThat(e.getPropertySources().size()).as( - "Properties for specified applications and default application with key 'mydefaultkey' should be returned") - .isEqualTo(3); + "Properties for specified applications and default application with key 'mydefaultkey' should be returned") + .isEqualTo(3); - Map firstResult = new HashMap(); + Map firstResult = new HashMap<>(); firstResult.put("yourapp-foo", "yourapp-bar"); assertThat(e.getPropertySources().get(0).getSource()).as( - "Properties for first specified application should be returned in priority position") - .isEqualTo(firstResult); + "Properties for first specified application should be returned in priority position") + .isEqualTo(firstResult); - Map secondResult = new HashMap(); + Map secondResult = new HashMap<>(); secondResult.put("myapp-foo", "myapp-bar"); assertThat(e.getPropertySources().get(1).getSource()).as( - "Properties for second specified application should be returned in priority position") - .isEqualTo(secondResult); + "Properties for second specified application should be returned in priority position") + .isEqualTo(secondResult); - Map thirdResult = new HashMap(); + Map thirdResult = new HashMap<>(); thirdResult.put("def-foo", "def-bar"); assertThat(e.getPropertySources().get(2).getSource()).as( - "Properties for default application with key 'mydefaultkey' should be returned in second position") - .isEqualTo(thirdResult); + "Properties for default application with key 'mydefaultkey' should be returned in second position") + .isEqualTo(thirdResult); } @Test @SuppressWarnings("unchecked") public void testFindOneDefaultKeySetAndEqualToApplication() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); RestTemplate rest = mock(RestTemplate.class); ResponseEntity myAppResp = mock(ResponseEntity.class); @@ -310,8 +291,8 @@ public class VaultEnvironmentRepositoryTests { eq("application"))).thenReturn(appResp); VaultEnvironmentRepository repo = new VaultEnvironmentRepository( - mockProvide(configRequest), new EnvironmentWatch.Default(), rest, - new VaultEnvironmentProperties()); + mockHttpRequest(), new EnvironmentWatch.Default(), rest, + new VaultEnvironmentProperties(), mockTokenProvider()); repo.setDefaultKey("myapp"); Environment e = repo.findOne("myapp", null, null); @@ -321,7 +302,7 @@ public class VaultEnvironmentRepositoryTests { .as("Only properties for specified application should be returned") .isEqualTo(1); - Map result = new HashMap(); + Map result = new HashMap<>(); result.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()) .as("Properties should be returned for specified application") @@ -329,42 +310,20 @@ public class VaultEnvironmentRepositoryTests { } @Test(expected = IllegalArgumentException.class) - @SuppressWarnings("unchecked") public void missingConfigToken() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - RestTemplate rest = mock(RestTemplate.class); - ResponseEntity myAppResp = mock(ResponseEntity.class); - when(myAppResp.getStatusCode()).thenReturn(HttpStatus.OK); - VaultResponse myAppVaultResp = mock(VaultResponse.class); - when(myAppVaultResp.getData()).thenReturn("{\"foo\":\"bar\"}"); - when(myAppResp.getBody()).thenReturn(myAppVaultResp); - when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), - eq(HttpMethod.GET), any(HttpEntity.class), eq(VaultResponse.class), - eq("myapp"))).thenReturn(myAppResp); + ConfigTokenProvider tokenProvider = mock(ConfigTokenProvider.class); + when(tokenProvider.getToken()).thenReturn(null); + VaultEnvironmentRepository repo = new VaultEnvironmentRepository( - mockProvide(configRequest), new EnvironmentWatch.Default(), rest, - new VaultEnvironmentProperties()); - repo.findOne("myapp", null, null); - } - - @Test(expected = IllegalStateException.class) - @SuppressWarnings("unchecked") - public void missingHttpRequest() { - ObjectProvider objectProvider = mock(ObjectProvider.class); - when(objectProvider.getIfAvailable()).thenReturn(null); - - RestTemplate rest = mock(RestTemplate.class); - VaultEnvironmentRepository repo = new VaultEnvironmentRepository(objectProvider, - new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties()); + mockHttpRequest(), new EnvironmentWatch.Default(), + mock(RestTemplate.class), new VaultEnvironmentProperties(), + tokenProvider); repo.findOne("myapp", null, null); } @Test @SuppressWarnings("unchecked") public void testVaultVersioning() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); - RestTemplate rest = mock(RestTemplate.class); ResponseEntity myAppResp = mock(ResponseEntity.class); @@ -388,8 +347,8 @@ public class VaultEnvironmentRepositoryTests { final VaultEnvironmentProperties vaultEnvironmentProperties = new VaultEnvironmentProperties(); vaultEnvironmentProperties.setKvVersion(2); VaultEnvironmentRepository repo = new VaultEnvironmentRepository( - mockProvide(configRequest), new EnvironmentWatch.Default(), rest, - vaultEnvironmentProperties); + mockHttpRequest(), new EnvironmentWatch.Default(), rest, + vaultEnvironmentProperties, mockTokenProvider()); Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument") @@ -397,7 +356,7 @@ public class VaultEnvironmentRepositoryTests { assertThat(e.getPropertySources().size()).as( "Properties for specified application and default application with key 'application' should be returned") .isEqualTo(2); - Map firstResult = new HashMap(); + Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()).as( "Properties for specified application should be returned in priority position") @@ -407,9 +366,6 @@ public class VaultEnvironmentRepositoryTests { @Test @SuppressWarnings({ "Duplicates", "unchecked" }) public void testNamespaceHeaderSent() { - MockHttpServletRequest configRequest = new MockHttpServletRequest(); - configRequest.addHeader("X-CONFIG-TOKEN", "mytoken"); - RestTemplate rest = mock(RestTemplate.class); ResponseEntity myAppResp = mock(ResponseEntity.class); @@ -433,8 +389,8 @@ public class VaultEnvironmentRepositoryTests { VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); properties.setNamespace("mynamespace"); VaultEnvironmentRepository repo = new VaultEnvironmentRepository( - mockProvide(configRequest), new EnvironmentWatch.Default(), rest, - properties); + mockHttpRequest(), new EnvironmentWatch.Default(), rest, properties, + mockTokenProvider()); TestAccessStrategy accessStrategy = new TestAccessStrategy(rest, properties); repo.setAccessStrategy(accessStrategy); @@ -456,6 +412,19 @@ public class VaultEnvironmentRepositoryTests { return null; } + @SuppressWarnings("unchecked") + private ObjectProvider mockHttpRequest() { + ObjectProvider objectProvider = mock(ObjectProvider.class); + when(objectProvider.getIfAvailable()).thenReturn(null); + return objectProvider; + } + + private ConfigTokenProvider mockTokenProvider() { + ConfigTokenProvider tokenProvider = mock(ConfigTokenProvider.class); + when(tokenProvider.getToken()).thenReturn("token"); + return tokenProvider; + } + private static class TestAccessStrategy implements VaultKvAccessStrategy { private final VaultKvAccessStrategy accessStrategy; diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClientSupportTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClientSupportTest.java index 43c3210e..cd0d8559 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClientSupportTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClientSupportTest.java @@ -42,7 +42,8 @@ import static org.hamcrest.Matchers.isA; import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause; @RunWith(SpringRunner.class) -@SpringBootTest(classes = HttpClientSupportTest.TestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = HttpClientSupportTest.TestConfiguration.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HttpClientSupportTest { @Rule