org.springframework.vault.client.VaultHttpHeaders Java Examples

The following examples show how to use org.springframework.vault.client.VaultHttpHeaders. 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: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldRunTokenRenewal() {

	when(this.clientAuthentication.login())
			.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10))));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.restOperations).postForObject(eq("auth/token/renew-self"),
			eq(new HttpEntity<>(
					VaultHttpHeaders.from(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))))),
			any(Class.class));
	verify(this.clientAuthentication, times(1)).login();
	verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRenewedEvent.class));
	verify(this.listener).onAuthenticationEvent(any(AfterLoginTokenRenewedEvent.class));
}
 
Example #2
Source File: CubbyholeAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldFailUsingStoredMultipleEntries() {

	this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")).andRespond(withSuccess()
					.contentType(MediaType.APPLICATION_JSON).body("{\"data\":{\"key1\":1, \"key2\":2} }"));

	CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
			.initialToken(VaultToken.of("hello")).path("cubbyhole/token").build();

	CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);

	try {
		authentication.login();
		fail("Missing VaultException");
	}
	catch (VaultException e) {
		assertThat(e).hasMessageContaining("does not contain an unique token");
	}
}
 
Example #3
Source File: CubbyholeAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldFailUsingStoredLoginNoData() {

	this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\":{} }"));

	CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
			.initialToken(VaultToken.of("hello")).path("cubbyhole/token").build();

	CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);

	try {
		authentication.login();
		fail("Missing VaultException");
	}
	catch (VaultException e) {
		assertThat(e).hasMessageContaining("does not contain a token");
	}
}
 
Example #4
Source File: LoginTokenAdapterUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldSelfLookupToken() throws Exception {

	this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "5e6332cf-f003-6369-8cba-5bce2330f6cc"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n"
					+ "    \"creation_ttl\": 600,\n" + "    \"renewable\": false,\n" + "    \"ttl\": 456} }"));

	LoginTokenAdapter adapter = new LoginTokenAdapter(
			new TokenAuthentication("5e6332cf-f003-6369-8cba-5bce2330f6cc"), this.restTemplate);

	VaultToken login = adapter.login();

	assertThat(login).isInstanceOf(LoginToken.class);
	assertThat(login.getToken()).isEqualTo("5e6332cf-f003-6369-8cba-5bce2330f6cc");

	LoginToken loginToken = (LoginToken) login;
	assertThat(loginToken.isRenewable()).isFalse();
	assertThat(loginToken.getLeaseDuration().getSeconds()).isEqualTo(456);
}
 
Example #5
Source File: CubbyholeAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLoginUsingStoredLogin() {

	this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
					.body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }"));

	CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
			.initialToken(VaultToken.of("hello")).path("cubbyhole/token").selfLookup(false).build();

	CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);

	VaultToken login = authentication.login();

	assertThat(login).isNotInstanceOf(LoginToken.class);
	assertThat(login.getToken()).isEqualTo("058222ef-9ab9-ff39-f087-9d5bee64e46d");
}
 
Example #6
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldSelfLookupToken() {

	VaultResponse vaultResponse = new VaultResponse();
	vaultResponse.setData(Collections.singletonMap("ttl", 100));

	when(this.clientAuthentication.login()).thenReturn(VaultToken.of("login"));

	when(this.restOperations.exchange(anyString(), any(), any(), ArgumentMatchers.<Class>any()))
			.thenReturn(new ResponseEntity<>(vaultResponse, HttpStatus.OK));

	LoginToken sessionToken = (LoginToken) this.sessionManager.getSessionToken();
	assertThat(sessionToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(100));

	verify(this.restOperations).exchange(eq("auth/token/lookup-self"), eq(HttpMethod.GET),
			eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), any(Class.class));

	verify(this.listener).onAuthenticationEvent(this.captor.capture());
	AfterLoginEvent event = (AfterLoginEvent) this.captor.getValue();
	assertThat(event.getSource()).isSameAs(sessionToken);
}
 
