org.springframework.vault.support.VaultResponse Java Examples

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

	mockToken(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));

	when(this.responseSpec.bodyToMono(VaultResponse.class))
			.thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10)))));

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

	this.sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.taskScheduler, times(2)).schedule(any(Runnable.class), any(Trigger.class));
}
 
Example #2
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 #3
Source File: CubbyholeAuthentication.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private static VaultToken getToken(CubbyholeAuthenticationOptions options, VaultResponse response, String url) {

		if (options.isWrappedToken()) {

			VaultResponse responseToUse = options.getUnwrappingEndpoints().unwrap(response);

			Assert.state(responseToUse.getAuth() != null, "Auth field must not be null");

			return LoginTokenUtil.from(responseToUse.getAuth());
		}

		Map<String, Object> data = response.getData();
		if (data == null || data.isEmpty()) {
			throw new VaultLoginException(
					String.format("Cannot retrieve Token from Cubbyhole: Response at %s does not contain a token",
							options.getPath()));
		}

		if (data.size() == 1) {
			String token = (String) data.get(data.keySet().iterator().next());
			return VaultToken.of(token);
		}

		throw new VaultLoginException(String
				.format("Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token", url));
	}
 
Example #4
Source File: CubbyholeAuthentication.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Override
public VaultToken login() throws VaultException {

	String url = getRequestPath(this.options);
	VaultResponse data = lookupToken(url);

	VaultToken tokenToUse = getToken(this.options, data, url);

	if (shouldEnhanceTokenWithSelfLookup(tokenToUse)) {

		LoginTokenAdapter adapter = new LoginTokenAdapter(new TokenAuthentication(tokenToUse), this.restOperations);
		tokenToUse = adapter.login();
	}

	logger.debug("Login successful using Cubbyhole authentication");
	return tokenToUse;
}
 
Example #5
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldContinueIfSelfLookupFails() {

	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()))
			.thenThrow(new HttpClientErrorException(HttpStatus.FORBIDDEN));

	VaultToken sessionToken = this.sessionManager.getSessionToken();
	assertThat(sessionToken).isExactlyInstanceOf(VaultToken.class);
	verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class));
	verify(this.errorListener).onAuthenticationError(any());
}
 
Example #6
Source File: CubbyholeAuthentication.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link AuthenticationSteps} for cubbyhole authentication given
 * {@link CubbyholeAuthenticationOptions}.
 * @param options must not be {@literal null}.
 * @return {@link AuthenticationSteps} for cubbyhole authentication.
 * @since 2.0
 */
public static AuthenticationSteps createAuthenticationSteps(CubbyholeAuthenticationOptions options) {

	Assert.notNull(options, "CubbyholeAuthenticationOptions must not be null");

	String url = getRequestPath(options);

	HttpMethod unwrapMethod = getRequestMethod(options);
	HttpEntity<Object> requestEntity = getRequestEntity(options);

	HttpRequest<VaultResponse> initialRequest = method(unwrapMethod, url) //
			.with(requestEntity) //
			.as(VaultResponse.class);

	return AuthenticationSteps.fromHttpRequest(initialRequest) //
			.login(it -> getToken(options, it, url));
}
 
Example #7
Source File: AzureMsiAuthentication.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private VaultToken createTokenUsingAzureMsiCompute() {

		Map<String, String> login = getAzureLogin(this.options.getRole(), getVmEnvironment(), getAccessToken());

		try {

			VaultResponse response = this.vaultRestOperations
					.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);

			Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");

			if (logger.isDebugEnabled()) {
				logger.debug("Login successful using Azure authentication");
			}

			return LoginTokenUtil.from(response.getAuth());
		}
		catch (RestClientException e) {
			throw VaultLoginException.create("Azure", e);
		}
	}
 
Example #8
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 #9
Source File: AppIdAuthentication.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private VaultToken createTokenUsingAppId() {

		Map<String, String> login = getAppIdLogin(this.options.getAppId(),
				this.options.getUserIdMechanism().createUserId());

		try {
			VaultResponse response = this.restOperations
					.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);

			Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");

			logger.debug("Login successful using AppId authentication");

			return LoginTokenUtil.from(response.getAuth());
		}
		catch (RestClientException e) {
			throw VaultLoginException.create("app-id", e);
		}
	}
 
