org.springframework.vault.support.VaultResponseSupport Java Examples

The following examples show how to use org.springframework.vault.support.VaultResponseSupport. 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: VaultTokenTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private <T extends VaultResponseSupport<?>> T writeAndReturn(String path, @Nullable Object body,
		Class<T> responseType) {

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

	T response = this.vaultOperations.doWithSession(restOperations -> {
		try {
			ResponseEntity<T> exchange = restOperations.exchange(path, HttpMethod.POST,
					body == null ? HttpEntity.EMPTY : new HttpEntity<>(body), responseType);

			return exchange.getBody();
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e, path);
		}
	});

	Assert.state(response != null, "Response must not be null");

	return response;
}
 
Example #2
Source File: VaultTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public <T> VaultResponseSupport<T> read(String path, Class<T> responseType) {

	ParameterizedTypeReference<VaultResponseSupport<T>> ref = VaultResponses.getTypeReference(responseType);

	return doWithSession(restOperations -> {

		try {
			ResponseEntity<VaultResponseSupport<T>> exchange = restOperations.exchange(path, HttpMethod.GET, null,
					ref);

			return exchange.getBody();
		}
		catch (HttpStatusCodeException e) {

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

			throw VaultResponses.buildException(e, path);
		}
	});
}
 
Example #3
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 #4
Source File: VaultTemplateGenericIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void readObjectShouldReadDomainClass() {

	Map<String, String> data = new HashMap<String, String>();
	data.put("firstname", "Walter");
	data.put("password", "Secret");

	this.vaultOperations.write("secret/mykey", data);

	VaultResponseSupport<Person> read = this.vaultOperations.read("secret/mykey", Person.class);
	assertThat(read).isNotNull();

	Person person = read.getRequiredData();
	assertThat(person.getFirstname()).isEqualTo("Walter");
	assertThat(person.getPassword()).isEqualTo("Secret");
}
 
Example #5
Source File: SecretLeaseContainer.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve secrets from {@link VaultOperations}.
 * @param requestedSecret the {@link RequestedSecret} providing the secret
 * {@code path}.
 * @return the response.
 */
@Nullable
protected VaultResponseSupport<Map<String, Object>> doGetSecrets(RequestedSecret requestedSecret) {

	try {
		VaultResponseSupport<Map<String, Object>> secrets;

		if (this.keyValueDelegate.isVersioned(requestedSecret.getPath())) {
			secrets = this.keyValueDelegate.getSecret(requestedSecret.getPath());
		}
		else {
			secrets = this.operations.read(requestedSecret.getPath());
		}

		if (secrets == null) {
			onSecretsNotFound(requestedSecret);
		}

		return secrets;
	}
	catch (RuntimeException e) {

		onError(requestedSecret, Lease.none(), e);
		return null;
	}
}
 
Example #6
Source File: VaultResponses.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link ParameterizedTypeReference} for {@code responseType}.
 * @param responseType must not be {@literal null}.
 * @return the {@link ParameterizedTypeReference} for {@code responseType}.
 */
public static <T> ParameterizedTypeReference<VaultResponseSupport<T>> getTypeReference(
		final Class<T> responseType) {

	Assert.notNull(responseType, "Response type must not be null");

	final Type supportType = new ParameterizedType() {

		@Override
		public Type[] getActualTypeArguments() {
			return new Type[] { responseType };
		}

		@Override
		public Type getRawType() {
			return VaultResponseSupport.class;
		}

		@Override
		public Type getOwnerType() {
			return VaultResponseSupport.class;
		}
	};

	return new ParameterizedTypeReference<VaultResponseSupport<T>>() {
		@Override
		public Type getType() {
			return supportType;
		}
	};
}
 
Example #7
Source File: VaultTransitTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public VaultTransitKey getKey(String keyName) {

	Assert.hasText(keyName, "Key name must not be empty");

	VaultResponseSupport<VaultTransitKeyImpl> result = this.vaultOperations
			.read(String.format("%s/keys/%s", this.path, keyName), VaultTransitKeyImpl.class);

	if (result != null) {
		return result.getRequiredData();
	}

	return null;
}
 
Example #8
Source File: VaultTransitTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public RawTransitKey exportKey(String keyName, TransitKeyType type) {

	Assert.hasText(keyName, "Key name must not be empty");
	Assert.notNull(type, "Key type must not be null");

	VaultResponseSupport<RawTransitKeyImpl> result = this.vaultOperations
			.read(String.format("%s/export/%s/%s", this.path, type.getValue(), keyName), RawTransitKeyImpl.class);

	return result != null ? result.getRequiredData() : null;
}
 
