org.springframework.vault.support.Versioned Java Examples

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

	String key = UUID.randomUUID().toString();

	this.versionedOperations.put(key, Collections.singletonMap("key", "v1"));
	this.versionedOperations.put(key, Collections.singletonMap("key", "v2"));

	this.versionedOperations.delete(key);

	Versioned<Map<String, Object>> versioned = this.versionedOperations.get(key);

	assertThat(versioned.getData()).isNull();
	assertThat(versioned.getVersion()).isEqualTo(Version.from(2));
	assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse();
	assertThat(versioned.getRequiredMetadata().getDeletedAt()).isBetween(Instant.now().minusSeconds(60),
			Instant.now().plusSeconds(60));
}
 
Example #3
Source File: VaultVersionedKeyValueTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUndeleteVersion() {

	String key = UUID.randomUUID().toString();

	this.versionedOperations.put(key, Collections.singletonMap("key", "v1"));
	this.versionedOperations.put(key, Collections.singletonMap("key", "v2"));

	this.versionedOperations.delete(key, Version.from(2));
	this.versionedOperations.undelete(key, Version.from(2));

	Versioned<Map<String, Object>> versioned = this.versionedOperations.get(key);

	assertThat(versioned.getRequiredData()).isEqualTo(Collections.singletonMap("key", "v2"));
	assertThat(versioned.getVersion()).isEqualTo(Version.from(2));
	assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse();
	assertThat(versioned.getRequiredMetadata().getDeletedAt()).isNull();
}
 
Example #4
Source File: VaultVersionedKeyValueTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldDeleteIntermediateRecentVersion() {

	String key = UUID.randomUUID().toString();

	this.versionedOperations.put(key, Collections.singletonMap("key", "v1"));
	this.versionedOperations.put(key, Collections.singletonMap("key", "v2"));

	this.versionedOperations.delete(key, Version.from(1));

	Versioned<Map<String, Object>> versioned = this.versionedOperations.get(key, Version.from(1));

	assertThat(versioned.getData()).isNull();
	assertThat(versioned.getVersion()).isEqualTo(Version.from(1));
	assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse();
	assertThat(versioned.getRequiredMetadata().getDeletedAt()).isBetween(Instant.now().minusSeconds(60),
			Instant.now().plusSeconds(60));
}
 
Example #5
Source File: VaultVersionedKeyValueTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldDestroyVersion() {

	String key = UUID.randomUUID().toString();

	this.versionedOperations.put(key, Collections.singletonMap("key", "v1"));
	this.versionedOperations.put(key, Collections.singletonMap("key", "v2"));

	this.versionedOperations.destroy(key, Version.from(2));

	Versioned<Map<String, Object>> versioned = this.versionedOperations.get(key);

	assertThat(versioned.getData()).isNull();
	assertThat(versioned.getVersion()).isEqualTo(Version.from(2));
	assertThat(versioned.getRequiredMetadata().isDestroyed()).isTrue();
	assertThat(versioned.getRequiredMetadata().getDeletedAt()).isNull();
}
 
Example #6
Source File: VaultKeyValueMetadataTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReadMetadataForANewKVEntry() {

	VaultMetadataResponse metadataResponse = this.vaultKeyValueMetadataOperations.get(SECRET_NAME);

	assertThat(metadataResponse.getMaxVersions()).isEqualTo(0);
	assertThat(metadataResponse.getCurrentVersion()).isEqualTo(1);
	assertThat(metadataResponse.getVersions()).hasSize(1);
	assertThat(metadataResponse.isCasRequired()).isFalse();
	assertThat(metadataResponse.getCreatedTime().isBefore(Instant.now())).isTrue();
	assertThat(metadataResponse.getUpdatedTime().isBefore(Instant.now())).isTrue();

	Versioned.Metadata version1 = metadataResponse.getVersions().get(0);

	if (prepare().getVersion().isGreaterThanOrEqualTo(Version.parse("1.2.0"))) {

		assertThat(metadataResponse.getDeleteVersionAfter()).isEqualTo(Duration.ZERO);

		assertThat(version1.getDeletedAt()).isNull();
		assertThat(version1.getCreatedAt()).isBefore(Instant.now());
	}

	assertThat(version1.getVersion().getVersion()).isEqualTo(1);
}
 