Example #10
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReLoginIfRenewalFails() {

	when(this.clientAuthentication.login()).thenReturn(
			LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)),
			LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenThrow(new ResourceAccessException("Connection refused"));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	assertThat(this.sessionManager.getSessionToken())
			.isEqualTo(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));

	verify(this.clientAuthentication, times(2)).login();
}
 
Example #11
Source File: CubbyholeAuthenticationIntegrationTestBase.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
Map<String, String> prepareWrappedToken() {

		ResponseEntity<VaultResponse> response = prepare().getVaultOperations().doWithSession(restOperations -> {

			HttpHeaders headers = new HttpHeaders();
			headers.add("X-Vault-Wrap-TTL", "10m");

			return restOperations.exchange("auth/token/create", HttpMethod.POST, new HttpEntity<>(headers),
					VaultResponse.class);
		});

		Map<String, String> wrapInfo = response.getBody().getWrapInfo();

		// Response Wrapping requires Vault 0.6.0+
		assertThat(wrapInfo).isNotNull();
		return wrapInfo;
	}
 
Example #12
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.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));

	mockToken(VaultToken.of("login"));

	when(this.responseSpec.bodyToMono((Class) any())).thenReturn(Mono.just(vaultResponse));

	this.sessionManager.getSessionToken().as(StepVerifier::create).assertNext(it -> {

		LoginToken sessionToken = (LoginToken) it;
		assertThat(sessionToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(100));
	}).verifyComplete();

	verify(this.webClient.get()).uri("auth/token/lookup-self");
	verify(this.listener).onAuthenticationEvent(this.captor.capture());
	AfterLoginEvent event = (AfterLoginEvent) this.captor.getValue();
	assertThat(event.getSource()).isInstanceOf(LoginToken.class);
}
 
Example #13
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldNotScheduleRenewalIfRenewalTtlExceedsThreshold() {

	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(2))));

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

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

	runnableCaptor.getValue().run();

	verify(this.taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class));
}
 
Example #14
Source File: AuthenticationStepsOperatorUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void justLoginShouldFail() {

	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/cert/login");
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.BAD_REQUEST);
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	WebClient webClient = WebClient.builder().clientConnector(connector).build();

	AuthenticationSteps steps = AuthenticationSteps
			.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));

	login(steps, webClient).as(StepVerifier::create) //
			.expectError() //
			.verify();
}
 
Example #15
Source File: VaultConfigTemplate.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
private Secrets createSecrets(VaultResponse vaultResponse, Map<String, Object> data) {

		Secrets secrets = new Secrets();

		secrets.setData(data);

		secrets.setAuth(vaultResponse.getAuth());
		secrets.setLeaseDuration(vaultResponse.getLeaseDuration());
		secrets.setMetadata(vaultResponse.getMetadata());
		secrets.setLeaseId(vaultResponse.getLeaseId());
		secrets.setRenewable(vaultResponse.isRenewable());
		secrets.setRequestId(vaultResponse.getRequestId());
		secrets.setWarnings(vaultResponse.getWarnings());
		secrets.setWrapInfo(vaultResponse.getWrapInfo());

		return secrets;
	}
 
Example #16
Source File: VaultKeyValueAccessor.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Write the {@code body} to the given Vault {@code path}.
 * @param path must not be {@literal null} or empty.
 * @param body
 * @return the response of this write action.
 */
@Nullable
VaultResponse doWrite(String path, Object body) {

	Assert.hasText(path, "Path must not be empty");

	try {

		return this.vaultOperations.doWithSession((restOperations) -> {
			return restOperations.exchange(path, HttpMethod.POST, new HttpEntity<>(body), VaultResponse.class)
					.getBody();
		});
	}
	catch (HttpStatusCodeException e) {
		throw VaultResponses.buildException(e, path);
	}
}
 
Example #17
Source File: VaultKeyValue1Template.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public VaultResponse get(String path) {

	Assert.hasText(path, "Path must not be empty");

	return doRead(path, Map.class, (response, data) -> {

		VaultResponse vaultResponse = new VaultResponse();
		vaultResponse.setRenewable(response.isRenewable());
		vaultResponse.setAuth(response.getAuth());
		vaultResponse.setLeaseDuration(response.getLeaseDuration());
		vaultResponse.setLeaseId(response.getLeaseId());
		vaultResponse.setMetadata(response.getMetadata());
		vaultResponse.setRequestId(response.getRequestId());
		vaultResponse.setWarnings(response.getWarnings());
		vaultResponse.setWrapInfo(response.getWrapInfo());
		vaultResponse.setData(data);

		return vaultResponse;
	});
}
 
