org.springframework.vault.core.VaultTemplate Java Examples
The following examples show how to use
org.springframework.vault.core.VaultTemplate.
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: HashicorpVaultAliasService.java From knox with Apache License 2.0 | 6 votes |
@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 #2
Source File: VaultRule.java From spring-cloud-vault with Apache License 2.0 | 6 votes |
/** * 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 #3
Source File: VaultInitializer.java From spring-vault with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: SpringVaultEnvironmentRepositoryFactory.java From spring-cloud-config with Apache License 2.0 | 6 votes |
private VaultKeyValueOperations buildVaultAccessStrategy( VaultEnvironmentProperties vaultProperties, VaultTemplate vaultTemplate) { String backend = vaultProperties.getBackend(); int version = vaultProperties.getKvVersion(); switch (version) { case 1: return vaultTemplate.opsForKeyValue(backend, VaultKeyValueOperationsSupport.KeyValueBackend.KV_1); case 2: return vaultTemplate.opsForKeyValue(backend, VaultKeyValueOperationsSupport.KeyValueBackend.KV_2); default: throw new IllegalArgumentException( "No support for given Vault k/v backend version " + version); } }
Example #5
Source File: VaultPropertySourceUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void shouldResolvePlaceholderForNonRenewablePropertySource() { System.setProperty("my_property", "non-renewable"); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(Config.class); ctx.register(NonRenewableConfig.class); ctx.refresh(); VaultTemplate templateMock = ctx.getBean(VaultTemplate.class); verify(templateMock).afterPropertiesSet(); verify(templateMock).read("sys/internal/ui/mounts/foo/non-renewable"); verify(templateMock).read("foo/non-renewable"); verifyNoMoreInteractions(templateMock); }
Example #6
Source File: SpringVaultEnvironmentRepositoryFactoryTests.java From spring-cloud-config with Apache License 2.0 | 5 votes |
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 #7
Source File: VaultPropertySourceUnitTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void shouldNotEnablePropertySource() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(Config.class); ctx.register(DemoProfile.class); ctx.register(DevProfile.class); ctx.refresh(); VaultTemplate templateMock = ctx.getBean(VaultTemplate.class); verify(templateMock).afterPropertiesSet(); verifyNoMoreInteractions(templateMock); }
Example #8
Source File: SpringVaultEnvironmentRepositoryFactory.java From spring-cloud-config with Apache License 2.0 | 5 votes |
@Override public SpringVaultEnvironmentRepository build( VaultEnvironmentProperties vaultProperties) { VaultTemplate vaultTemplate = clientConfiguration.vaultTemplate(); VaultKeyValueOperations accessStrategy = buildVaultAccessStrategy(vaultProperties, vaultTemplate); return new SpringVaultEnvironmentRepository(this.request, this.watch, vaultProperties, accessStrategy); }
Example #9
Source File: ClientCertificateNamespaceIntegrationTests.java From spring-vault with Apache License 2.0 | 5 votes |
private void mountKv(VaultTemplate template, String path) { VaultSysOperations vaultSysOperations = template.opsForSys(); Map<String, VaultMount> mounts = vaultSysOperations.getMounts(); if (!mounts.containsKey(path + "/")) { vaultSysOperations.mount(path, VaultMount.builder().type("kv").options(Collections.singletonMap("version", "1")).build()); } }
Example #10
Source File: VaultBootstrapConfiguration.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
/** * Creates a {@link VaultTemplate}. * @return the {@link VaultTemplate} bean. * @see VaultBootstrapConfiguration#clientHttpRequestFactoryWrapper() */ @Bean @ConditionalOnMissingBean(VaultOperations.class) public VaultTemplate vaultTemplate() { VaultProperties.AuthenticationMethod authentication = this.vaultProperties .getAuthentication(); if (authentication == VaultProperties.AuthenticationMethod.NONE) { return new VaultTemplate(this.restTemplateBuilder); } return new VaultTemplate(this.restTemplateBuilder, this.applicationContext.getBean(SessionManager.class)); }
Example #11
Source File: VaultBootstrapConfigurationTests.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
@Test public void shouldConfigureWithoutAuthentication() { this.contextRunner.withPropertyValues("spring.cloud.vault.kv.enabled=false", "spring.cloud.vault.authentication=NONE").run(context -> { assertThat(context).doesNotHaveBean(SessionManager.class); assertThat(context).doesNotHaveBean(ClientAuthentication.class); assertThat(context).hasSingleBean(VaultTemplate.class); }); }
Example #12
Source File: VaultNamespaceTests.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
@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 #13
Source File: VaultNamespaceTests.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
private void mountKv(VaultTemplate template, String path) { VaultSysOperations vaultSysOperations = template.opsForSys(); Map<String, VaultMount> mounts = vaultSysOperations.getMounts(); if (!mounts.containsKey(path + "/")) { vaultSysOperations.mount(path, VaultMount.builder().type("kv") .options(Collections.singletonMap("version", "1")).build()); } }
Example #14
Source File: VaultNamespaceTests.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
@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 #15
Source File: VaultConfigTests.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
@Test public void shouldContainVaultBeans() { // Beans are registered in parent (bootstrap) context. ApplicationContext parent = this.applicationContext.getParent(); assertThat(parent.getBeanNamesForType(VaultTemplate.class)).isNotEmpty(); assertThat(parent.getBeanNamesForType(LeasingVaultPropertySourceLocator.class)) .isNotEmpty(); }
Example #16
Source File: VaultVersionedKvBackendConfigTests.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
@Test public void shouldContainVaultBeans() { // Beans are registered in parent (bootstrap) context. ApplicationContext parent = this.applicationContext.getParent(); assertThat(parent.getBeanNamesForType(VaultTemplate.class)).isNotEmpty(); assertThat(parent.getBeanNamesForType(LeasingVaultPropertySourceLocator.class)) .isNotEmpty(); }
Example #17
Source File: VaultConfigDisabledTests.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
@Test public void shouldNotContainVaultBeans() { // Beans are registered in parent (bootstrap) context. ApplicationContext parent = this.applicationContext.getParent(); assertThat(parent.getBeanNamesForType(VaultTemplate.class)).isEmpty(); assertThat(parent.getBeanNamesForType(VaultPropertySourceLocator.class)) .isEmpty(); }
Example #18
Source File: CentralRecipeContext.java From cloudbreak with Apache License 2.0 | 4 votes |
@Bean public VaultTemplate vaultTemplate() { return Mockito.mock(VaultTemplate.class); }
Example #19
Source File: VaultKvV1Engine.java From cloudbreak with Apache License 2.0 | 4 votes |
@Inject public VaultKvV1Engine(VaultTemplate template) { this.template = template; }
Example #20
Source File: VaultKvV2Engine.java From cloudbreak with Apache License 2.0 | 4 votes |
public VaultKvV2Engine(VaultTemplate template) { this.template = template; }
Example #21
Source File: VaultCommunication.java From vault-crd with Apache License 2.0 | 4 votes |
public VaultCommunication(VaultTemplate vaultTemplate) { this.vaultTemplate = vaultTemplate; }
Example #22
Source File: ClientCertificateNamespaceIntegrationTests.java From spring-vault with Apache License 2.0 | 4 votes |
@Test void shouldAuthenticateWithNamespace() { ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), ClientCertificateAuthenticationIntegrationTestBase.prepareCertAuthenticationMethod()); RestTemplateBuilder builder = RestTemplateBuilder.builder() .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).requestFactory(clientHttpRequestFactory) .defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev"); RestTemplate forAuthentication = builder.build(); ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(forAuthentication); VaultTemplate dev = new VaultTemplate(builder, new SimpleSessionManager(authentication)); dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev")); assertThat(dev.read("dev-secrets/my-secret").getRequiredData()).containsEntry("key", "dev"); }
Example #23
Source File: ClientCertificateNamespaceIntegrationTests.java From spring-vault with Apache License 2.0 | 4 votes |
@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 #24
Source File: VaultApp.java From spring-vault with Apache License 2.0 | 4 votes |
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 #25
Source File: VaultPropertySourceUnitTests.java From spring-vault with Apache License 2.0 | 4 votes |
@Test void shouldEnablePropertySourceByProfile() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().addActiveProfile("demo"); ctx.register(Config.class); ctx.register(DemoProfile.class); ctx.register(DevProfile.class); ctx.refresh(); VaultTemplate templateMock = ctx.getBean(VaultTemplate.class); verify(templateMock).afterPropertiesSet(); verify(templateMock).read("foo"); verify(templateMock, never()).read("bar"); }
Example #26
Source File: VaultPropertySourceUnitTests.java From spring-vault with Apache License 2.0 | 4 votes |
@Bean VaultTemplate vaultTemplate() { return Mockito.mock(VaultTemplate.class); }
Example #27
Source File: HashicorpKeyVaultServiceFactory.java From tessera with Apache License 2.0 | 4 votes |
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 #28
Source File: AbstractVaultConfiguration.java From spring-vault with Apache License 2.0 | 3 votes |
/** * Create a {@link VaultTemplate}. * @return the {@link VaultTemplate}. * @see #vaultEndpointProvider() * @see #clientHttpRequestFactoryWrapper() * @see #sessionManager() */ @Bean public VaultTemplate vaultTemplate() { return new VaultTemplate( restTemplateBuilder(vaultEndpointProvider(), getClientFactoryWrapper().getClientHttpRequestFactory()), getBeanFactory().getBean("sessionManager", SessionManager.class)); }