屬性源

Vault 可以透過多種不同方式使用。其中一種特定的用例是使用 Vault 儲存加密屬性。Spring Vault 支援將 Vault 作為屬性源,以便使用 Spring 的 PropertySource 抽象獲取配置屬性。

你可以在其他屬性源中引用儲存在 Vault 中的屬性,或者使用 @Value(…) 進行值注入。當引導需要儲存在 Vault 中的資料的 bean 時,需要特別注意。此時必須初始化一個 VaultPropertySource 以從 Vault 中檢索屬性。
Spring Boot/Spring Cloud 使用者可以受益於 Spring Cloud Vault 的配置整合,它在應用程式啟動期間初始化各種屬性源。

註冊 VaultPropertySource

Spring Vault 提供了一個 VaultPropertySource 與 Vault 一起使用以獲取屬性。它使用巢狀的 data 元素來暴露儲存在 Vault 中並加密的屬性。

ConfigurableApplicationContext ctx = new GenericApplicationContext();
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.addFirst(new VaultPropertySource(vaultTemplate, "secret/my-application"));

在上面的程式碼中,VaultPropertySource 已以最高優先順序新增到搜尋中。如果它包含一個 ´foo` 屬性,它將被檢測到並優先於任何其他 PropertySource 中的任何 foo 屬性返回。MutablePropertySources 暴露了許多方法,允許精確地操作屬性源集。

@VaultPropertySource

@VaultPropertySource 註解提供了一種方便且宣告性的機制,用於向 Spring 的 Environment 新增 PropertySource,以便與 @Configuration 類一起使用。

@VaultPropertySource 接受一個 Vault 路徑,例如 secret/my-application,並暴露儲存在該節點的資料作為 PropertySource@VaultPropertySource 支援與租約相關的 secrets(即 mysql 後端提供的憑據)的租約續期,並在租約到期時輪換憑據。租約續期預設停用。

示例 1. 儲存在 Vault 中的屬性
{
  // …

  "data": {
    "database": {
      "password": ...
    },
    "user.name": ...,
  }

  // …
}
示例 2. 宣告一個 @VaultPropertySource
@Configuration
@VaultPropertySource("secret/my-application")
public class AppConfig {

    @Autowired Environment env;

    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setUser(env.getProperty("user.name"));
        testBean.setPassword(env.getProperty("database.password"));
        return testBean;
    }
}
示例 3. 宣告一個帶有憑據輪換和字首的 @VaultPropertySource
@Configuration
@VaultPropertySource(value = "aws/creds/s3-access",
                     propertyNamePrefix = "aws.",
                     renewal = Renewal.ROTATE)
public class AppConfig {
  // provides aws.access_key and aws.secret_key properties
}
generic secret 後端獲得的 secrets 關聯有 TTL (refresh_interval),但沒有租約 ID。當通用 secrets 達到其 TTL 時,Spring Vault 的 PropertySource 會對其進行輪換。
你可以使用 @VaultPropertySource 從版本化 Key-Value 後端獲取最新的 secret 版本。請確保路徑中不包含 data/ 段。

@VaultPropertySource 路徑中存在的任何 ${…​} 佔位符都會根據已註冊到環境中的屬性源集進行解析,如下例所示

示例 4. 使用佔位符宣告 @VaultPropertySource 路徑
@Configuration
@VaultPropertySource(value = "aws/creds/${my.placeholder:fallback/value}",
                     propertyNamePrefix = "aws.",
                     renewal = Renewal.ROTATE)
public class AppConfig {
}

假設 my.placeholder 存在於已註冊的屬性源(例如,系統屬性或環境變數)之一中,佔位符將被解析為相應的值。如果不存在,則使用 fallback/value 作為預設值。如果未指定預設值且無法解析屬性,則會丟擲 IllegalArgumentException

在某些情況下,使用 @VaultPropertySource 註解時,可能無法或不方便嚴格控制屬性源的順序。例如,如果上面的 @Configuration 類是透過元件掃描註冊的,則順序難以預測。在這種情況下——以及如果覆蓋很重要——建議使用者回退到使用程式設計方式的 PropertySource API。有關詳細資訊,請參閱 ConfigurableEnvironmentMutablePropertySources