Example #18
Source File: VaultSysTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Override
public void createOrUpdatePolicy(String name, Policy policy) throws VaultException {

	Assert.hasText(name, "Name must not be null or empty");
	Assert.notNull(policy, "Policy must not be null");

	String rules;

	try {
		rules = OBJECT_MAPPER.writeValueAsString(policy);
	}
	catch (IOException e) {
		throw new VaultException("Cannot serialize policy to JSON", e);
	}

	this.vaultOperations.doWithSession(restOperations -> {

		restOperations.exchange("sys/policy/{name}", HttpMethod.PUT,
				new HttpEntity<>(Collections.singletonMap("rules", rules)), VaultResponse.class, name);

		return null;
	});
}
 
Example #19
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRetainTokenAfterRenewalFailure() {

	when(this.tokenSupplier.getVaultToken()).thenReturn(
			Mono.just(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))),
			Mono.just(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))));
	when(this.responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.error(new RuntimeException("foo")));
	this.sessionManager.setLeaseStrategy(LeaseStrategy.retainOnError());

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	this.sessionManager.getSessionToken().as(StepVerifier::create)
			.expectNext(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))).verifyComplete();

	verify(this.tokenSupplier).getVaultToken();
}
 
Example #20
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRevokeLoginTokenOnDestroy() {

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

	mockToken(LoginToken.of("login"));
	when(this.responseSpec.bodyToMono(String.class)).thenReturn(Mono.just("OK"));

	this.sessionManager.getVaultToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();

	this.sessionManager.destroy();

	verify(this.webClient.post()).uri("auth/token/revoke-self");
	verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class));
	verify(this.listener).onAuthenticationEvent(any(AfterLoginTokenRevocationEvent.class));
}
 
Example #21
Source File: AppRoleAuthenticationStepsIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void authenticationStepsShouldAuthenticatePushModeWithProvidedSecretId() {

	String roleId = getRoleId("with-secret-id");
	String secretId = "hello_world_two";

	VaultResponse customSecretIdResponse = getVaultOperations().write(
			"auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId));

	AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
			.secretId(SecretId.provided(secretId)).build();

	AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
			AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());

	assertThat(executor.login()).isNotNull();

	getVaultOperations().write("auth/approle/role/with-secret-id/secret-id-accessor/destroy",
			customSecretIdResponse.getRequiredData());
}
 
Example #22
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldContinueIfSelfLookupFails() {

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

	mockToken(VaultToken.of("login"));

	when(this.responseSpec.bodyToMono((Class) any())).thenReturn(
			Mono.error(new WebClientResponseException("forbidden", 403, "Forbidden", null, null, null)));

	this.sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.assertNext(it -> {
				assertThat(it).isExactlyInstanceOf(VaultToken.class);
			}).verifyComplete();
	verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class));
	verify(this.errorListener).onAuthenticationError(any());
}
 
Example #23
Source File: AuthenticationStepsExecutorUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void zipWithShouldRequestTwoItems() {

	this.mockRest.expect(requestTo("/auth/login/left")).andExpect(method(HttpMethod.POST)).andRespond(
			withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"request_id\": \"left\"}"));

	this.mockRest.expect(requestTo("/auth/login/right")).andExpect(method(HttpMethod.POST)).andRespond(
			withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"request_id\": \"right\"}"));

	Node<VaultResponse> left = AuthenticationSteps
			.fromHttpRequest(post("/auth/login/left").as(VaultResponse.class));

	Node<VaultResponse> right = AuthenticationSteps
			.fromHttpRequest(post("/auth/login/right").as(VaultResponse.class));

	AuthenticationSteps steps = left.zipWith(right)
			.login(it -> VaultToken.of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId()));

	assertThat(login(steps)).isEqualTo(VaultToken.of("left-right"));
}
 
Example #24
Source File: AuthenticationStepsExecutor.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public VaultToken login() throws VaultException {

	Iterable<Node<?>> steps = this.chain.steps;

	Object state = evaluate(steps);

	if (state instanceof VaultToken) {
		return (VaultToken) state;
	}

	if (state instanceof VaultResponse) {

		VaultResponse response = (VaultResponse) state;
		Assert.state(response.getAuth() != null, "Auth field must not be null");
		return LoginTokenUtil.from(response.getAuth());
	}

	throw new IllegalStateException(
			String.format("Cannot retrieve VaultToken from authentication chain. Got instead %s", state));
}
 
