Java源码示例:org.springframework.vault.authentication.SimpleSessionManager
示例1
@Test
void reactiveNamespaceSecretsAreIsolated() {
VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));
ReactiveVaultTemplate reactiveMarketing = new ReactiveVaultTemplate(this.marketingWebClientBuilder,
() -> Mono.just(VaultToken.of(this.marketingToken)));
marketing.write("marketing-secrets/my-secret", Collections.singletonMap("key", "marketing"));
assertThat(marketing.read("marketing-secrets/my-secret")).isNotNull();
reactiveMarketing.read("marketing-secrets/my-secret").as(StepVerifier::create).consumeNextWith(actual -> {
assertThat(actual.getRequiredData()).containsEntry("key", "marketing");
}).verifyComplete();
}
示例2
/**
* @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
*/
@Bean
@ConditionalOnMissingBean
@ConditionalOnAuthentication
public SessionManager vaultSessionManager(ClientAuthentication clientAuthentication,
ObjectFactory<TaskSchedulerWrapper> asyncTaskExecutorFactory) {
if (this.vaultProperties.getConfig().getLifecycle().isEnabled()) {
RestTemplate restTemplate = this.restTemplateBuilder.build();
return new LifecycleAwareSessionManager(clientAuthentication,
asyncTaskExecutorFactory.getObject().getTaskScheduler(),
restTemplate);
}
return new SimpleSessionManager(clientAuthentication);
}
示例3
@Test
public void shouldConfigureTemplate() {
this.contextRunner.withUserConfiguration(AuthenticationFactoryConfiguration.class)
.withPropertyValues("spring.cloud.vault.config.lifecycle.enabled=false")
.run(context -> {
assertThat(context.getBean(ReactiveVaultOperations.class))
.isNotNull();
assertThat(context.getBean(AuthenticationStepsFactory.class))
.isNotNull();
assertThat(context.getBean(SessionManager.class)).isNotNull()
.isNotInstanceOf(LifecycleAwareSessionManager.class)
.isNotInstanceOf(SimpleSessionManager.class);
assertThat(context.getBeanNamesForType(WebClient.class)).isEmpty();
});
}
示例4
@Test
void namespaceSecretsAreIsolated() {
VaultTemplate dev = new VaultTemplate(this.devRestTemplate,
new SimpleSessionManager(new TokenAuthentication(this.devToken)));
VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));
dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev"));
marketing.write("marketing-secrets/my-secret", Collections.singletonMap("key", "marketing"));
assertThat(dev.read("marketing-secrets/my-secret")).isNull();
assertThat(marketing.read("marketing-secrets/my-secret")).isNotNull();
}
示例5
@Test
void shouldReportInitialized() {
VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));
assertThat(marketing.opsForSys().isInitialized()).isTrue();
}
示例6
@Test
void shouldReportHealth() {
VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));
assertThat(marketing.opsForSys().health().isInitialized()).isTrue();
}
示例7
@Before
public void before() {
Assume.assumeTrue("Namespaces require enterprise version",
this.vaultRule.prepare().getVersion().isEnterprise());
List<String> namespaces = new ArrayList<>(Arrays.asList("dev/", "marketing/"));
List<String> list = this.vaultRule.prepare().getVaultOperations()
.list("sys/namespaces");
namespaces.removeAll(list);
for (String namespace : namespaces) {
this.vaultRule.prepare().getVaultOperations()
.write("sys/namespaces/" + namespace.replaceAll("/", ""));
}
this.maketingRestTemplate = RestTemplateBuilder.builder()
.requestFactory(ClientHttpRequestFactoryFactory
.create(new ClientOptions(), Settings.createSslConfiguration()))
.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "marketing");
VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
new SimpleSessionManager(new TokenAuthentication(Settings.token())));
mountKv(marketing, "marketing-secrets");
marketing.opsForSys().createOrUpdatePolicy("relaxed", POLICY);
this.marketingToken = marketing.opsForToken()
.create(VaultTokenRequest.builder().withPolicy("relaxed").build())
.getToken().getToken();
}
示例8
@Test
public void shouldReportHealth() {
VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));
Health.Builder builder = Health.unknown();
new VaultHealthIndicator(marketing).doHealthCheck(builder);
assertThat(builder.build().getStatus()).isEqualTo(Status.UP);
}
示例9
@Test
public void shouldConfigureTemplateWithTokenSupplier() {
this.contextRunner.withUserConfiguration(TokenSupplierConfiguration.class)
.withPropertyValues("spring.cloud.vault.config.lifecycle.enabled=false")
.run(context -> {
assertThat(context.getBean(ReactiveVaultOperations.class))
.isNotNull();
assertThat(context.getBean(SessionManager.class)).isNotNull()
.isNotInstanceOf(LifecycleAwareSessionManager.class)
.isNotInstanceOf(SimpleSessionManager.class);
assertThat(context.getBeanNamesForType(WebClient.class)).isEmpty();
});
}
示例10
KeyVaultService create(
Config config, EnvironmentVariableProvider envProvider, HashicorpKeyVaultServiceFactoryUtil util) {
Objects.requireNonNull(config);
Objects.requireNonNull(envProvider);
Objects.requireNonNull(util);
final String roleId = envProvider.getEnv(HASHICORP_ROLE_ID);
final String secretId = envProvider.getEnv(HASHICORP_SECRET_ID);
final String authToken = envProvider.getEnv(HASHICORP_TOKEN);
if (roleId == null && secretId == null && authToken == null) {
throw new HashicorpCredentialNotSetException(
"Environment variables must be set to authenticate with Hashicorp Vault. Set the "
+ HASHICORP_ROLE_ID
+ " and "
+ HASHICORP_SECRET_ID
+ " environment variables if using the AppRole authentication method. Set the "
+ HASHICORP_TOKEN
+ " environment variable if using another authentication method.");
} else if (isOnlyOneInputNull(roleId, secretId)) {
throw new HashicorpCredentialNotSetException(
"Only one of the "
+ HASHICORP_ROLE_ID
+ " and "
+ HASHICORP_SECRET_ID
+ " environment variables to authenticate with Hashicorp Vault using the AppRole method has been set");
}
KeyVaultConfig keyVaultConfig =
Optional.ofNullable(config.getKeys())
.flatMap(k -> k.getKeyVaultConfig(KeyVaultType.HASHICORP))
.orElseThrow(
() ->
new ConfigException(
new RuntimeException(
"Trying to create Hashicorp Vault connection but no Vault configuration provided")));
VaultEndpoint vaultEndpoint;
try {
URI uri = new URI(keyVaultConfig.getProperty("url").get());
vaultEndpoint = VaultEndpoint.from(uri);
} catch (URISyntaxException | NoSuchElementException | IllegalArgumentException e) {
throw new ConfigException(new RuntimeException("Provided Hashicorp Vault url is incorrectly formatted", e));
}
SslConfiguration sslConfiguration = util.configureSsl(keyVaultConfig, envProvider);
ClientOptions clientOptions = new ClientOptions();
ClientHttpRequestFactory clientHttpRequestFactory =
util.createClientHttpRequestFactory(clientOptions, sslConfiguration);
ClientAuthentication clientAuthentication =
util.configureClientAuthentication(
keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint);
SessionManager sessionManager = new SimpleSessionManager(clientAuthentication);
VaultOperations vaultOperations = new VaultTemplate(vaultEndpoint, clientHttpRequestFactory, sessionManager);
return new HashicorpKeyVaultService(new KeyValueOperationsDelegateFactory(vaultOperations));
}
示例11
/**
* Create a new {@link VaultTemplate} with a {@link VaultEndpoint} and
* {@link ClientAuthentication}.
* @param vaultEndpoint must not be {@literal null}.
* @param clientAuthentication must not be {@literal null}.
*/
public VaultTemplate(VaultEndpoint vaultEndpoint, ClientAuthentication clientAuthentication) {
Assert.notNull(vaultEndpoint, "VaultEndpoint must not be null");
Assert.notNull(clientAuthentication, "ClientAuthentication must not be null");
this.sessionManager = new SimpleSessionManager(clientAuthentication);
this.dedicatedSessionManager = true;
ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
VaultEndpointProvider endpointProvider = SimpleVaultEndpointProvider.of(vaultEndpoint);
this.statelessTemplate = doCreateRestTemplate(endpointProvider, requestFactory);
this.sessionTemplate = doCreateSessionTemplate(endpointProvider, requestFactory);
}
示例12
@BeforeEach
void before() {
Assumptions.assumeTrue(prepare().getVersion().isEnterprise(), "Namespaces require enterprise version");
List<String> namespaces = new ArrayList<>(Arrays.asList("dev/", "marketing/"));
List<String> list = prepare().getVaultOperations().list("sys/namespaces");
namespaces.removeAll(list);
for (String namespace : namespaces) {
prepare().getVaultOperations().write("sys/namespaces/" + namespace.replaceAll("/", ""));
}
this.devRestTemplate = RestTemplateBuilder.builder()
.requestFactory(
ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration()))
.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).customizers(restTemplate -> restTemplate
.getInterceptors().add(VaultClients.createNamespaceInterceptor("dev")));
this.maketingRestTemplate = RestTemplateBuilder.builder()
.requestFactory(
ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration()))
.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "marketing");
VaultTemplate dev = new VaultTemplate(this.devRestTemplate,
new SimpleSessionManager(new TokenAuthentication(Settings.token())));
mountKv(dev, "dev-secrets");
dev.opsForSys().createOrUpdatePolicy("relaxed", POLICY);
this.devToken = dev.opsForToken().create(VaultTokenRequest.builder().withPolicy("relaxed").build()).getToken()
.getToken();
VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
new SimpleSessionManager(new TokenAuthentication(Settings.token())));
mountKv(marketing, "marketing-secrets");
marketing.opsForSys().createOrUpdatePolicy("relaxed", POLICY);
this.marketingToken = marketing.opsForToken().create(VaultTokenRequest.builder().withPolicy("relaxed").build())
.getToken().getToken();
}