org.springframework.vault.support.ClientOptions Java Examples

The following examples show how to use org.springframework.vault.support.ClientOptions. 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: ReactiveVaultClientsIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUseVaultEndpointProvider() {

	AtomicReference<Thread> resolver = new AtomicReference<>();

	WebClient client = ReactiveVaultClients.createWebClient(() -> {

		return Mono.fromSupplier(() -> {
			resolver.set(Thread.currentThread());
			return TestRestTemplateFactory.TEST_VAULT_ENDPOINT;
		});
	}, ClientHttpConnectorFactory.create(new ClientOptions(), Settings.createSslConfiguration()));

	client.get().uri("/sys/health").exchange().flatMap(it -> it.bodyToMono(String.class)).as(StepVerifier::create)
			.consumeNextWith(actual -> {
				assertThat(actual).contains("initialized").contains("standby");
			}).verifyComplete();

	client.get().uri("sys/health").exchange().flatMap(it -> it.bodyToMono(String.class)).as(StepVerifier::create)
			.consumeNextWith(actual -> {
				assertThat(actual).contains("initialized").contains("standby");
			}).verifyComplete();

	assertThat(resolver).hasValue(Thread.currentThread());
}
 
Example #2
Source File: ClientHttpRequestFactoryFactoryIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void httpComponentsClientUsingPemShouldWork() throws Exception {

	File caCertificate = new File(Settings.findWorkDir(), "ca/certs/ca.cert.pem");
	SslConfiguration sslConfiguration = SslConfiguration.forTrustStore(SslConfiguration.KeyStoreConfiguration
			.of(new FileSystemResource(caCertificate)).withStoreType(SslConfiguration.PEM_KEYSTORE_TYPE));

	ClientHttpRequestFactory factory = HttpComponents.usingHttpComponents(new ClientOptions(), sslConfiguration);
	RestTemplate template = new RestTemplate(factory);

	String response = request(template);

	assertThat(factory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
	assertThat(response).isNotNull().contains("initialized");

	((DisposableBean) factory).destroy();
}
 
Example #3
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link ClientHttpConnector} for the given {@link ClientOptions} and
 * {@link SslConfiguration}.
 * @param options must not be {@literal null}
 * @param sslConfiguration must not be {@literal null}
 * @return a new {@link ClientHttpConnector}.
 */
public static ClientHttpConnector create(ClientOptions options, SslConfiguration sslConfiguration) {

	Assert.notNull(options, "ClientOptions must not be null");
	Assert.notNull(sslConfiguration, "SslConfiguration must not be null");

	if (REACTOR_NETTY_PRESENT) {
		return ReactorNetty.usingReactorNetty(options, sslConfiguration);
	}

	if (JETTY_PRESENT) {
		return JettyClient.usingJetty(options, sslConfiguration);
	}

	throw new IllegalStateException("No supported Reactive Http Client library available (Reactor Netty, Jetty)");
}
 
Example #4
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
static ClientHttpConnector usingReactorNetty(ClientOptions options, SslConfiguration sslConfiguration) {
	HttpClient client = HttpClient.create();

	if (hasSslConfiguration(sslConfiguration)) {

		SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
		configureSsl(sslConfiguration, sslContextBuilder);

		client = client.secure(builder -> {
			builder.sslContext(sslContextBuilder);
		});
	}

	client = client.tcpConfiguration(it -> it.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
			Math.toIntExact(options.getConnectionTimeout().toMillis())));

	return new ReactorClientHttpConnector(client);
}
 
Example #5
Source File: VaultReactiveHealthIndicatorIntegrationTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnHealthState() {

	ReactiveVaultTemplate vaultTemplate = new ReactiveVaultTemplate(
			TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			ClientHttpConnectorFactory.create(new ClientOptions(),
					Settings.createSslConfiguration()),
			() -> Mono.just(Settings.token()));

	VaultReactiveHealthIndicator healthIndicator = new VaultReactiveHealthIndicator(
			vaultTemplate);

	healthIndicator.doHealthCheck(Health.up()).as(StepVerifier::create)
			.consumeNextWith(actual -> {
				assertThat(actual.getStatus()).isEqualTo(Status.UP);
			}).verifyComplete();
}
 