Example #7
Source File: HashicorpKeyVaultServiceTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void getSecretThrowsExceptionIfValueNotFoundForGivenId() {
    HashicorpGetSecretData getSecretData = new HashicorpGetSecretData("engine", "secretName", "id", 0);

    Versioned versionedResponse = mock(Versioned.class);
    when(versionedResponse.hasData()).thenReturn(true);

    Map responseData = mock(Map.class);
    when(versionedResponse.getData()).thenReturn(responseData);
    when(responseData.containsKey("id")).thenReturn(false);

    when(delegate.get(getSecretData)).thenReturn(versionedResponse);

    Throwable ex = catchThrowable(() -> keyVaultService.getSecret(getSecretData));

    assertThat(ex).isExactlyInstanceOf(HashicorpVaultException.class);
    assertThat(ex).hasMessage("No value with id id found at engine/secretName");
}
 
Example #8
Source File: HashicorpKeyVaultServiceTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void getSecret() {
    HashicorpGetSecretData getSecretData = mock(HashicorpGetSecretData.class);

    when(getSecretData.getSecretEngineName()).thenReturn("secretEngine");
    when(getSecretData.getSecretName()).thenReturn("secretName");
    when(getSecretData.getValueId()).thenReturn("keyId");

    Versioned versionedResponse = mock(Versioned.class);

    when(delegate.get(any(HashicorpGetSecretData.class))).thenReturn(versionedResponse);

    when(versionedResponse.hasData()).thenReturn(true);

    Map responseData = mock(Map.class);
    when(versionedResponse.getData()).thenReturn(responseData);
    when(responseData.containsKey("keyId")).thenReturn(true);
    String keyValue = "keyvalue";
    when(responseData.get("keyId")).thenReturn(keyValue);

    String result = keyVaultService.getSecret(getSecretData);

    assertThat(result).isEqualTo(keyValue);
}
 
Example #9
Source File: HashicorpKeyVaultService.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Override
public String getSecret(HashicorpGetSecretData hashicorpGetSecretData) {
    KeyValueOperationsDelegate keyValueOperationsDelegate = keyValueOperationsDelegateFactory.create(hashicorpGetSecretData.getSecretEngineName());

    Versioned<Map<String, Object>> versionedResponse = keyValueOperationsDelegate.get(hashicorpGetSecretData);

    if (versionedResponse == null || !versionedResponse.hasData()) {
        throw new HashicorpVaultException("No data found at " + hashicorpGetSecretData.getSecretEngineName() + "/" + hashicorpGetSecretData.getSecretName());
    }

    if (!versionedResponse.getData().containsKey(hashicorpGetSecretData.getValueId())) {
        throw new HashicorpVaultException("No value with id " + hashicorpGetSecretData.getValueId() + " found at " + hashicorpGetSecretData.getSecretEngineName() + "/" + hashicorpGetSecretData.getSecretName());
    }

    return versionedResponse.getData().get(hashicorpGetSecretData.getValueId()).toString();
}
 
Example #10
Source File: KeyValueOperationsDelegateTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void get() {
    String secretName = "secretName";

    HashicorpGetSecretData getSecretData = mock(HashicorpGetSecretData.class);
    when(getSecretData.getSecretName()).thenReturn(secretName);
    when(getSecretData.getSecretVersion()).thenReturn(0);

    Versioned versionedResponse = mock(Versioned.class);
    when(keyValueOperations.get(secretName, Versioned.Version.from(0))).thenReturn(versionedResponse);

    Versioned result = delegate.get(getSecretData);

    verify(keyValueOperations).get(secretName, Versioned.Version.unversioned());

    assertThat(result).isEqualTo(versionedResponse);
}
 
Example #11
Source File: KeyValueOperationsDelegateTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void set() {
    String secretName = "secretName";

    HashicorpSetSecretData setSecretData = mock(HashicorpSetSecretData.class);
    when(setSecretData.getSecretName()).thenReturn(secretName);
    Map nameValuePairs = mock(Map.class);
    when(setSecretData.getNameValuePairs()).thenReturn(nameValuePairs);

    Versioned.Metadata metadata = mock(Versioned.Metadata.class);
    when(keyValueOperations.put(secretName, nameValuePairs)).thenReturn(metadata);

    Versioned.Metadata result = delegate.set(setSecretData);

    verify(keyValueOperations).put(secretName, nameValuePairs);

    assertThat(result).isEqualTo(metadata);
}
 
