Class VaultClient

java.lang.Object
codes.grow.packages.vault.VaultClient
All Implemented Interfaces:
AutoCloseable

public final class VaultClient extends Object implements AutoCloseable
Client for Vault.

Implements SPEC section 2.4 plus the Vault modules: auth(), kv(), transit(), database(), leases(), pki(), sys(), wrapping() and the SecretsProvider secrets(); withNamespace(String) returns a view in a Vault Enterprise namespace. Thread-safe; create one per endpoint and close it when done.


 try (VaultClient client = VaultClient.fromEnv()) {   // VAULT_ADDR / VAULT_TOKEN / GROW_HASHICORP_VAULT_*
   client.kv().write("app/db", Map.of("password", "s3cret"));
   KvSecret secret = client.kv().read("app/db");
 }
 

Every I/O method has a blocking form and an ...Async form returning CompletableFuture.

  • Method Details

    • create

      public static VaultClient create(VaultConfig config)
      Creates a client.
      Parameters:
      config - validated configuration
      Returns:
      a new client
      Throws:
      ConfigException - when TLS or proxy settings are invalid
    • fromEnv

      public static VaultClient fromEnv()
      Creates a client from the SDK and vendor environment variables (GROW_HASHICORP_VAULT_* then VAULT_*).
      Returns:
      a new client
    • builder

      public static VaultClient.Builder builder()
      Starts a client builder.
      Returns:
      a new builder
    • config

      public VaultConfig config()
      Returns the configuration.
      Returns:
      the configuration
    • transport

      public HttpTransport transport()
      Returns the HTTP transport, for modules built on this client.
      Returns:
      the transport
    • token

      public Optional<Secret> token()
      Returns the current client token (from the config, a login or setToken(codes.grow.packages.vault.core.Secret)).
      Returns:
      the token, or empty
    • setToken

      public void setToken(Secret token)
      Replaces the client token.
      Parameters:
      token - the new token, or null to send none
    • setToken

      public void setToken(String token)
      Replaces the client token.
      Parameters:
      token - the new token, or null to send none
    • register

      public void register(AutoCloseable resource)
      Registers a resource (watcher, renewer, provider) closed with the client.
      Parameters:
      resource - the resource
    • namespace

      public Optional<String> namespace()
      Returns the namespace sent as X-Vault-Namespace.
      Returns:
      the namespace, or empty for the root namespace
    • withNamespace

      public VaultClient withNamespace(String ns)
      Returns a view of this client whose requests carry X-Vault-Namespace: <ns> ("" = the root namespace, no header; surrounding slashes are removed). The view shares the connection pool and starts with this client's current token; logins, token changes, KV version detection, renewers and watchers of the view do not affect this client, which stays unchanged. Closing the view stops its own renewers, leases and watchers; closing this client also closes every view.

      Vault Enterprise only. Vault OSS silently ignores the header and serves the root namespace, so on OSS a view reads and writes the root namespace and a wrong namespace is not detected.

      
       VaultClient team = client.withNamespace("team-a");
       team.kv().read("app/db");   // X-Vault-Namespace: team-a
       
      Parameters:
      ns - namespace path, e.g. team-a or team-a/child
      Returns:
      the view
      Throws:
      ValidationException - when ns is null or this client is closed
      ConfigException - when ns contains whitespace
    • auth

      public Auth auth()
      Logins, token self-service and token renewal.
      Returns:
      the auth module
    • sys

      public Sys sys()
      System backend (health, seal status, policies, mounts, auth methods, AppRole admin).
      Returns:
      the sys module
    • wrapping

      public Wrapping wrapping()
      Response wrapping.
      Returns:
      the wrapping module
    • leases

      public LeaseManager leases()
      Lease renew / revoke / lookup and automatic lease renewal.
      Returns:
      the lease manager
    • kv

      public KvMount kv()
      The default KV mount (VaultConfig.kvMount()) with auto-detected version.
      Returns:
      the mount
    • kv

      public KvMount kv(String mount)
      A KV mount with auto-detected version; the same instance is returned for the same mount.
      Parameters:
      mount - mount path
      Returns:
      the mount
    • kvV1

      public KvV1 kvV1(String mount)
      A KV version 1 mount (no detection).
      Parameters:
      mount - mount path
      Returns:
      the mount
    • kvV2

      public KvV2 kvV2(String mount)
      A KV version 2 mount (no detection).
      Parameters:
      mount - mount path
      Returns:
      the mount
    • transit

      public Transit transit()
      The transit engine on mount transit.
      Returns:
      the transit module
    • transit

      public Transit transit(String mount)
      The transit engine on a mount.
      Parameters:
      mount - mount path
      Returns:
      the transit module
    • database

      public Database database()
      The database engine on mount database.
      Returns:
      the database module
    • database

      public Database database(String mount)
      The database engine on a mount.
      Parameters:
      mount - mount path
      Returns:
      the database module
    • pki

      public Pki pki()
      The PKI engine on mount pki.
      Returns:
      the PKI module
    • pki

      public Pki pki(String mount)
      The PKI engine on a mount.
      Parameters:
      mount - mount path
      Returns:
      the PKI module
    • secrets

      public VaultSecretsProvider secrets()
      SecretsProvider over the default KV mount. close() stops its watchers.
      Returns:
      the provider
    • secrets

      public VaultSecretsProvider secrets(SecretsOptions options)
      SecretsProvider over a KV mount and base path.
      Parameters:
      options - mount, base path, value field
      Returns:
      the provider
    • request

      public RawResponse request(String method, String path, Object body)
      Calls any Vault API path (/v1/<path>) with the client token, namespace, retries and error mapping. Use it for endpoints this SDK has no method for.
      Parameters:
      method - HTTP method (GET, POST, PUT, DELETE, LIST is sent as GET ?list=true)
      path - path below /v1/ (each segment is percent-encoded)
      body - JSON body, may be null
      Returns:
      the decoded envelope
    • requestAsync

      public CompletableFuture<RawResponse> requestAsync(String method, String path, Object body)
      Parameters:
      method - HTTP method
      path - path below /v1/
      body - JSON body, may be null
      Returns:
      a future with the decoded envelope
    • health

      public HealthStatus health()
      Unauthenticated health (GET /v1/sys/health, answers 200 in every node state). healthy is true only for an active, unsealed node; status is active, standby, perfstandby, sealed or uninitialized (unreachable on errors). Never throws except for cancellation and configuration errors.
      Returns:
      the health status
      Throws:
      CancelledException - when interrupted or closed
    • healthAsync

      public CompletableFuture<HealthStatus> healthAsync()
      Asynchronous health().
      Returns:
      a future with the health status
    • ping

      public Duration ping()
      Authenticated round trip (GET /v1/auth/token/lookup-self, allowed for every valid token).
      Returns:
      the latency
      Throws:
      AuthenticationException - on a missing, invalid or revoked token
    • pingAsync

      public CompletableFuture<Duration> pingAsync()
      Asynchronous ping().
      Returns:
      a future with the latency
    • serverVersion

      public String serverVersion()
      Returns the server version from sys/health (e.g. 2.2.2).
      Returns:
      the version string
      Throws:
      UnsupportedException - when the server reports none
    • serverVersionAsync

      public CompletableFuture<String> serverVersionAsync()
      Asynchronous serverVersion().
      Returns:
      a future with the version
    • isClosed

      public boolean isClosed()
      Returns whether close() was called.
      Returns:
      true once closed
    • close

      public void close()
      Stops token renewers, managed leases (revoking those with revokeOnStop) and secret watchers, then releases the transport. Idempotent.
      Specified by:
      close in interface AutoCloseable
    • toString

      public String toString()
      Overrides:
      toString in class Object