Example #6
Source File: ClientCertificateAuthenticationIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldLoginSuccessfully() {

	ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(),
			prepareCertAuthenticationMethod());

	RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			clientHttpRequestFactory);
	ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(restTemplate);
	VaultToken login = authentication.login();

	assertThat(login.getToken()).isNotEmpty();
}
 
Example #7
Source File: TestWebClientFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link WebClient} using the {@link SslConfiguration}. See
 * {@link ReactiveVaultClients#createWebClient(VaultEndpoint, ClientHttpConnector)} to
 * create {@link WebClient} for a given {@link ClientHttpConnector}.
 * @param sslConfiguration must not be {@literal null}.
 * @return
 */
public static WebClient create(SslConfiguration sslConfiguration) {

	Assert.notNull(sslConfiguration, "SslConfiguration must not be null!");

	try {
		ClientHttpConnector connector = ClientHttpConnectorFactory.create(new ClientOptions(), sslConfiguration);
		return ReactiveVaultClients.createWebClient(TEST_VAULT_ENDPOINT, connector);
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
Example #8
Source File: ClientHttpRequestFactoryFactoryIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void nettyClientShouldWork() throws Exception {

	ClientHttpRequestFactory factory = Netty.usingNetty(new ClientOptions(), Settings.createSslConfiguration());
	((InitializingBean) factory).afterPropertiesSet();
	RestTemplate template = new RestTemplate(factory);

	String response = request(template);

	assertThat(factory).isInstanceOf(Netty4ClientHttpRequestFactory.class);
	assertThat(response).isNotNull().contains("initialized");

	((DisposableBean) factory).destroy();
}
 
Example #9
Source File: ClientHttpRequestFactoryFactoryIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void httpComponentsClientShouldWork() throws Exception {

	ClientHttpRequestFactory factory = HttpComponents.usingHttpComponents(new ClientOptions(),
			Settings.createSslConfiguration());
	RestTemplate template = new RestTemplate(factory);

	String response = request(template);

	assertThat(factory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
	assertThat(response).isNotNull().contains("initialized");

	((DisposableBean) factory).destroy();
}
 
Example #10
Source File: TestRestTemplateFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static void initializeClientHttpRequestFactory(SslConfiguration sslConfiguration) throws Exception {

		if (factoryCache.get() != null) {
			return;
		}

		final ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory
				.create(new ClientOptions(), sslConfiguration);

		if (factoryCache.compareAndSet(null, clientHttpRequestFactory)) {

			if (clientHttpRequestFactory instanceof InitializingBean) {
				((InitializingBean) clientHttpRequestFactory).afterPropertiesSet();
			}

			if (clientHttpRequestFactory instanceof DisposableBean) {

				Runtime.getRuntime().addShutdownHook(new Thread("ClientHttpRequestFactory Shutdown Hook") {

					@Override
					public void run() {
						try {
							((DisposableBean) clientHttpRequestFactory).destroy();
						}
						catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		}
	}
 
Example #11
Source File: VaultTemplateAgentIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {

	try (Socket socket = new Socket()) {

		socket.connect(new InetSocketAddress(this.endpoint.getHost(), this.endpoint.getPort()),
				(int) new ClientOptions().getConnectionTimeout().toMillis());
	}
	catch (IOException e) {
		throw new TestAbortedException("Vault Agent not available: " + e.getMessage());
	}
}
 
Example #12
Source File: ReactiveVaultTemplateAgentIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {

	try (Socket socket = new Socket()) {

		socket.connect(new InetSocketAddress(this.endpoint.getHost(), this.endpoint.getPort()),
				(int) new ClientOptions().getConnectionTimeout().toMillis());
	}
	catch (IOException e) {
		throw new TestAbortedException("Vault Agent not available: " + e.getMessage());
	}
}
 
Example #13
Source File: ClientCertificateAuthenticationStepsIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void authenticationStepsLoginShouldFail() {

	ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(),
			Settings.createSslConfiguration());
	RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			clientHttpRequestFactory);

	assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(
			() -> new AuthenticationStepsExecutor(ClientCertificateAuthentication.createAuthenticationSteps(),
					restTemplate).login());
}
 
Example #14
Source File: ClientCertificateAuthenticationIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void loginShouldFail() {

	ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(),
			Settings.createSslConfiguration());
	RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			clientHttpRequestFactory);

	assertThatExceptionOfType(NestedRuntimeException.class)
			.isThrownBy(() -> new ClientCertificateAuthentication(restTemplate).login());
}
 
Example #15
Source File: VaultBootstrapConfiguration.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link ClientFactoryWrapper} containing a
 * {@link ClientHttpRequestFactory}. {@link ClientHttpRequestFactory} is not exposed
 * as root bean because {@link ClientHttpRequestFactory} is configured with
 * {@link ClientOptions} and {@link SslConfiguration} which are not necessarily
 * applicable for the whole application.
 * @return the {@link ClientFactoryWrapper} to wrap a {@link ClientHttpRequestFactory}
 * instance.
 */
@Bean
@ConditionalOnMissingBean
public ClientFactoryWrapper clientHttpRequestFactoryWrapper() {

	ClientOptions clientOptions = new ClientOptions(
			Duration.ofMillis(this.vaultProperties.getConnectionTimeout()),
			Duration.ofMillis(this.vaultProperties.getReadTimeout()));

	SslConfiguration sslConfiguration = VaultConfigurationUtil
			.createSslConfiguration(this.vaultProperties.getSsl());

	return new ClientFactoryWrapper(
			ClientHttpRequestFactoryFactory.create(clientOptions, sslConfiguration));
}
 
Example #16
Source File: ClientCertificateAuthenticationIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSelectInvalidKey() {

	ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(),
			prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "2")));

	RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			clientHttpRequestFactory);
	ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(restTemplate);

	assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(authentication::login);
}
 