Example #12
Source File: HashicorpVaultAliasService.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public char[] getPasswordFromAliasForCluster(String clusterName, String alias) throws AliasServiceException {
  try {
    Versioned<Map<String, Object>> mapVersioned = vault.get(getPath(clusterName, alias));
    if(mapVersioned != null && mapVersioned.hasData()) {
      Map<String, Object> data = mapVersioned.getData();
      if(data != null && data.containsKey(KEY)) {
        return String.valueOf(data.get(KEY)).toCharArray();
      }
    }
    return null;
  } catch (VaultException e) {
    throw new AliasServiceException(e);
  }
}
 
Example #13
Source File: VaultKvV2Engine.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
@Cacheable(cacheNames = "vaultCache")
public String get(@NotNull String secret) {
    return Optional.ofNullable(convertToVaultSecret(secret)).map(s -> {
        Versioned<Map<String, Object>> response = template.opsForVersionedKeyValue(s.getEnginePath()).get(s.getPath());
        return response != null && response.getData() != null ? String.valueOf(response.getData().get("secret")) : null;
    }).orElse(null);
}
 
Example #14
Source File: VaultVersionedKeyValueTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldCreateVersionedWithCAS() {

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

	String key = UUID.randomUUID().toString();

	this.versionedOperations.put(key, Versioned.create(secret, Version.unversioned()));

	// this should fail
	assertThatThrownBy(() -> this.versionedOperations.put(key, Versioned.create(secret, Version.unversioned())))
			.isExactlyInstanceOf(VaultException.class)
			.hasMessageContaining("check-and-set parameter did not match the current version");
}
 
Example #15
Source File: VaultVersionedKeyValueTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldCreateComplexVersionedSecret() {

	Person person = new Person();
	person.setFirstname("Walter");
	person.setLastname("White");

	String key = UUID.randomUUID().toString();
	this.versionedOperations.put(key, Versioned.create(person));

	Versioned<Person> versioned = this.versionedOperations.get(key, Person.class);

	assertThat(versioned.getRequiredData()).isEqualTo(person);
}
 
Example #16
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 #17
Source File: HashicorpKeyVaultServiceTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void getSecretThrowsExceptionIfNoDataRetrievedFromVault() {
    HashicorpGetSecretData getSecretData = new HashicorpGetSecretData("engine", "secretName", "id", 0);

    Versioned versionedResponse = mock(Versioned.class);
    when(versionedResponse.hasData()).thenReturn(false);

    when(delegate.get(getSecretData)).thenReturn(versionedResponse);

    Throwable ex = catchThrowable(() -> keyVaultService.getSecret(getSecretData));

    assertThat(ex).isExactlyInstanceOf(HashicorpVaultException.class);
    assertThat(ex).hasMessage("No data found at engine/secretName");
}
 
Example #18
Source File: VaultKeyValueMetadataTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static Versioned.Metadata buildVersion(String version, Map<String, Object> versionData) {

		Instant createdTime = toInstant((String) versionData.get("created_time"));
		Instant deletionTime = toInstant((String) versionData.get("deletion_time"));
		boolean destroyed = (Boolean) versionData.get("destroyed");
		Versioned.Version kvVersion = Versioned.Version.from(Integer.parseInt(version));

		return Versioned.Metadata.builder().createdAt(createdTime).deletedAt(deletionTime).destroyed(destroyed)
				.version(kvVersion).build();
	}
 
Example #19
Source File: VaultKvV2Engine.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isExists(String secret) {
    return Optional.ofNullable(convertToVaultSecret(secret)).map(s -> {
        Versioned<Map<String, Object>> response = template.opsForVersionedKeyValue(s.getEnginePath()).get(s.getPath());
        return response != null && response.getData() != null;
    }).orElse(false);
}
 
