Java Code Examples for org.springframework.vault.client.VaultEndpoint

The following examples show how to use org.springframework.vault.client.VaultEndpoint. These examples are extracted from open source projects. 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
@Test
public void configureClientAuthenticationIfAllEnvVarsSetThenAppRoleMethod() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn("role-id");
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn("secret-id");
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn("token");

    when(keyVaultConfig.getProperty("approlePath")).thenReturn(Optional.of("approle"));

    ClientAuthentication result = util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint);

    assertThat(result).isInstanceOf(AppRoleAuthentication.class);
}
 
Example 2
@Test
public void configureClientAuthenticationIfOnlyRoleIdAndSecretIdSetThenAppRoleMethod() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn("role-id");
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn("secret-id");
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn(null);

    when(keyVaultConfig.getProperty("approlePath")).thenReturn(Optional.of("somepath"));

    ClientAuthentication result = util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint);

    assertThat(result).isInstanceOf(AppRoleAuthentication.class);
}
 
Example 3
@Test
public void configureClientAuthenticationIfOnlyRoleIdSetThenException() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn("role-id");
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn(null);

    Throwable ex = catchThrowable(() -> util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint));

    assertThat(ex).isExactlyInstanceOf(HashicorpCredentialNotSetException.class);
    assertThat(ex.getMessage()).isEqualTo("Both " + HASHICORP_ROLE_ID + " and " + HASHICORP_SECRET_ID + " environment variables must be set to use the AppRole authentication method");
}
 
Example 4
@Test
public void configureClientAuthenticationIfOnlySecretIdSetThenException() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn("secret-id");
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn(null);

    Throwable ex = catchThrowable(() -> util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint));

    assertThat(ex).isExactlyInstanceOf(HashicorpCredentialNotSetException.class);
    assertThat(ex.getMessage()).isEqualTo("Both " + HASHICORP_ROLE_ID + " and " + HASHICORP_SECRET_ID + " environment variables must be set to use the AppRole authentication method");
}
 
Example 5
@Test
public void configureClientAuthenticationIfNoEnvVarSetThenException() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn(null);

    Throwable ex = catchThrowable(() -> util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint));

    assertThat(ex).isExactlyInstanceOf(HashicorpCredentialNotSetException.class);
    assertThat(ex.getMessage()).isEqualTo("Both " + HASHICORP_ROLE_ID + " and " + HASHICORP_SECRET_ID + " environment variables must be set to use the AppRole authentication method.  Alternatively set " + HASHICORP_TOKEN + " to authenticate using the Token method");
}
 
Example 6
Source Project: spring-vault   Source File: VaultInitializer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a new {@link VaultInitializer} with the given {@link SslConfiguration} and
 * {@link VaultEndpoint}.
 * @param sslConfiguration must not be {@literal null}.
 * @param vaultEndpoint must not be {@literal null}.
 */
public VaultInitializer(SslConfiguration sslConfiguration, VaultEndpoint vaultEndpoint) {

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

	RestTemplate restTemplate = TestRestTemplateFactory.create(sslConfiguration);
	WebClient webClient = TestWebClientFactory.create(sslConfiguration);

	VaultTemplate vaultTemplate = new VaultTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			restTemplate.getRequestFactory(), new PreparingSessionManager());

	this.token = Settings.token();

	this.prepareVault = new PrepareVault(webClient, TestRestTemplateFactory.create(sslConfiguration),
			vaultTemplate);
	this.vaultEndpoint = vaultEndpoint;
}
 
Example 7
@Test
public void shouldRegisterDefaultBeans() {

	this.contextRunner.withUserConfiguration(DiscoveryConfiguration.class)
			.withPropertyValues("spring.cloud.vault.token=foo",
					"spring.cloud.vault.discovery.enabled=true")
			.run(context -> {

				assertThat(context.getBean(VaultServiceInstanceProvider.class))
						.isInstanceOf(
								DiscoveryClientVaultServiceInstanceProvider.class);

				VaultEndpointProvider endpointProvider = context
						.getBean(VaultEndpointProvider.class);
				VaultEndpoint vaultEndpoint = endpointProvider.getVaultEndpoint();
				assertThat(vaultEndpoint.getPort()).isEqualTo(1234);
			});
}
 
Example 8
Source Project: spring-cloud-vault   Source File: VaultRule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a new {@link VaultRule} with the given {@link SslConfiguration} and
 * {@link VaultEndpoint}.
 * @param sslConfiguration must not be {@literal null}.
 * @param vaultEndpoint must not be {@literal null}.
 */
public VaultRule(SslConfiguration sslConfiguration, VaultEndpoint vaultEndpoint) {

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

	ClientHttpRequestFactory requestFactory = TestRestTemplateFactory
			.create(sslConfiguration).getRequestFactory();

	VaultTemplate vaultTemplate = new VaultTemplate(vaultEndpoint, requestFactory,
			new PreparingSessionManager());

	this.token = Settings.token();
	this.prepareVault = new PrepareVault(vaultTemplate);
	this.vaultEndpoint = vaultEndpoint;
}
 