Example #9
Source File: SecretLeaseContainer.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private void start(RequestedSecret requestedSecret, LeaseRenewalScheduler renewalScheduler) {

		VaultResponseSupport<Map<String, Object>> secrets = doGetSecrets(requestedSecret);

		if (secrets != null) {

			Lease lease;

			if (StringUtils.hasText(secrets.getLeaseId())) {
				lease = Lease.of(secrets.getLeaseId(), Duration.ofSeconds(secrets.getLeaseDuration()),
						secrets.isRenewable());
			}
			else if (isRotatingGenericSecret(requestedSecret, secrets)) {
				lease = Lease.fromTimeToLive(Duration.ofSeconds(secrets.getLeaseDuration()));
			}
			else {
				lease = Lease.none();
			}

			if (renewalScheduler.isLeaseRenewable(lease, requestedSecret)) {
				scheduleLeaseRenewal(requestedSecret, lease, renewalScheduler);
			}
			else if (renewalScheduler.isLeaseRotateOnly(lease, requestedSecret)) {
				scheduleLeaseRotation(requestedSecret, lease, renewalScheduler);
			}

			onSecretsObtained(requestedSecret, lease, secrets.getRequiredData());
		}
	}
 
Example #10
Source File: VaultWrappingTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public <T> VaultResponseSupport<T> read(VaultToken token, Class<T> responseType) {

	ParameterizedTypeReference<VaultResponseSupport<T>> ref = VaultResponses.getTypeReference(responseType);

	return doUnwrap(token, (restOperations, entity) -> {
		return restOperations.exchange("sys/wrapping/unwrap", HttpMethod.POST, entity, ref).getBody();
	});
}
 
Example #11
Source File: VaultKeyValue1Template.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
@SuppressWarnings("unchecked")
public <T> VaultResponseSupport<T> get(String path, Class<T> responseType) {

	Assert.hasText(path, "Path must not be empty");
	Assert.notNull(responseType, "Response type must not be null");

	return doRead(path, responseType, (response, data) -> {

		VaultResponseSupport result = response;
		result.setData(data);
		return result;
	});
}
 
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: VaultKeyValue2Template.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
@SuppressWarnings("unchecked")
public <T> VaultResponseSupport<T> get(String path, Class<T> responseType) {

	Assert.hasText(path, "Path must not be empty");
	Assert.notNull(responseType, "Response type must not be null");

	return doRead(path, responseType, (response, data) -> {

		VaultResponseSupport result = response;
		result.setData(data);
		return result;
	});
}
 
Example #14
Source File: VaultKeyValueMetadataTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public VaultMetadataResponse get(String path) {

	VaultResponseSupport<Map> response = this.vaultOperations.read(getPath(path), Map.class);

	return response != null ? fromMap(response.getRequiredData()) : null;
}
 
Example #15
Source File: VaultVersionedKeyValueTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Nullable
private <T> Versioned<T> doRead(String path, Version version, Class<T> responseType) {

	String secretPath = version.isVersioned()
			? String.format("%s?version=%d", createDataPath(path), version.getVersion()) : createDataPath(path);

	VersionedResponse response = this.vaultOperations.doWithSession(restOperations -> {

		try {
			return restOperations.exchange(secretPath, HttpMethod.GET, null, VersionedResponse.class).getBody();
		}
		catch (HttpStatusCodeException e) {

			if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
				if (e.getResponseBodyAsString().contains("deletion_time")) {

					return VaultResponses.unwrap(e.getResponseBodyAsString(), VersionedResponse.class);
				}

				return null;
			}

			throw VaultResponses.buildException(e, path);
		}
	});

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

	VaultResponseSupport<JsonNode> data = response.getRequiredData();
	Metadata metadata = getMetadata(data.getMetadata());

	T body = deserialize(data.getRequiredData(), responseType);

	return Versioned.create(body, metadata);
}
 
Example #16
Source File: VaultApp.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

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

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

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

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

		vaultTemplate.delete("secret/myapp");
	}
 
Example #17
Source File: SecretLeaseContainer.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
private static boolean isRotatingGenericSecret(RequestedSecret requestedSecret,
		VaultResponseSupport<Map<String, Object>> secrets) {

	return Mode.ROTATE.equals(requestedSecret.getMode()) && !secrets.isRenewable()
			&& secrets.getLeaseDuration() > 0;
}
 
Example #18
Source File: VaultKeyValue2Accessor.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
JsonNode getJsonNode(VaultResponseSupport<JsonNode> response) {
	return response.getRequiredData().at("/data");
}
 
Example #19
Source File: CredentialsService.java    From tutorials with MIT License 4 votes vote down vote up
/**
 * To Retrieve Credentials
 * @return Credentials
 * @throws URISyntaxException
 */
