org.springframework.vault.VaultException Java Examples

The following examples show how to use org.springframework.vault.VaultException. 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: VaultCommunication.java    From vault-crd with Apache License 2.0 6 votes vote down vote up
private <T> T getVersionedSecret(String path, Optional<Integer> version, Class<T> clazz) throws SecretNotAccessibleException{
    String mountPoint = extractMountPoint(path);
    String extractedKey = extractKey(path);

    VaultVersionedKeyValueOperations versionedKV = vaultTemplate.opsForVersionedKeyValue(mountPoint);
    Versioned<T> versionedResponse;

    try {
        if (version.isPresent()) {
            versionedResponse = versionedKV.get(extractedKey, Version.from(version.get()), clazz);
        } else {
            versionedResponse = versionedKV.get(extractedKey, clazz);
        }

        if (versionedResponse != null) {
            return versionedResponse.getData();
        }

        throw new SecretNotAccessibleException(String.format("The secret %s is not available or in the wrong format.", path));

    } catch (VaultException ex) {
        throw new SecretNotAccessibleException(
                String.format("Couldn't load secret from vault path %s", path), ex);
    }
}
 
Example #2
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 #3
Source File: VaultPropertySource.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Hook method to obtain properties from Vault.
 * @param path the path, must not be empty or {@literal null}.
 * @return the resulting {@link Map} or {@literal null} if properties were not found.
 * @throws VaultException on problems retrieving properties
 */
@Nullable
protected Map<String, Object> doGetProperties(String path) throws VaultException {

	VaultResponse vaultResponse;

	if (this.keyValueDelegate.isVersioned(path)) {
		vaultResponse = this.keyValueDelegate.getSecret(path);
	}
	else {
		vaultResponse = this.source.read(path);
	}

	if (vaultResponse == null || vaultResponse.getData() == null) {
		if (logger.isDebugEnabled()) {
			logger.debug(String.format("No properties found at %s", path));
		}

		return null;
	}

	return flattenMap(vaultResponse.getData());
}
 
Example #4
Source File: VaultWrappingTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public WrappedMetadata lookup(VaultToken token) {

	Assert.notNull(token, "token VaultToken not be null");

	VaultResponse response = null;
	try {
		response = this.vaultOperations.write("sys/wrapping/lookup",
				Collections.singletonMap("token", token.getToken()));
	}
	catch (VaultException e) {

		if (e.getMessage() != null && e.getMessage().contains("does not exist")) {
			return null;
		}

		throw e;
	}

	if (response == null) {
		return null;
	}

	return getWrappedMetadata(response.getData(), token);
}
 
Example #5
Source File: TokenAuthenticationOperatorIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldFailDuringSelfLookup() {

	VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1)
			.build();

	VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken();

	AuthenticationStepsOperator operator = new AuthenticationStepsOperator(
			TokenAuthentication.createAuthenticationSteps(token, true), this.webClient);

	// first usage
	operator.getVaultToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();

	operator.getVaultToken() //
			.as(StepVerifier::create) //
			.expectError(VaultException.class) //
			.verify();
}
 
Example #6
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 #7
Source File: VaultTransitTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private static List<VaultDecryptionResult> toDecryptionResults(VaultResponse vaultResponse,
		List<Ciphertext> batchRequest) {

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

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

		VaultDecryptionResult encrypted;
		Ciphertext ciphertext = batchRequest.get(i);

		if (batchData.size() > i) {
			encrypted = getDecryptionResult(batchData.get(i), ciphertext);
		}
		else {
			encrypted = new VaultDecryptionResult(new VaultException("No result for ciphertext #" + i));
		}

		result.add(encrypted);
	}

	return result;
}
 
Example #8
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 #9
Source File: SecretLeaseContainerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldRetainLeaseAfterRenewalFailure() {

	prepareRenewal();
	when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class)))
			.thenThrow(new VaultException("Renewal failure"));

	this.secretLeaseContainer.setLeaseStrategy(LeaseStrategy.retainOnError());
	this.secretLeaseContainer.start();

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

	verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class));
	captor.getValue().run();

	verify(this.vaultOperations, times(2)).doWithSession(any(RestOperationsCallback.class));
}
 
Example #10
Source File: ReactiveVaultTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
public <V, T extends Publisher<V>> T doWithVault(Function<WebClient, ? extends T> clientCallback)
		throws VaultException, WebClientException {

	Assert.notNull(clientCallback, "Client callback must not be null");

	try {
		return (T) clientCallback.apply(this.statelessClient);
	}
	catch (HttpStatusCodeException e) {
		throw VaultResponses.buildException(e);
	}
}
 
Example #11
Source File: AppRoleAuthenticationIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldAuthenticatePullModeFailsWithoutSecretId() {

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

	AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
			.build();
	AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());

	assertThatExceptionOfType(VaultException.class).isThrownBy(authentication::login);
}
 