Example 9
Source Project: knox   Source File: HashicorpVaultAliasService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(GatewayConfig config, Map<String, String> options) throws ServiceLifecycleException {
  this.config = config;
  Map<String, String> remoteAliasServiceConfiguration = config.getRemoteAliasServiceConfiguration();
  Map<String, String> vaultConfiguration = new HashMap<>();
  for(Map.Entry<String, String> entry : remoteAliasServiceConfiguration.entrySet()) {
    if(entry.getKey().startsWith(VAULT_CONFIG_PREFIX)) {
      vaultConfiguration.put(entry.getKey(),
          entry.getValue());
    }
  }

  String vaultAddress = vaultConfiguration.get(VAULT_ADDRESS_KEY);
  String vaultSecretsEngine = vaultConfiguration.get(VAULT_SECRETS_ENGINE_KEY);
  vaultPathPrefix = getVaultPathPrefix(vaultConfiguration);

  VaultEndpoint vaultEndpoint;
  try {
    vaultEndpoint = VaultEndpoint.from(new URI(vaultAddress));
    ClientAuthentication vaultAuthentication = getClientAuthentication(vaultConfiguration);
    VaultTemplate vaultTemplate = new VaultTemplate(vaultEndpoint, vaultAuthentication);
    vault = vaultTemplate.opsForVersionedKeyValue(vaultSecretsEngine);
  } catch (Exception e) {
    throw new ServiceLifecycleException("Failed to init", e);
  }
}
 
Example 10
@Test
public void configureClientAuthenticationIfOnlyTokenSetThenTokenMethod() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn("token");

    ClientAuthentication result = util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint);

    assertThat(result).isInstanceOf(TokenAuthentication.class);
}
 
Example 11
@Override
public VaultEndpoint vaultEndpoint() {

	String uri = getProperty("vault.uri");
	if (uri != null) {
		return VaultEndpoint.from(URI.create(uri));
	}

	throw new IllegalStateException("Vault URI (vault.uri) is null");
}
 
Example 12
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "spring.cloud.vault.enabled", matchIfMissing = true)
public VaultEndpointProvider vaultEndpointProvider(
		VaultServiceInstanceProvider instanceProvider) {

	String serviceId = this.vaultProperties.getDiscovery().getServiceId();
	String fallbackScheme;

	if (StringUtils.hasText(this.vaultProperties.getUri())) {
		fallbackScheme = URI.create(this.vaultProperties.getUri()).getScheme();
	}
	else {
		fallbackScheme = this.vaultProperties.getScheme();
	}

	ServiceInstance server = instanceProvider.getVaultServerInstance(serviceId);

	VaultEndpoint vaultEndpoint = VaultEndpoint.create(server.getHost(),
			server.getPort());

	if (server.getMetadata().containsKey("scheme")) {
		vaultEndpoint.setScheme(server.getMetadata().get("scheme"));
	}
	else {
		vaultEndpoint.setScheme(server.isSecure() ? "https" : fallbackScheme);
	}

	return () -> vaultEndpoint;
}
 
Example 13
Source Project: spring-cloud-vault   Source File: VaultConfigurationUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link VaultEndpoint} given {@link VaultProperties}.
 * @param vaultProperties the Vault properties.
 * @return the endpoint.
 */
static VaultEndpoint createVaultEndpoint(VaultProperties vaultProperties) {

	if (StringUtils.hasText(vaultProperties.getUri())) {
		return VaultEndpoint.from(URI.create(vaultProperties.getUri()));
	}

	VaultEndpoint vaultEndpoint = new VaultEndpoint();
	vaultEndpoint.setHost(vaultProperties.getHost());
	vaultEndpoint.setPort(vaultProperties.getPort());
	vaultEndpoint.setScheme(vaultProperties.getScheme());

	return vaultEndpoint;
}
 
Example 14
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 15
@Override
public VaultEndpoint vaultEndpoint() {

	URI baseUrl = UriComponentsBuilder.newInstance()
			.scheme(vaultProperties.getScheme()).host(vaultProperties.getHost())
			.port(vaultProperties.getPort()).build().toUri();

	return VaultEndpoint.from(baseUrl);
}
 
Example 16
private SpringVaultClientConfiguration mockClientConfiguration() {
	VaultTemplate vaultTemplate = new VaultTemplate(
			VaultEndpoint.create("localhost", 8200),
			new TokenAuthentication("token"));

	SpringVaultClientConfiguration clientConfiguration = mock(
			SpringVaultClientConfiguration.class);
	when(clientConfiguration.vaultTemplate()).thenReturn(vaultTemplate);

	return clientConfiguration;
}
 
Example 17
Source Project: vault-crd   Source File: VaultConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public VaultEndpoint vaultEndpoint() {
    return VaultEndpoint.from(getVaultUrlWithoutPath(vaultUrl));
}
 