Example #17
Source File: ClientCertificateAuthenticationIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSelectKey() {

	ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(),
			prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "1")));

	RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			clientHttpRequestFactory);
	ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(restTemplate);
	VaultToken login = authentication.login();

	assertThat(login.getToken()).isNotEmpty();
}
 
Example #18
Source File: VaultReactiveBootstrapConfiguration.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link ClientHttpConnector} configured with {@link ClientOptions} and
 * {@link SslConfiguration} which are not necessarily applicable for the whole
 * application.
 * @param vaultProperties the Vault properties.
 * @return the {@link ClientHttpConnector}.
 */
private static ClientHttpConnector createConnector(VaultProperties vaultProperties) {

	ClientOptions clientOptions = new ClientOptions(
			Duration.ofMillis(vaultProperties.getConnectionTimeout()),
			Duration.ofMillis(vaultProperties.getReadTimeout()));

	SslConfiguration sslConfiguration = VaultConfigurationUtil
			.createSslConfiguration(vaultProperties.getSsl());

	return ClientHttpConnectorFactory.create(clientOptions, sslConfiguration);
}
 
Example #19
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 #20
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static org.eclipse.jetty.client.HttpClient configureClient(
		org.eclipse.jetty.client.HttpClient httpClient, ClientOptions options) {

	httpClient.setConnectTimeout(options.getConnectionTimeout().toMillis());
	httpClient.setAddressResolutionTimeout(options.getConnectionTimeout().toMillis());

	return httpClient;
}
 
Example #21
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
static ClientHttpConnector usingJetty(ClientOptions options, SslConfiguration sslConfiguration) {

			try {
				return new JettyClientHttpConnector(configureClient(getHttpClient(sslConfiguration), options));
			}
			catch (GeneralSecurityException | IOException e) {
				throw new IllegalStateException(e);
			}
		}
 