Example #12
Source File: VaultCommunication.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
private <T> T getRequest(String path, Class<T> clazz) throws SecretNotAccessibleException {
    try {
        VaultResponseSupport<T> response = vaultTemplate.read(path, clazz);
        if (response != null) {
            return response.getData();
        } else {
            throw new SecretNotAccessibleException(String.format("The secret %s is not available or in the wrong format.", path));
        }
    } catch (VaultException exception) {
        throw new SecretNotAccessibleException(
                String.format("Couldn't load secret from vault path %s", path), exception);
    }
}
 
Example #13
Source File: PcfAuthentication.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static String sign(String message, String privateKeyPem) {

		try {
			return doSign(message.getBytes(StandardCharsets.US_ASCII), privateKeyPem);
		}
		catch (CryptoException e) {
			throw new VaultException("Cannot sign PCF login", e);
		}
	}
 
Example #14
Source File: AppRoleAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void loginShouldFail() {

	AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided("hello")) //
			.build();

	this.mockRest.expect(requestTo("/auth/approle/login")) //
			.andRespond(withServerError());

	assertThatExceptionOfType(VaultException.class)
			.isThrownBy(() -> new AppRoleAuthentication(options, this.restTemplate).login());
}
 
Example #15
Source File: VaultSysTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
public void authMount(String path, VaultMount vaultMount) throws VaultException {

	Assert.hasText(path, "Path must not be empty");
	Assert.notNull(vaultMount, "VaultMount must not be null");

	this.vaultOperations.write(String.format("sys/auth/%s", path), vaultMount);
}
 
Example #16
Source File: VaultResponsesUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldBuildException() {

	HttpStatusCodeException cause = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Bad Request");

	VaultException vaultException = VaultResponses.buildException(cause);
	assertThat(vaultException).hasMessageContaining("Status 400 Bad Request;").hasCause(cause);
}
 
Example #17
Source File: VaultSysTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Policy getPolicy(String name) throws VaultException {

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

	return this.vaultOperations.doWithSession(restOperations -> {

		ResponseEntity<VaultResponse> response;

		try {
			response = restOperations.getForEntity("sys/policy/{name}", VaultResponse.class, name);
		}
		catch (HttpStatusCodeException e) {

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

			throw e;
		}

		String rules = (String) response.getBody().getRequiredData().get("rules");

		if (StringUtils.isEmpty(rules)) {
			return Policy.empty();
		}

		if (rules.trim().startsWith("{")) {
			return VaultResponses.unwrap(rules, Policy.class);
		}

		throw new UnsupportedOperationException("Cannot parse policy in HCL format");
	});
}
 
Example #18
Source File: VaultResponsesUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldBuildExceptionWithPath() {

	HttpStatusCodeException cause = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Bad Request");

	VaultException vaultException = VaultResponses.buildException(cause, "sys/path");
	assertThat(vaultException).hasMessageContaining("Status 400 Bad Request [sys/path];").hasCause(cause);
}
 
Example #19
Source File: VaultKeyValueAccessor.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Deserialize a {@link JsonNode} to the requested {@link Class type}.
 * @param jsonNode must not be {@literal null}.
 * @param type must not be {@literal null}.
 * @return the deserialized object.
 */
<T> T deserialize(JsonNode jsonNode, Class<T> type) {

	try {
		return this.mapper.reader().readValue(jsonNode.traverse(), type);
	}
	catch (IOException e) {
		throw new VaultException("Cannot deserialize response", e);
	}
}
 
Example #20
Source File: KubernetesAuthenticationUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void loginShouldFail() {

	KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("hello")
			.jwtSupplier(() -> "my-jwt-token").build();

	this.mockRest.expect(requestTo("/auth/kubernetes/login")) //
			.andRespond(withServerError());

	assertThatExceptionOfType(VaultException.class)
			.isThrownBy(() -> new KubernetesAuthentication(options, this.restTemplate).login());
}
 
Example #21
Source File: VaultTokenTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void revokeShouldRevokeToken() {

	final VaultTokenResponse tokenResponse = this.tokenOperations.create();
	this.tokenOperations.revoke(tokenResponse.getToken());

	try {
		lookupSelf(tokenResponse);
	}
	catch (VaultException e) {
		assertThat(e).hasMessageContaining("permission denied");
	}
}
 