Example #7
Source File: CubbyholeAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLoginUsingWrappedLogin() {

	String wrappedResponse = "{\"request_id\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\","
			+ "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":0,"
			+ "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }";

	this.mockRest.expect(requestTo("/sys/wrapping/unwrap")).andExpect(method(HttpMethod.POST))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse));

	CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
			.initialToken(VaultToken.of("hello")).unwrappingEndpoints(UnwrappingEndpoints.SysWrapping).wrapped()
			.build();

	CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);

	VaultToken login = authentication.login();

	assertThat(login).isInstanceOf(LoginToken.class);
	assertThat(login.getToken()).isEqualTo("5e6332cf-f003-6369-8cba-5bce2330f6cc");

	LoginToken loginToken = (LoginToken) login;
	assertThat(loginToken.isRenewable()).isFalse();
	assertThat(loginToken.getLeaseDuration()).isEqualTo(Duration.ZERO);
}
 
Example #8
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldNotThrowExceptionsOnRevokeErrors() {

	when(this.clientAuthentication.login()).thenReturn(LoginToken.of("login"));

	when(this.restOperations.postForObject(anyString(), any(), ArgumentMatchers.<Class>any()))
			.thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

	this.sessionManager.renewToken();
	this.sessionManager.destroy();

	verify(this.restOperations).postForObject(eq("auth/token/revoke-self"),
			eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), any(Class.class));
	verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class));
	verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class));
	verifyNoMoreInteractions(this.listener);
	verify(this.errorListener).onAuthenticationError(any(LoginTokenRevocationFailedEvent.class));
}
 
Example #9
Source File: VaultWrappingTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Nullable
private <T extends VaultResponseSupport<?>> T doUnwrap(VaultToken token,
		BiFunction<RestOperations, HttpEntity<?>, T> requestFunction) {

	return this.vaultOperations.doWithVault(restOperations -> {

		try {
			return requestFunction.apply(restOperations, new HttpEntity<>(VaultHttpHeaders.from(token)));
		}
		catch (HttpStatusCodeException e) {

			if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
				return null;
			}

			if (e.getStatusCode() == HttpStatus.BAD_REQUEST
					&& e.getResponseBodyAsString().contains("does not exist")) {
				return null;
			}

			throw VaultResponses.buildException(e, "sys/wrapping/unwrap");
		}
	});
}
 
Example #10
Source File: VaultBootstrapConfiguration.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {

	ClientHttpRequestFactory clientHttpRequestFactory = clientHttpRequestFactoryWrapper()
			.getClientHttpRequestFactory();

	this.restTemplateBuilder = RestTemplateBuilder.builder()
			.requestFactory(clientHttpRequestFactory)
			.endpointProvider(this.endpointProvider);

	this.customizers.forEach(this.restTemplateBuilder::customizers);
	this.requestCustomizers.forEach(this.restTemplateBuilder::requestCustomizers);

	if (StringUtils.hasText(this.vaultProperties.getNamespace())) {
		this.restTemplateBuilder.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE,
				this.vaultProperties.getNamespace());
	}

	this.externalRestOperations = new RestTemplate(clientHttpRequestFactory);
}
 
Example #11
Source File: ReactiveLifecycleAwareSessionManager.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Revoke a {@link VaultToken}.
 * @param token the token to revoke, must not be {@literal null}.
 */
protected Mono<Void> revoke(VaultToken token) {

	return this.webClient.post().uri("auth/token/revoke-self").headers(httpHeaders -> {
		httpHeaders.addAll(VaultHttpHeaders.from(token));
	}).retrieve().bodyToMono(String.class)
			.doOnSubscribe(ignore -> dispatch(new BeforeLoginTokenRevocationEvent(token)))
			.doOnNext(ignore -> dispatch(new AfterLoginTokenRevocationEvent(token)))
			.onErrorResume(WebClientResponseException.class, e -> {

				this.logger.warn(format("Could not revoke token", e));
				dispatch(new LoginTokenRevocationFailedEvent(token, e));

				return Mono.empty();
			}).onErrorResume(Exception.class, e -> {

				this.logger.warn("Could not revoke token", e);
				dispatch(new LoginTokenRevocationFailedEvent(token, e));

				return Mono.empty();
			}).then();
}
 