Example #22
Source File: ClientHttpRequestFactoryFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
static ClientHttpRequestFactory usingNetty(ClientOptions options, SslConfiguration sslConfiguration)
		throws GeneralSecurityException, IOException {

	Netty4ClientHttpRequestFactory requestFactory = new Netty4ClientHttpRequestFactory();

	if (hasSslConfiguration(sslConfiguration)) {

		SslContextBuilder sslContextBuilder = SslContextBuilder //
				.forClient();

		if (sslConfiguration.getTrustStoreConfiguration().isPresent()) {
			sslContextBuilder
					.trustManager(createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration()));
		}

		if (sslConfiguration.getKeyStoreConfiguration().isPresent()) {
			sslContextBuilder.keyManager(createKeyManagerFactory(sslConfiguration.getKeyStoreConfiguration(),
					sslConfiguration.getKeyConfiguration()));
		}

		requestFactory.setSslContext(sslContextBuilder.sslProvider(SslProvider.JDK).build());
	}

	requestFactory.setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis()));
	requestFactory.setReadTimeout(Math.toIntExact(options.getReadTimeout().toMillis()));

	return requestFactory;
}
 
Example #23
Source File: TestRestTemplateFactory.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
private static void initializeClientHttpRequestFactory(
		SslConfiguration sslConfiguration) throws Exception {

	if (factoryCache.get() != null) {
		return;
	}

	final ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory
			.create(new ClientOptions(), sslConfiguration);

	if (factoryCache.compareAndSet(null, clientHttpRequestFactory)) {

		if (clientHttpRequestFactory instanceof InitializingBean) {
			((InitializingBean) clientHttpRequestFactory).afterPropertiesSet();
		}

		if (clientHttpRequestFactory instanceof DisposableBean) {

			Runtime.getRuntime().addShutdownHook(
					new Thread("ClientHttpRequestFactory Shutdown Hook") {

						@Override
						public void run() {
							try {
								((DisposableBean) clientHttpRequestFactory).destroy();
							}
							catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
		}
	}
}
 
Example #24
Source File: ClientHttpRequestFactoryFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
		throws GeneralSecurityException, IOException {

	HttpClientBuilder httpClientBuilder = HttpClients.custom();

	httpClientBuilder.setRoutePlanner(
			new SystemDefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));

	if (hasSslConfiguration(sslConfiguration)) {

		SSLContext sslContext = getSSLContext(sslConfiguration, getTrustManagers(sslConfiguration));
		SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
		httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
		httpClientBuilder.setSSLContext(sslContext);
	}

	RequestConfig requestConfig = RequestConfig.custom()
			//
			.setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis())) //
			.setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis())) //
			.setAuthenticationEnabled(true) //
			.build();

	httpClientBuilder.setDefaultRequestConfig(requestConfig);

	// Support redirects
	httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

	return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
 
Example #25
Source File: ClientHttpRequestFactoryFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link ClientHttpRequestFactory} for the given {@link ClientOptions} and
 * {@link SslConfiguration}.
 * @param options must not be {@literal null}
 * @param sslConfiguration must not be {@literal null}
 * @return a new {@link ClientHttpRequestFactory}. Lifecycle beans must be initialized
 * after obtaining.
 */
public static ClientHttpRequestFactory create(ClientOptions options, SslConfiguration sslConfiguration) {

	Assert.notNull(options, "ClientOptions must not be null");
	Assert.notNull(sslConfiguration, "SslConfiguration must not be null");

	try {

		if (HTTP_COMPONENTS_PRESENT) {
			return HttpComponents.usingHttpComponents(options, sslConfiguration);
		}

		if (OKHTTP3_PRESENT) {
			return OkHttp3.usingOkHttp3(options, sslConfiguration);
		}

		if (NETTY_PRESENT) {
			return Netty.usingNetty(options, sslConfiguration);
		}
	}
	catch (GeneralSecurityException | IOException e) {
		throw new IllegalStateException(e);
	}

	if (hasSslConfiguration(sslConfiguration)) {
		logger.warn("VaultProperties has SSL configured but the SSL configuration "
				+ "must be applied outside the Vault Client to use the JDK HTTP client");
	}

	return new SimpleClientHttpRequestFactory();
}
 
