org.springframework.vault.authentication.SimpleSessionManager Java Examples

The following examples show how to use org.springframework.vault.authentication.SimpleSessionManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VaultNamespaceSecretIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #2
Source File: VaultBootstrapConfiguration.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
/**
 * @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);
}
 
Example #3
Source File: VaultReactiveBootstrapConfigurationTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@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();
			});
}
 
Example #4
Source File: VaultNamespaceSecretIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #5
Source File: VaultNamespaceSecretIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldReportInitialized() {

	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));

	assertThat(marketing.opsForSys().isInitialized()).isTrue();
}
 
Example #6
Source File: VaultNamespaceSecretIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldReportHealth() {

	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));

	assertThat(marketing.opsForSys().health().isInitialized()).isTrue();
}
 
Example #7
Source File: VaultNamespaceTests.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #8
Source File: VaultNamespaceTests.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #9
Source File: VaultReactiveBootstrapConfigurationTests.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@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();
			});
}
 
Example #10
Source File: HashicorpKeyVaultServiceFactory.java    From tessera with Apache License 2.0 4 votes vote down vote up
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));
}
 
Example #11
Source File: VaultTemplate.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}
 
Example #12
Source File: VaultNamespaceSecretIntegrationTests.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@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();
}