Skip to content

Hashicorp Vault Module

Testcontainers module for Vault. Vault is a tool for managing secrets. More information on Vault here.

Usage example

Start Vault container as a @ClassRule:

public static VaultContainer<?> vaultContainer = new VaultContainer<>("hashicorp/vault:1.13")
    .withVaultToken(VAULT_TOKEN)
    .withInitCommand(
        "secrets enable transit",
        "write -f transit/keys/my-key",
        "kv put secret/testing1 top_secret=password123",
        "kv put secret/testing2 secret_one=password1 secret_two=password2 secret_three=password3 secret_three=password3 secret_four=password4"
    );

Use CLI to read data from Vault container:

GenericContainer.ExecResult result = vaultContainer.execInContainer(
    "vault",
    "kv",
    "get",
    "-format=json",
    "secret/testing1"
);
assertThat(result.getStdout()).contains("password123");

Use Http API to read data from Vault container:

Response response = given()
    .header("X-Vault-Token", VAULT_TOKEN)
    .when()
    .get(vaultContainer.getHttpHostAddress() + "/v1/secret/data/testing1")
    .thenReturn();
assertThat(response.body().jsonPath().getString("data.data.top_secret")).isEqualTo("password123");

Use client library to read data from Vault container:

public void readFirstSecretPathOverClientLibrary() throws Exception {
    final VaultConfig config = new VaultConfig()
        .address(vaultContainer.getHttpHostAddress())
        .token(VAULT_TOKEN)
        .build();

    final Vault vault = new Vault(config);

    final Map<String, String> value = vault.logical().read("secret/testing1").getData();

    assertThat(value).containsEntry("top_secret", "password123");
}

See full example.

Why Vault in Junit tests?

With the increasing popularity of Vault and secret management, applications are now needing to source secrets from Vault. This can prove challenging in the development phase without a running Vault instance readily on hand. This library aims to solve your apps integration testing with Vault. You can also use it to test how your application behaves with Vault by writing different test scenarios in Junit.

Adding this module to your project dependencies

Add the following dependency to your pom.xml/build.gradle file:

testImplementation "org.testcontainers:vault:1.20.2"
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>vault</artifactId>
    <version>1.20.2</version>
    <scope>test</scope>
</dependency>

License

See LICENSE.

Copyright (c) 2017 Capital One Services, LLC and other authors.

See AUTHORS for contributors.