Example #26
Source File: HashicorpKeyVaultServiceFactoryUtilTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void createClientHttpRequestFactory() {
    ClientOptions clientOptions = mock(ClientOptions.class);
    SslConfiguration sslConfiguration = mock(SslConfiguration.class);

    SslConfiguration.KeyStoreConfiguration keyStoreConfiguration = mock(SslConfiguration.KeyStoreConfiguration.class);
    when(sslConfiguration.getKeyStoreConfiguration()).thenReturn(keyStoreConfiguration);
    when(sslConfiguration.getTrustStoreConfiguration()).thenReturn(keyStoreConfiguration);

    when(clientOptions.getConnectionTimeout()).thenReturn(Duration.ZERO);
    when(clientOptions.getReadTimeout()).thenReturn(Duration.ZERO);

    ClientHttpRequestFactory result = util.createClientHttpRequestFactory(clientOptions, sslConfiguration);

    assertThat(result).isInstanceOf(OkHttp3ClientHttpRequestFactory.class);
}
 
Example #27
Source File: KubernetesHashicorpVaultClientAuthenticationProvider.java    From knox with Apache License 2.0 5 votes vote down vote up
private RestOperations getRestOperations(Map<String, String> properties) throws Exception {
  String vaultAddress = properties.get(HashicorpVaultAliasService.VAULT_ADDRESS_KEY);
  VaultEndpoint vaultEndpoint = VaultEndpoint.from(new URI(vaultAddress));
  VaultEndpointProvider vaultEndpointProvider = SimpleVaultEndpointProvider.of(vaultEndpoint);
  ClientOptions clientOptions = new ClientOptions();
  SslConfiguration sslConfiguration = SslConfiguration.unconfigured();
  ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(
      clientOptions, sslConfiguration);
  return VaultClients.createRestTemplate(vaultEndpointProvider, clientHttpRequestFactory);
}
 
Example #28
Source File: VaultConfig.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
        throws GeneralSecurityException, IOException {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(
            DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));

    if (isNoneEmpty(httpsProxyUser, httpsProxyPassword)) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(httpsProxyUser, httpsProxyPassword);
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }

    if (hasSslConfiguration(sslConfiguration)) {
        SSLContext sslContext = getSSLContext(sslConfiguration,
                getTrustManagers(sslConfiguration));
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setSSLContext(sslContext);
    }

    RequestConfig requestConfig = RequestConfig
            .custom()
            .setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis()))
            .setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis()))
            .setAuthenticationEnabled(true)
            .build();

    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
 
Example #29
Source File: ClientCertificateNamespaceIntegrationTests.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("/", ""));
	}

	RestTemplateBuilder devRestTemplate = RestTemplateBuilder.builder()
			.requestFactory(
					ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration()))
			.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).customizers(restTemplate -> restTemplate
					.getInterceptors().add(VaultClients.createNamespaceInterceptor("dev")));

	VaultTemplate dev = new VaultTemplate(devRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(Settings.token())));

	mountKv(dev, "dev-secrets");
	dev.opsForSys().createOrUpdatePolicy("relaxed", POLICY);

	if (!dev.opsForSys().getAuthMounts().containsKey("cert/")) {
		dev.opsForSys().authMount("cert", VaultMount.create("cert"));
	}

	dev.doWithSession((RestOperationsCallback<Object>) restOperations -> {

		File workDir = findWorkDir();

		String certificate = Files.contentOf(new File(workDir, "ca/certs/client.cert.pem"),
				StandardCharsets.US_ASCII);

		Map<String, String> role = new LinkedHashMap<>();
		role.put("token_policies", "relaxed");
		role.put("policies", "relaxed");
		role.put("certificate", certificate);

		return restOperations.postForEntity("auth/cert/certs/relaxed", role, Map.class);
	});
}
 
Example #30
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();
}