Example #12
Source File: SpringVaultClientConfigurationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void namespaceInterceptorAddedWhenNamespaceConfigured() throws IOException {
	VaultEnvironmentProperties properties = new VaultEnvironmentProperties();
	properties.setNamespace("test-namespace");

	SpringVaultClientConfiguration configuration = getConfiguration(properties);
	HttpRequest request = invokeInterceptors(configuration.restOperations());
	assertThat(request.getHeaders().getFirst(VaultHttpHeaders.VAULT_NAMESPACE))
			.isEqualTo("test-namespace");
}
 
Example #13
Source File: VaultTokenTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
private ResponseEntity<String> lookupSelf(final VaultTokenResponse tokenResponse) {

	return this.vaultOperations.doWithVault(restOperations -> {
		HttpHeaders headers = new HttpHeaders();
		headers.add(VaultHttpHeaders.VAULT_TOKEN, tokenResponse.getToken().getToken());

		return restOperations.exchange("auth/token/lookup-self", HttpMethod.GET, new HttpEntity<>(headers),
				String.class);
	});

}
 
Example #14
Source File: VaultNamespaceSecretIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldReportReactiveInitialized() {

	ReactiveVaultTemplate reactiveMarketing = new ReactiveVaultTemplate(this.marketingWebClientBuilder,
			() -> Mono.just(VaultToken.of(this.marketingToken)));

	reactiveMarketing.doWithSession(webClient -> {
		return webClient.get().uri("sys/init").header(VaultHttpHeaders.VAULT_NAMESPACE, "").exchange()
				.flatMap(it -> it.bodyToMono(Map.class));
	}).as(StepVerifier::create).assertNext(actual -> assertThat(actual).containsEntry("initialized", true))
			.verifyComplete();
}
 
Example #15
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldRevokeLoginTokenOnDestroy() {

	when(this.clientAuthentication.login()).thenReturn(LoginToken.of("login"));

	this.sessionManager.renewToken();
	this.sessionManager.destroy();

	verify(this.restOperations).postForObject(eq("auth/token/revoke-self"),
			eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), any(Class.class));

	verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class));
	verify(this.listener).onAuthenticationEvent(any(AfterLoginTokenRevocationEvent.class));
}
 
Example #16
Source File: VaultReactiveHealthIndicator.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Health> doHealthCheck(Builder builder) {

	return this.vaultOperations
			.doWithSession((it) -> it.get().uri("sys/health")
					.header(VaultHttpHeaders.VAULT_NAMESPACE, "").exchange())
			.flatMap((it) -> it.bodyToMono(VaultHealthImpl.class))
			.onErrorResume(WebClientResponseException.class,
					VaultReactiveHealthIndicator::deserializeError)
			.map((vaultHealthResponse) -> getHealth(builder, vaultHealthResponse));
}
 
Example #17
Source File: VaultReactiveBootstrapConfiguration.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
public VaultReactiveBootstrapConfiguration(BeanFactory beanFactory,
		VaultProperties vaultProperties,
		ObjectProvider<VaultEndpointProvider> endpointProvider,
		ObjectProvider<List<WebClientCustomizer>> webClientCustomizers) {

	this.beanFactory = beanFactory;
	this.vaultProperties = vaultProperties;

	VaultEndpointProvider provider = endpointProvider.getIfAvailable();

	if (provider == null) {
		provider = SimpleVaultEndpointProvider
				.of(VaultConfigurationUtil.createVaultEndpoint(vaultProperties));
	}

	this.webClientBuilder = WebClientBuilder.builder()
			.httpConnector(createConnector(this.vaultProperties))
			.endpointProvider(provider);
	List<WebClientCustomizer> customizers = new ArrayList<>(
			webClientCustomizers.getIfAvailable(Collections::emptyList));
	AnnotationAwareOrderComparator.sort(customizers);

	customizers.forEach(this.webClientBuilder::customizers);

	if (StringUtils.hasText(this.vaultProperties.getNamespace())) {
		this.webClientBuilder.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE,
				this.vaultProperties.getNamespace());
	}
}
 
Example #18
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 #19
Source File: SpringVaultClientConfigurationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void namespaceHeaderNotAddedWhenNamespaceNotConfigured() throws IOException {
	VaultEnvironmentProperties properties = new VaultEnvironmentProperties();

	SpringVaultClientConfiguration configuration = getConfiguration(properties);
	HttpRequest request = invokeInterceptors(configuration.restOperations());
	assertThat(request.getHeaders().getFirst(VaultHttpHeaders.VAULT_NAMESPACE))
			.isNull();
}
 