public Credentials accessCredentials() throws URISyntaxException {

    VaultResponseSupport<Credentials> response = vaultTemplate.read("credentials/myapp", Credentials.class);
    return response.getData();
}
 
Example #20
Source File: VaultKeyValueAccessor.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
/**
 * Read a secret at {@code path} and deserialize the {@literal data} element to the
 * given {@link Class type}.
 * @param path must not be {@literal null}.
 * @param deserializeAs must not be {@literal null}.
 * @param mappingFunction Mapping function to convert from the intermediate to the
 * target data type. Must not be {@literal null}.
 * @param <I> intermediate data type for {@literal data} deserialization.
 * @param <T> return type. Value is created by the {@code mappingFunction}.
 * @return mapped value.
 */
@Nullable
<I, T> T doRead(String path, Class<I> deserializeAs, BiFunction<VaultResponseSupport<?>, I, T> mappingFunction) {

	ParameterizedTypeReference<VaultResponseSupport<JsonNode>> ref = VaultResponses
			.getTypeReference(JsonNode.class);

	VaultResponseSupport<JsonNode> response = doRead(createDataPath(path), ref);

	if (response != null) {

		JsonNode jsonNode = getJsonNode(response);

		return mappingFunction.apply(response, deserialize(jsonNode, deserializeAs));
	}

	return null;
}
 
Example #21
Source File: VaultKeyValue1Template.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@Override
JsonNode getJsonNode(VaultResponseSupport<JsonNode> response) {
	return response.getRequiredData();
}
 
Example #22
Source File: ReactiveVaultTemplate.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
@Override
public <T> Mono<VaultResponseSupport<T>> read(String path, Class<T> responseType) {

	return doWithSession(webClient -> {

		ParameterizedTypeReference<VaultResponseSupport<T>> ref = VaultResponses.getTypeReference(responseType);

		return webClient.get().uri(path).exchange().flatMap(mapResponse(ref, path, HttpMethod.GET));
	});
}
 
Example #23
Source File: VaultWrappingTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
@Test
void shouldReadWrappedTypedSecret() {

	Map<String, String> map = Collections.singletonMap("key", "value");

	WrappedMetadata metadata = this.wrappingOperations.wrap(map, Duration.ofSeconds(100));
	VaultResponseSupport<Secret> response = this.wrappingOperations.read(metadata.getToken(), Secret.class);

	assertThat(response.getRequiredData()).isEqualTo(new Secret("value"));
}
 
Example #24
Source File: VaultOperations.java    From spring-vault with Apache License 2.0 2 votes vote down vote up
/**
 * Read from a secret backend. Reading data using this method is suitable for secret
 * backends that do not require a request body.
 * @param path must not be {@literal null}.
 * @param responseType must not be {@literal null}.
 * @return the data. May be {@literal null} if the path does not exist.
 */
@Nullable
<T> VaultResponseSupport<T> read(String path, Class<T> responseType);
 
Example #25
Source File: ReactiveVaultOperations.java    From spring-vault with Apache License 2.0 2 votes vote down vote up
/**
 * Read from a Vault path. Reading data using this method is suitable for API
 * calls/secret backends that do not require a request body.
 * @param path must not be {@literal null}.
 * @param responseType must not be {@literal null}.
 * @return the data. May be empty if the path does not exist.
 */
<T> Mono<VaultResponseSupport<T>> read(String path, Class<T> responseType);
 
Example #26
Source File: VaultKeyValueAccessor.java    From spring-vault with Apache License 2.0 2 votes vote down vote up
/**
 * Return the {@link JsonNode} that contains the actual response body.
 * @param response
 * @return
 */
abstract JsonNode getJsonNode(VaultResponseSupport<JsonNode> response);
 
Example #27
Source File: VaultKeyValueOperations.java    From spring-vault with Apache License 2.0 2 votes vote down vote up
/**
 * Read the secret at {@code path}.
 * @param path must not be {@literal null}.
 * @param responseType must not be {@literal null}.
 * @return the data. May be {@literal null} if the path does not exist.
 */
@Nullable
<T> VaultResponseSupport<T> get(String path, Class<T> responseType);
 
Example #28
Source File: VaultWrappingOperations.java    From spring-vault with Apache License 2.0 2 votes vote down vote up
/**
 * Read a wrapped secret of type {@link Class responseType}.
 * @param token must not be {@literal null}.
 * @param responseType must not be {@literal null}.
 * @return the data or {@literal null} if the token was invalid or expired.
 */
@Nullable
<T> VaultResponseSupport<T> read(VaultToken token, Class<T> responseType);