Example #25
Source File: SecretLeaseContainerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldAcceptSecretsWithoutLease() {

	VaultResponse secrets = new VaultResponse();
	secrets.setData(Collections.singletonMap("key", (Object) "value"));

	when(this.vaultOperations.read(this.requestedSecret.getPath())).thenReturn(secrets);

	this.secretLeaseContainer.addRequestedSecret(this.requestedSecret);
	this.secretLeaseContainer.start();

	verifyZeroInteractions(this.taskScheduler);
	verify(this.leaseListenerAdapter).onLeaseEvent(this.captor.capture());

	SecretLeaseCreatedEvent leaseCreatedEvent = (SecretLeaseCreatedEvent) this.captor.getValue();

	assertThat(leaseCreatedEvent.getSource()).isEqualTo(this.requestedSecret);
	assertThat(leaseCreatedEvent.getLease()).isNotNull();
	assertThat(leaseCreatedEvent.getSecrets()).containsKey("key");
}
 
Example #26
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReLoginIfRenewFails() {

	when(this.tokenSupplier.getVaultToken()).thenReturn(
			Mono.just(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))),
			Mono.just(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))));
	when(this.responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.error(new RuntimeException("foo")));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	this.sessionManager.getSessionToken().as(StepVerifier::create)
			.expectNext(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))).verifyComplete();

	verify(this.tokenSupplier, times(2)).getVaultToken();
}
 
Example #27
Source File: VaultConfigCubbyholeAuthenticationTests.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {

	VaultRule vaultRule = new VaultRule();
	vaultRule.before();

	assumeTrue(vaultRule.prepare().getVersion()
			.isGreaterThanOrEqualTo(Version.parse("0.6.1")));

	VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();

	vaultOperations.write(
			"secret/" + VaultConfigCubbyholeAuthenticationTests.class.getSimpleName(),
			Collections.singletonMap("vault.value",
					VaultConfigCubbyholeAuthenticationTests.class.getSimpleName()));

	VaultResponse vaultResponse = vaultOperations.doWithSession(restOperations -> {

		HttpHeaders headers = new HttpHeaders();
		headers.add("X-Vault-Wrap-TTL", "1h");

		return restOperations.postForObject("/auth/token/create",
				new HttpEntity<>(headers), VaultResponse.class);
	});

	String initialToken = vaultResponse.getWrapInfo().get("token");
	System.setProperty("spring.cloud.vault.token", initialToken);
}
 
Example #28
Source File: VaultTransitTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static List<VaultEncryptionResult> toEncryptionResults(VaultResponse vaultResponse,
		List<Plaintext> batchRequest) {

	List<VaultEncryptionResult> result = new ArrayList<>(batchRequest.size());
	List<Map<String, String>> batchData = getBatchData(vaultResponse);

	for (int i = 0; i < batchRequest.size(); i++) {

		VaultEncryptionResult encrypted;
		Plaintext plaintext = batchRequest.get(i);
		if (batchData.size() > i) {

			Map<String, String> data = batchData.get(i);
			if (StringUtils.hasText(data.get("error"))) {
				encrypted = new VaultEncryptionResult(new VaultException(data.get("error")));
			}
			else {
				encrypted = new VaultEncryptionResult(toCiphertext(data.get("ciphertext"), plaintext.getContext()));
			}
		}
		else {
			encrypted = new VaultEncryptionResult(new VaultException("No result for plaintext #" + i));
		}

		result.add(encrypted);
	}

	return result;
}
 
Example #29
Source File: VaultKeyValueMetadataTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldDeleteMetadata() {

	this.kvOperations.delete(SECRET_NAME);
	VaultMetadataResponse metadataResponse = this.vaultKeyValueMetadataOperations.get(SECRET_NAME);
	Versioned.Metadata version1 = metadataResponse.getVersions().get(0);
	assertThat(version1.getDeletedAt()).isBefore(Instant.now());

	this.vaultKeyValueMetadataOperations.delete(SECRET_NAME);

	VaultResponse response = this.kvOperations.get(SECRET_NAME);
	assertThat(response).isNull();
}
 
Example #30
Source File: VaultWrappingTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public VaultResponse read(VaultToken token) {

	return doUnwrap(token, (restOperations, entity) -> {
		return restOperations.exchange("sys/wrapping/unwrap", HttpMethod.POST, entity, VaultResponse.class)
				.getBody();
	});
}