Example #20
Source File: CubbyholeAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldLoginUsingWrappedLoginWithSelfLookup() {

	String wrappedResponse = "{\"request_id\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\","
			+ "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":10,"
			+ "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }";

	this.mockRest.expect(requestTo("/sys/wrapping/unwrap")).andExpect(method(HttpMethod.POST))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse));

	this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "5e6332cf-f003-6369-8cba-5bce2330f6cc"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n"
					+ "    \"creation_ttl\": 600,\n" + "    \"renewable\": false,\n" + "    \"ttl\": 456} }"));

	CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
			.initialToken(VaultToken.of("hello")).wrapped().build();

	CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);

	VaultToken login = authentication.login();

	assertThat(login).isInstanceOf(LoginToken.class);
	assertThat(login.getToken()).isEqualTo("5e6332cf-f003-6369-8cba-5bce2330f6cc");

	LoginToken loginToken = (LoginToken) login;
	assertThat(loginToken.isRenewable()).isFalse();
	assertThat(loginToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(456));
}
 
Example #21
Source File: ReactiveLifecycleAwareSessionManager.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private Mono<TokenWrapper> doRenew(TokenWrapper tokenWrapper) {

		Mono<VaultResponse> exchange = this.webClient.post().uri("auth/token/renew-self")
				.headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(tokenWrapper.token))).retrieve()
				.bodyToMono(VaultResponse.class);

		return exchange.doOnSubscribe(ignore -> dispatch(new BeforeLoginTokenRenewedEvent(tokenWrapper.getToken())))
				.handle((response, sink) -> {

					LoginToken renewed = LoginTokenUtil.from(response.getRequiredAuth());

					if (!isExpired(renewed)) {
						sink.next(new TokenWrapper(renewed, tokenWrapper.revocable));
						dispatch(new AfterLoginTokenRenewedEvent(renewed));
						return;
					}

					if (this.logger.isDebugEnabled()) {

						Duration validTtlThreshold = getRefreshTrigger().getValidTtlThreshold(renewed);
						this.logger.info(
								String.format("Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.",
										renewed.getLeaseDuration(), validTtlThreshold));
					}
					else {
						this.logger.info("Token TTL exceeded validity TTL threshold. Dropping token.");
					}

					dropCurrentToken();
					dispatch(new LoginTokenExpiredEvent(renewed));
				});
	}
 
Example #22
Source File: ReactiveLifecycleAwareSessionManager.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static Mono<Map<String, Object>> lookupSelf(WebClient webClient, VaultToken token) {

		return webClient.get().uri("auth/token/lookup-self")
				.headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(token))).retrieve()
				.bodyToMono(VaultResponse.class).map(it -> {

					Assert.state(it.getData() != null, "Token response is null");
					return it.getRequiredData();
				}).onErrorMap(WebClientResponseException.class, e -> {
					return new VaultTokenLookupException(format("Token self-lookup", e), e);
				});
	}
 
Example #23
Source File: LifecycleAwareSessionManager.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Revoke a {@link VaultToken}.
 * @param token the token to revoke, must not be {@literal null}.
 */
protected void revoke(VaultToken token) {

	try {
		dispatch(new BeforeLoginTokenRevocationEvent(token));
		this.restOperations.postForObject("auth/token/revoke-self", new HttpEntity<>(VaultHttpHeaders.from(token)),
				Map.class);
		dispatch(new AfterLoginTokenRevocationEvent(token));
	}
	catch (RuntimeException e) {
		this.logger.warn("Cannot revoke VaultToken: %s", e);
		dispatch(new LoginTokenRevocationFailedEvent(token, e));
	}
}
 