Example #20
Source File: VaultVersionedKeyValueTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
public Metadata put(String path, Object body) {

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

	Map<Object, Object> data = new LinkedHashMap<>();
	Map<Object, Object> requestOptions = new LinkedHashMap<>();

	if (body instanceof Versioned) {

		Versioned<?> versioned = (Versioned<?>) body;

		data.put("data", versioned.getData());
		data.put("options", requestOptions);

		requestOptions.put("cas", versioned.getVersion().getVersion());
	}
	else {
		data.put("data", body);
	}

	VaultResponse response = doWrite(createDataPath(path), data);

	if (response == null) {
		throw new IllegalStateException(
				"VaultVersionedKeyValueOperations cannot be used with a Key-Value version 1 mount");
	}

	return getMetadata(response.getRequiredData());
}
 
Example #21
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 #22
Source File: VaultVersionedKeyValueTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public <T> Versioned<T> get(String path, Version version, Class<T> responseType) {

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

	return doRead(path, version, responseType);
}
 
Example #23
Source File: VaultVersionedKeyValueTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
@SuppressWarnings("unchecked")
public Versioned<Map<String, Object>> get(String path, Version version) {

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

	return (Versioned) doRead(path, version, Map.class);
}
 
Example #24
Source File: HashicorpKeyVaultServiceTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void setSecretReturnsMetadataObject() {
    HashicorpSetSecretData setSecretData = new HashicorpSetSecretData("engine", "name", Collections.emptyMap());

    Versioned.Metadata metadata = mock(Versioned.Metadata.class);
    when(delegate.set(setSecretData)).thenReturn(metadata);

    Object result = keyVaultService.setSecret(setSecretData);

    assertThat(result).isInstanceOf(Versioned.Metadata.class);
    assertThat(result).isEqualTo(metadata);
}
 
Example #25
Source File: KeyValueOperationsDelegate.java    From tessera with Apache License 2.0 4 votes vote down vote up
Versioned<Map<String, Object>> get(HashicorpGetSecretData getSecretData) {
    //if version 0 then latest version retrieved
    return keyValueOperations.get(getSecretData.getSecretName(), Versioned.Version.from(getSecretData.getSecretVersion()));
}
 
Example #26
Source File: VaultKeyValueMetadataTemplate.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
private static List<Versioned.Metadata> buildVersions(Map<String, Map<String, Object>> versions) {

		return versions.entrySet().stream().map(entry -> buildVersion(entry.getKey(), entry.getValue()))
				.collect(Collectors.toList());
	}
 
Example #27
Source File: KeyValueOperationsDelegate.java    From tessera with Apache License 2.0 4 votes vote down vote up
Versioned.Metadata set(HashicorpSetSecretData setSecretData) {
    return keyValueOperations.put(setSecretData.getSecretName(), setSecretData.getNameValuePairs());
}
 
Example #28
Source File: VaultVersionedKeyValueTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
@Test
void shouldReadAndWriteVersionedSecret() {

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

	String key = UUID.randomUUID().toString();

	this.versionedOperations.put(key, Versioned.create(secret));

	Versioned<Map<String, Object>> loaded = this.versionedOperations.get(key);

	assertThat(loaded.getRequiredData()).isEqualTo(secret);
	assertThat(loaded.getRequiredMetadata()).isNotNull();
	assertThat(loaded.getVersion()).isEqualTo(Version.from(1));
}
 
Example #29
Source File: VaultVersionedKeyValueTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
@Test
void shouldCreateVersionedSecret() {

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

	String key = UUID.randomUUID().toString();

	Metadata metadata = this.versionedOperations.put(key, Versioned.create(secret));

	assertThat(metadata.isDestroyed()).isFalse();
	assertThat(metadata.getCreatedAt()).isBetween(Instant.now().minusSeconds(60), Instant.now().plusSeconds(60));
	assertThat(metadata.getDeletedAt()).isNull();
}
 
Example #30
Source File: VaultVersionedKeyValueOperations.java    From spring-vault with Apache License 2.0 2 votes vote down vote up
/**
 * Read the requested {@link Version} of the secret at {@code path} and deserialize
 * the secret to the given {@link Class responseType}.
 * @param path must not be {@literal null}.
 * @param version 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> Versioned<T> get(String path, Version version, Class<T> responseType);