Example #22
Source File: ReactiveLifecycleAwareSessionManagerIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldRenewToken() {

	VaultTokenOperations tokenOperations = prepare().getVaultOperations().opsForToken();

	VaultTokenRequest tokenRequest = VaultTokenRequest.builder() //
			.renewable().ttl(1, TimeUnit.HOURS) //
			.explicitMaxTtl(10, TimeUnit.HOURS) //
			.build();

	VaultToken token = tokenOperations.create(tokenRequest).getToken();

	LoginToken loginToken = LoginToken.renewable(token, Duration.ZERO);

	final AtomicInteger counter = new AtomicInteger();
	ReactiveLifecycleAwareSessionManager sessionManager = new ReactiveLifecycleAwareSessionManager(
			() -> Flux.fromStream(Stream.of((VaultToken) loginToken)).next(), this.taskScheduler,
			prepare().getWebClient()) {

		@Override
		public Mono<VaultToken> getVaultToken() throws VaultException {

			if (counter.getAndIncrement() > 0) {
				throw new IllegalStateException();
			}

			return super.getVaultToken();
		}
	};

	sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.expectNext(loginToken) //
			.verifyComplete();
	sessionManager.renewToken() //
			.as(StepVerifier::create) //
			.expectNext(loginToken) //
			.verifyComplete();
}
 
Example #23
Source File: VaultTokenTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void renewShouldFailForNonRenewableRenewTokens() {

	VaultTokenResponse tokenResponse = this.tokenOperations.create();

	assertThatExceptionOfType(VaultException.class)
			.isThrownBy(() -> this.tokenOperations.renew(tokenResponse.getToken()));
}
 
Example #24
Source File: VaultResponsesUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldBuildExceptionWithPathAndErrorMessage() {

	HttpStatusCodeException cause = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Bad Request",
			"{\"errors\":[\"some-error\"]}".getBytes(), StandardCharsets.US_ASCII);

	VaultException vaultException = VaultResponses.buildException(cause, "sys/path");
	assertThat(vaultException).hasMessageContaining("Status 400 Bad Request [sys/path]: some-error;")
			.hasCause(cause);
}
 
Example #25
Source File: VaultTransitTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static VaultDecryptionResult getDecryptionResult(Map<String, String> data, Ciphertext ciphertext) {

		if (StringUtils.hasText(data.get("error"))) {
			return new VaultDecryptionResult(new VaultException(data.get("error")));
		}

		if (StringUtils.hasText(data.get("plaintext"))) {

			byte[] plaintext = Base64Utils.decodeFromString(data.get("plaintext"));
			return new VaultDecryptionResult(Plaintext.of(plaintext).with(ciphertext.getContext()));
		}

		return new VaultDecryptionResult(Plaintext.empty().with(ciphertext.getContext()));
	}
 
Example #26
Source File: VaultPkiTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
public VaultCertificateResponse issueCertificate(String roleName, VaultCertificateRequest certificateRequest)
		throws VaultException {

	Assert.hasText(roleName, "Role name must not be empty");
	Assert.notNull(certificateRequest, "Certificate request must not be null");

	return requestCertificate(roleName, "{path}/issue/{roleName}", createIssueRequest(certificateRequest),
			VaultCertificateResponse.class);
}
 
Example #27
Source File: AppRoleAuthenticationIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldAuthenticateWithWrappedSecretIdFailIfUnwrappingTokenExpired() {

	String roleId = getRoleId("no-secret-id");
	String unwrappingToken = "incorrect-unwrapping-token";

	AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
			.secretId(SecretId.wrapped(VaultToken.of(unwrappingToken))).roleId(RoleId.provided(roleId))
			.unwrappingEndpoints(getUnwrappingEndpoints()).build();

	AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());

	assertThatExceptionOfType(VaultException.class).isThrownBy(authentication::login);
}
 
Example #28
Source File: SecretLeaseContainerUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldRenewLeaseAfterFailure() {

	prepareRenewal();
	AtomicInteger attempts = new AtomicInteger();
	when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))).then(invocation -> {

		int attempt = attempts.incrementAndGet();
		if (attempt == 1) {
			throw new VaultException("Renewal failure");
		}

		return Lease.of("new_lease", Duration.ofSeconds(70), true);
	});

	this.secretLeaseContainer.setLeaseStrategy(LeaseStrategy.retainOnError());
	this.secretLeaseContainer.start();

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

	boolean renewed = this.secretLeaseContainer.renew(this.requestedSecret);
	assertThat(renewed).isTrue();

	verify(this.vaultOperations, times(2)).doWithSession(any(RestOperationsCallback.class));
	verify(this.scheduledFuture).cancel(false);
	verify(this.taskScheduler, times(3)).schedule(captor.capture(), any(Trigger.class));
}
 
Example #29
Source File: VaultTransitTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void signWithInvalidKeyFormatShouldFail() {

	this.transitOperations.createKey("mykey");

	assertThatExceptionOfType(VaultException.class)
			.isThrownBy(() -> this.transitOperations.sign("mykey", Plaintext.of("hello-world")));
}
 
Example #30
Source File: AwsEc2AuthenticationUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void loginShouldFailWhileObtainingIdentityDocument() {

	this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) //
			.andRespond(withServerError());

	assertThatExceptionOfType(VaultException.class)
			.isThrownBy(() -> new AwsEc2Authentication(this.restTemplate).login());
}