Example #24
Source File: LifecycleAwareSessionManager.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private boolean doRenew(TokenWrapper wrapper) {

		dispatch(new BeforeLoginTokenRenewedEvent(wrapper.getToken()));
		VaultResponse vaultResponse = this.restOperations.postForObject("auth/token/renew-self",
				new HttpEntity<>(VaultHttpHeaders.from(wrapper.token)), VaultResponse.class);

		LoginToken renewed = LoginTokenUtil.from(vaultResponse.getRequiredAuth());

		if (isExpired(renewed)) {

			if (this.logger.isDebugEnabled()) {
				Duration validTtlThreshold = getRefreshTrigger().getValidTtlThreshold(renewed);
				this.logger.info(String.format("Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.",
						renewed.getLeaseDuration(), validTtlThreshold));
			}
			else {
				this.logger.info("Token TTL exceeded validity TTL threshold. Dropping token.");
			}

			setToken(Optional.empty());
			dispatch(new LoginTokenExpiredEvent(renewed));
			return false;
		}

		setToken(Optional.of(new TokenWrapper(renewed, wrapper.revocable)));
		dispatch(new AfterLoginTokenRenewedEvent(renewed));

		return true;
	}
 
Example #25
Source File: ReactiveVaultTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private ExchangeFilterFunction getSessionFilter() {

		return ofRequestProcessor(request -> this.vaultTokenSupplier.getVaultToken().map(token -> {

			return ClientRequest.from(request).headers(headers -> {
				headers.set(VaultHttpHeaders.VAULT_TOKEN, token.getToken());
			}).build();
		}));
	}
 
Example #26
Source File: CubbyholeAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldLoginUsingCubbyholeLogin() throws Exception {

	String wrappedResponse = "{\"request_id\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\","
			+ "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":0,"
			+ "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }";

	this.mockRest.expect(requestTo("/cubbyhole/response")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
					"{\"data\":{\"response\":" + this.OBJECT_MAPPER.writeValueAsString(wrappedResponse) + "} }"));

	CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
			.initialToken(VaultToken.of("hello")).unwrappingEndpoints(UnwrappingEndpoints.Cubbyhole).wrapped()
			.build();

	CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);

	VaultToken login = authentication.login();

	assertThat(login).isInstanceOf(LoginToken.class);
	assertThat(login.getToken()).isEqualTo("5e6332cf-f003-6369-8cba-5bce2330f6cc");

	LoginToken loginToken = (LoginToken) login;
	assertThat(loginToken.isRenewable()).isFalse();
	assertThat(loginToken.getLeaseDuration()).isEqualTo(Duration.ZERO);
}
 
Example #27
Source File: CubbyholeAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldRetrieveRenewabilityUsingStoredLogin() {

	this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
					.body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }"));

	this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET))
			.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "058222ef-9ab9-ff39-f087-9d5bee64e46d"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n"
					+ "    \"creation_ttl\": 600,\n" + "    \"renewable\": true,\n" + "    \"ttl\": 456} }"));

	CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
			.initialToken(VaultToken.of("hello")).path("cubbyhole/token").build();

	CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);

	VaultToken login = authentication.login();

	assertThat(login).isInstanceOf(LoginToken.class);
	assertThat(login.getToken()).isEqualTo("058222ef-9ab9-ff39-f087-9d5bee64e46d");

	LoginToken loginToken = (LoginToken) login;
	assertThat(loginToken.isRenewable()).isTrue();
	assertThat(loginToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(456));
}
 
Example #28
Source File: ClientCertificateNamespaceIntegrationTests.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@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 #29
Source File: ClientCertificateNamespaceIntegrationTests.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@Test
void shouldAuthenticateReactiveWithNamespace() {

	ClientHttpConnector connector = ClientHttpConnectorFactory.create(new ClientOptions(),
			ClientCertificateAuthenticationIntegrationTestBase.prepareCertAuthenticationMethod());

	WebClientBuilder builder = WebClientBuilder.builder().endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
			.httpConnector(connector).defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev");

	WebClient forAuthentication = builder.build();

	AuthenticationSteps steps = ClientCertificateAuthentication.createAuthenticationSteps();

	AuthenticationStepsOperator operator = new AuthenticationStepsOperator(steps, forAuthentication);

	ReactiveVaultTemplate dev = new ReactiveVaultTemplate(builder, operator);

	dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev")).as(StepVerifier::create)
			.verifyComplete();

	dev.read("dev-secrets/my-secret").as(StepVerifier::create).consumeNextWith(actual -> {

		assertThat(actual.getRequiredData()).containsEntry("key", "dev");
	}).verifyComplete();
}
 
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();
}