Example 18
Source Project: vault-crd   Source File: VaultConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public VaultEndpoint vaultEndpoint() {
    return VaultEndpoint.from(getVaultUrlWithoutPath(vaultUrl));
}
 
Example 19
Source Project: tessera   Source File: HashicorpKeyVaultServiceFactory.java    License: 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 20
private void setUpUtilMocks(KeyVaultConfig keyVaultConfig) {
    SslConfiguration sslConfiguration = mock(SslConfiguration.class);
    when(keyVaultServiceFactoryUtil.configureSsl(keyVaultConfig, envProvider)).thenReturn(sslConfiguration);

    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    when(keyVaultServiceFactoryUtil.createClientHttpRequestFactory(
        any(ClientOptions.class),
        eq(sslConfiguration))
    ).thenReturn(clientHttpRequestFactory);

    ClientAuthentication clientAuthentication = mock(ClientAuthentication.class);
    when(keyVaultServiceFactoryUtil.configureClientAuthentication(
        eq(keyVaultConfig),
        eq(envProvider),
        eq(clientHttpRequestFactory),
        any(VaultEndpoint.class))
    ).thenReturn(clientAuthentication);
}
 
Example 21
Source Project: spring-vault   Source File: VaultTemplate.java    License: 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 22
Source Project: spring-vault   Source File: VaultApp.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

		VaultTemplate vaultTemplate = new VaultTemplate(new VaultEndpoint(),
				new TokenAuthentication("00000000-0000-0000-0000-000000000000"));

		Secrets secrets = new Secrets();
		secrets.username = "hello";
		secrets.password = "world";

		vaultTemplate.write("secret/myapp", secrets);

		VaultResponseSupport<Secrets> response = vaultTemplate.read("secret/myapp", Secrets.class);
		System.out.println(response.getRequiredData().getUsername());

		vaultTemplate.delete("secret/myapp");
	}
 
Example 23
@Override
public VaultEndpoint vaultEndpoint() {
	return TestRestTemplateFactory.TEST_VAULT_ENDPOINT;
}
 
Example 24
@Override
public VaultEndpoint vaultEndpoint() {
	return TestRestTemplateFactory.TEST_VAULT_ENDPOINT;
}
 
Example 25
@Override
public VaultEndpoint vaultEndpoint() {
	return TestRestTemplateFactory.TEST_VAULT_ENDPOINT;
}
 
Example 26
@Override
public VaultEndpoint vaultEndpoint() {
	return TestRestTemplateFactory.TEST_VAULT_ENDPOINT;
}
 
Example 27
Source Project: cloudbreak   Source File: VaultConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public VaultEndpoint vaultEndpoint() {
    VaultEndpoint endpoint = VaultEndpoint.create(address, port);
    endpoint.setScheme(sslEnabled ? "https" : "http");
    return endpoint;
}
 
Example 28
Source Project: tutorials   Source File: VaultConfig.java    License: MIT License 4 votes vote down vote up
@Override
public VaultEndpoint vaultEndpoint() {
    return VaultEndpoint.create("host", 8020);
}
 
Example 29
ClientAuthentication configureClientAuthentication(KeyVaultConfig keyVaultConfig, EnvironmentVariableProvider envProvider, ClientHttpRequestFactory clientHttpRequestFactory, VaultEndpoint vaultEndpoint) {

        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) {

            AppRoleAuthenticationOptions appRoleAuthenticationOptions = AppRoleAuthenticationOptions.builder()
                .path(keyVaultConfig.getProperty("approlePath").get())
                .roleId(AppRoleAuthenticationOptions.RoleId.provided(roleId))
                .secretId(AppRoleAuthenticationOptions.SecretId.provided(secretId))
                .build();

            RestOperations restOperations = VaultClients.createRestTemplate(vaultEndpoint, clientHttpRequestFactory);

            return new AppRoleAuthentication(appRoleAuthenticationOptions, restOperations);

        } else if (Objects.isNull(roleId) != Objects.isNull(secretId)) {

            throw new HashicorpCredentialNotSetException("Both " + HASHICORP_ROLE_ID + " and " + HASHICORP_SECRET_ID + " environment variables must be set to use the AppRole authentication method");

        } else if (authToken == null){

            throw new HashicorpCredentialNotSetException("Both " + HASHICORP_ROLE_ID + " and " + HASHICORP_SECRET_ID + " environment variables must be set to use the AppRole authentication method.  Alternatively set " + HASHICORP_TOKEN + " to authenticate using the Token method");
        }

        return new TokenAuthentication(authToken);
    }
 
Example 30
Source Project: spring-vault   Source File: AbstractVaultConfiguration.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * @return Vault endpoint coordinates for HTTP/HTTPS communication, must not be
 * {@literal null}.
 */
public abstract VaultEndpoint vaultEndpoint();