Spring Cloud Vault

repository·main·Indexed 43 days ago

https://github.com/spring-cloud/spring-cloud-vault

Integrates HashiCorp Vault into the Spring Environment, providing a seamless way for Spring applications to retrieve secrets and configuration. It supports various authentication methods including Token, AppId, AppRole, AWS-EC2, AWS-IAM, Azure MSI, TLS certificates, Cubbyhole, and GCP-GCE/IAM. Features include lease and session token lifecycle management, Vault Enterprise namespace support, service discovery integration, and configurable SSL settings.

Tokens
13.6K
Snippets
49
Records
63
Agent score
53%

What's inside Spring Cloud Vault

  1. Overview of Spring Cloud Vault

    main

    Spring Cloud Vault Config provides client-side support for externalized configuration in distributed systems. It is built on top of Spring Vault and integrates with HashiCorp's Vault to provide a central location for managing external secret properties across all environments.

    Key capabilities include:

    • Managing static and dynamic secrets (e.g., usernames/passwords for remote applications).
    • Providing credentials for external services such as MySQL, PostgreSQL, Apache Cassandra, Couchbase, MongoDB, Consul, AWS, and more.
  2. Spring Cloud Vault Config Client Features

    main

    The Spring Cloud Vault Config Client is designed for Spring applications to integrate with HashiCorp Vault. Its primary capabilities include:

    • Secret Retrieval: Automatically retrieves secrets from Vault and initializes the Spring Environment with remote property sources.
    • Key-Value Support: Obtains Key-Value secrets secured with SSL.
    • Dynamic Credential Generation: Generates credentials for various data stores and services, including:
      • MySQL
      • PostgreSQL
      • Apache Cassandra
      • MongoDB
      • Consul
      • AWS
      • RabbitMQ
    • Authentication Support: Supports multiple authentication methods:
      • Token
      • AppId
      • AppRole
      • Client Certificate
      • Cubbyhole
      • AWS-EC2
      • AWS-IAM
      • Kubernetes
    • Context Bootstrapping: Bootstraps the application context as a parent context for the main application.
  3. Features of Spring Cloud Vault Config Client

    main

    The spring-cloud-vault-config client is designed for Spring applications to integrate with HashiCorp Vault. Key capabilities include:

    • Secret Retrieval: Fetches secrets from Vault and initializes the Spring Environment with remote property sources.
    • Key-Value Secrets: Supports obtaining KV secrets secured with SSL.
    • Credential Generation: Automatically generates credentials for various data stores and services, including:
      • MySQL, PostgreSQL, Apache Cassandra, MongoDB
      • Consul, AWS, RabbitMQ
    • Authentication Support: Supports multiple authentication methods:
      • Token, AppId, AppRole, Client Certificate, Cubbyhole, AWS-EC2, AWS-IAM, and Kubernetes.
    • Bootstrap Support: Provides a parent context for the main application to initialize configuration during startup.
  4. Manage Session Token Lifecycle

    main

    A Vault session token (LoginToken) has a TTL and max TTL. Spring Cloud Vault manages this lifecycle by default using a SessionManager API.

    Behavior:

    • Lazy Login: Login is deferred until the first session-bound use of Vault.
    • Renewal: Spring Cloud Vault retains the token until expiry and re-logins to obtain a new token when needed.
    • Revocation: On application shutdown, the active session token is revoked.

    Configuration Keys (spring.cloud.vault.session.lifecycle):

    • enabled: Enables/disables session token renewal (default true).
    • refresh-before-expiry: The amount of time subtracted from the token expiry time to trigger a renewal. Defaults to 5s.
    • expiry-threshold: The minimum TTL duration to consider a token valid. Tokens with a shorter TTL are treated as expired. Defaults to 7s.

    Important: expiry-threshold should be greater than refresh-before-expiry to prevent token expiry.

    spring.cloud.vault:
        session.lifecycle:
            enabled: true
            refresh-before-expiry: 10s
            expiry-threshold: 20s
  5. Configure Vault ConfigData Locations

    main

    Spring Cloud Vault supports two types of configuration locations via spring.config.import:

    • vault://: The default location. It mounts property sources for all enabled secret backends. By default, it mounts the key-value backend at /secret/${spring.application.name} and adds profile-specific paths like /secret/${spring.application.name}/${profile}.
    • vault:///<context-path>: A contextual location. This allows you to specify exact paths to be mounted as unique PropertySource instances. This is useful for manual control over key-value backend mounting.

    You can mix default and contextual locations to control the order of property sources.

    spring.config.import: vault://my/path, vault://
  6. Configure Spring Cloud Vault Authentication

    main

    Spring Cloud Vault supports multiple authentication mechanisms. Use the spring.cloud.vault.authentication property to select the method. Common methods include:

    • token: Uses a static Vault token provided via spring.cloud.vault.token.
    • app-id: Uses the AppId authentication backend.
    • app-role: Uses the AppRole authentication backend.
    • aws-ec2: Uses AWS-EC2 authentication.
    • aws-iam: Uses AWS IAM authentication.
    • azure-msi: Uses Azure Managed Service Identity.
    • gcp-gce / gcp-iam: Uses Google Cloud authentication.
    • kubernetes: Uses Kubernetes service account tokens.
    • github: Uses GitHub personal access tokens.
    • ssl: Uses TLS certificate authentication.
  7. Implement a Custom Secret Backend

    main

    To integrate a non-standard backend, you must implement two interfaces and register them via Spring's spring.factories mechanism.

    1. org.springframework.cloud.vault.config.VaultSecretBackendDescriptor: This object holds the configuration data. It should be annotated with @ConfigurationProperties so Spring can materialize it from your configuration files.

    2. org.springframework.cloud.vault.config.SecretBackendMetadataFactory: This factory accepts a VaultSecretBackendDescriptor and produces a SecretBackendMetadata object. The metadata object contains the Vault context path, path variables for resolution, and the PropertyTransformer used to map Vault data into Spring properties.

  8. Conditionally enable/disable Vault Configuration

    main

    To allow an application to start even if Vault is unavailable or disabled, you can mark a Vault location as optional.

    • optional:vault:// (default location)
    • optional:vault:///<context-path> (contextual location)

    If spring.cloud.vault.enabled=false is set, optional locations are skipped. Additionally, Vault context paths that return an HTTP 404 are skipped by default, regardless of whether they are marked optional.

    spring.config.import: optional:vault://
  9. Manage Secret Lease Lifecycle

    main

    Vault secrets are associated with a lease (TTL). Spring Cloud Vault manages the lifecycle of these leases by default, including renewal and revocation.

    Behavior:

    • Renewal: Login tokens and secrets are scheduled for renewal just before the lease expires.
    • Revocation: On application shutdown, Spring Cloud Vault revokes obtained login tokens and renewable leases (e.g., database credentials).
    • Static Tokens: Note that static tokens are not renewed or revoked.

    Configuration Keys (spring.cloud.vault.config.lifecycle):

    • enabled: Enables/disables lease renewal and rotation (default true).
    • min-renewal: Minimum duration required before renewing a lease to prevent excessive renewal calls.
    • expiry-threshold: The period of time before expiry at which a lease is renewed.
    • lease-endpoints: Specifies the endpoints for renew/revoke. Use Legacy for Vault < 0.8 or SysLeases for later versions.
    • lease-strategy: Controls error handling on renewal. Options: DropOnError, RetainOnError, RetainOnIoError.
    spring.cloud.vault:
        config.lifecycle:
        	enabled: true
        	min-renewal: 10s
        	expiry-threshold: 1m
        	lease-endpoints: Legacy
  10. Configure Multiple Database Secret Backends

    main

    If an application connects to multiple databases of the same kind, use the spring.cloud.vault.databases.* namespace to define unique configurations for each.

    Important: You MUST configure unique username-property and password-property values for each database to avoid property shadowing.

    spring.cloud.vault:
        databases:
            primary:
                enabled: true
                role: readwrite
                backend: database
                username-property: spring.primary-datasource.username
                password-property: spring.primary-datasource.password
            other-database:
                enabled: true
                role: readonly
                backend: database
                username-property: spring.secondary-datasource.username
                password-property: spring.secondary-datasource.password
  11. Use prefixes to prevent property shadowing in Vault

    main

    If you are mounting multiple Vault paths that contain overlapping secret names, you can prevent shadowing by adding a prefix query parameter to the location string.

    Important: Prefixes are added as-is. To ensure a dot separates the prefix from the key name, include a trailing dot in the prefix value.

    spring.config.import: vault://my/path?prefix=foo., vault://my/other/path?prefix=bar.
    secret: ${foo.secret}
    other.secret: ${bar.secret}
  12. Start the Vault server

    main

    To start a Vault server using an in-memory storage backend and TLS, create a configuration file (e.g., vault.conf) and run the server command.

    Example vault.conf:

    backend "inmem" {
    }
    
    listener "tcp" {
      address = "0.0.0.0:8200"
      tls_cert_file = "work/ca/certs/localhost.cert.pem"
      tls_key_file = "work/ca/private/localhost.decrypted.key.pem"
    }
    
    disable_mlock = true

    Run the server with:

    $ vault server -config=vault.conf

    Note for testing: If you are running Spring Cloud Vault tests, leave Vault uninitialized. The tests will automatically initialize Vault and use the root token 00000000-0000-0000-0000-000000000000.